diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..0afa50a --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,48 @@ +name: CI + +on: + push: + branches: + - main + pull_request: + +concurrency: + group: ${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + verify: + runs-on: ubuntu-latest + env: + NEXT_TELEMETRY_DISABLED: 1 + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 20 + cache: npm + + - name: Install dependencies + run: npm ci + + - name: Build packages + run: npm run build:packages + + - name: Run tests + run: npm test + + - name: Type-check + run: npm run typecheck + + - name: Run linter + run: npm run lint + + - name: Build web-demo + run: npm run build -w apps/web-demo diff --git a/.gitignore b/.gitignore index 01ffa65..ebb51a6 100644 --- a/.gitignore +++ b/.gitignore @@ -19,6 +19,7 @@ npm-debug.log* yarn-debug.log* yarn-error.log* .pnpm-debug.log* +*.log # env files (can opt-in for committing if needed) .env* @@ -44,3 +45,6 @@ next-env.d.ts # Claude Code worktrees (prevent VS Code from indexing them) .claude/worktrees/ + +# build output de los paquetes — se regenera con npm run build:packages +packages/*/dist/ diff --git a/CLAUDE.md b/CLAUDE.md index a880b85..961bc90 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,6 +1,6 @@ # Point & Click Game Engine -**Versión**: 2.0-dev | **Estado**: Desarrollo activo | **Owner**: Daniel Martínez Sebastián +**Versión**: 0.6.0 | **Estado**: Desarrollo activo | **Owner**: Daniel Martínez Sebastián Librería agnóstica al framework para juegos point-and-click 2D/2.5D, con primera implementación en R3F. La demo R3F vive en `apps/web-demo/` dentro del monorepo para evaluar engine y demo en paralelo. @@ -23,9 +23,9 @@ Dos objetivos concurrentes que NO deben sabotearse mutuamente: ┌────────────────────────────────────────────┐ │ Presentación / UI (apps/web-demo) │ ← InventoryUI, Joystick, DebugOverlay ├────────────────────────────────────────────┤ -│ Renderer R3F (apps/web-demo) │ ← GameTouchCanvas, useFrame, Three.js +│ Renderer R3F (engine-renderer-r3f) │ ← GameViewport, hooks, useFrame, Three.js ├────────────────────────────────────────────┤ -│ Core (packages/engine-core) AGNÓSTICO │ ← state, rules, pathfinding, events +│ Core (packages/engine-core) AGNÓSTICO │ ← runtime, state, rules, pathfinding, events ├────────────────────────────────────────────┤ │ Platform Adapters (apps/web-demo) │ ← storage, clipboard, timer (web) └────────────────────────────────────────────┘ @@ -46,9 +46,10 @@ Dos objetivos concurrentes que NO deben sabotearse mutuamente: | Tipo | Ubicación | Ejemplos | |------|-----------|----------| -| **Core** (agnóstico) | `packages/engine-core/` | rules, sceneStore, findPath, types | -| **Renderer** (R3F) | `apps/web-demo/app/lib/engine/runtime/` y `/render/` | useFrame loops, Canvas, sprites | +| **Core** (agnóstico) | `packages/engine-core/src/` (runtime en `game/runtime/`) | createGameRuntime, rules, sceneStore, findPath, types | +| **Renderer** (R3F) | `packages/engine-renderer-r3f/src/` (`viewport/`, `hooks/`, `scene/`, `sprite/`) | GameViewport, useFrame loops, Canvas, sprites | | **UI** (React) | `apps/web-demo/app/components/` | Joystick, InventoryUI, panels | +| **Contenido y composición** (demo) | `apps/web-demo/demo-content/`, `apps/web-demo/app/lib/engine/runtime/` | escenas, ítems, opciones del viewport, puertas, editores | | **Platform** (web) | `apps/web-demo/app/lib/platform-web.ts` | localStorage, clipboard adapters | **Detalles**: `docs/architecture/03-rules-core-vs-render.md` @@ -57,11 +58,13 @@ Dos objetivos concurrentes que NO deben sabotearse mutuamente: ## API Pública (Contrato Estable) -Frontera pública en `apps/web-demo/app/lib/engine/publicApi.ts`. **No romper sin issue + migración**. +Vive en los paquetes: runtime en `packages/engine-core/src/game/runtime/`, viewport y hooks en `packages/engine-renderer-r3f/src/index.ts`. `apps/web-demo/app/lib/engine/publicApi.ts` es un barrel de compatibilidad que re-exporta ambos. **No romper sin issue + migración**. -Exporta: `createGameRuntime`, `registerScene`, `registerItem`, `registerRule`, `getGameState`, `getGameActions`, `getGameRuntime`, `useGameState`, `useGameActions`, `GameViewport`. +- `engine-core` exporta: `createGameRuntime`, `getGameRuntime`, `registerScene`, `registerItem`, `registerRule`, `getGameState`, `getGameActions`. +- `engine-renderer-r3f` exporta: `GameViewport`, `useGameViewportController`, `GameViewportView`, `useGameState`, `useGameActions`. +- El handle de `createGameRuntime` trae `executeCommand`, `on`, `emit`, `dispose`. -**Phase 4 añade** (via handle devuelto por `createGameRuntime`): `executeCommand`, `on`, `emit`, `dispose`. +Lista completa: `docs/LIBRARY_API_CONTRACT_V1.md`. **Detalles**: `docs/architecture/02-public-api.md` @@ -107,10 +110,12 @@ Ver: `docs/workflow/pre-commit-checklist.md` ## Versionado -- **v0.1.x**: Demo R3F funcional (actual) +- **v0.1.x**: Demo R3F funcional - **v0.2.x**: `engine-core` extraído del monorepo - **v0.3.x**: Renderer abstraction (interfaces agnósticas) - **v0.4.x**: Bidireccionalidad web ↔ juego +- **v0.5.x**: Runtime en los paquetes, `GameViewport` jugable +- **v0.6.x**: Narrativa declarativa: hotspots, NPCs, diálogos, guardado único (actual) - **v1.0.0**: Publicación en npm --- @@ -137,8 +142,6 @@ Ver: `docs/workflow/pre-commit-checklist.md` └── decisions/ # ADRs ligeros ``` -**Nota**: la estructura monorepo se materializa en Fase 2. Estado actual: app Next.js plana. - --- ## Documentos Clave @@ -153,7 +156,8 @@ Ver: `docs/workflow/pre-commit-checklist.md` | Delegar subagentes | `docs/workflow/how-to-spawn-subagent.md` | | Hacer commit | `docs/workflow/commit-convention.md` | | Decisiones tomadas | `docs/decisions/` (ADRs) | -| Fase activa | `docs/phases/phase-4-bidirectional-web-game/` | +| Escribir contenido (escenas, diálogos, ítems) | `docs/authoring/README.md` | +| Fase activa | `docs/phases/phase-18-story-demo/` | --- diff --git a/apps/web-demo/app/components/GameTouchCanvas.tsx b/apps/web-demo/app/components/GameTouchCanvas.tsx index 2a1b3e5..b5f682c 100644 --- a/apps/web-demo/app/components/GameTouchCanvas.tsx +++ b/apps/web-demo/app/components/GameTouchCanvas.tsx @@ -1,41 +1,34 @@ "use client"; -import { Suspense, useCallback, useEffect, useRef, useState } from "react"; -import { Canvas } from "@react-three/fiber"; -import { OrthographicCamera } from "@react-three/drei"; -import { Physics } from "@react-three/rapier"; - -import { PixelLoader } from "./PixelLoader"; +import { useCallback, useEffect, useState } from "react"; +import dynamic from "next/dynamic"; import { - type GameCharacterName, -} from "./sprite/clips"; -import dynamic from "next/dynamic"; + GameViewportView, + useGameViewportController, +} from "@pointclick-engine/engine-renderer-r3f"; +import { getGameRuntime, useSceneStore, type RuntimeEvent } from "@pointclick-engine/engine-core"; + +import { PixelLoader } from "./PixelLoader"; import { DraggedInventoryGhost, InventoryUI } from "./InventoryUI"; -import { SceneDropTargets } from "./inventory/SceneDropTargets"; -import { PlacedSceneItems } from "./inventory/PlacedSceneItems"; -import { SceneBackgroundPlane } from "./scene/SceneBackgroundPlane"; -import { CameraController, CameraFitHeight } from "./scene/SceneCameraControllers"; import { FreeCameraController } from "./scene/FreeCameraController"; import { SceneDoors } from "./scene/SceneDoors"; -import { SCENES } from "../../demo-content/scenes/scenes"; import { DebugOverlayRuntimePanel } from "./debug/DebugOverlayRuntimePanel"; -import { GameTouchSpriteRuntime, SceneTransitions } from "@pointclick-engine/engine-renderer-r3f"; -import { useInventoryRuntimeController } from "../lib/engine/runtime/useInventoryRuntimeController"; +import { SCENES } from "../../demo-content/scenes/scenes"; +import { getRandomPhrase } from "../../demo-content/dialogs/getRandomPhrase"; +import { DAVID } from "../../demo-content/characters/david"; +import { DEMO_NPC_CHARACTERS } from "../../demo-content/characters/guide"; +import type { GameRuntime } from "../lib/engine/publicApi"; +import { DEMO_VIEWPORT_OPTIONS } from "../lib/engine/runtime/demoViewportOptions"; +import { useDemoUiSounds } from "../lib/engine/runtime/useDemoAudio"; +import { useDemoSceneDebug } from "../lib/engine/runtime/useDemoSceneDebug"; +import { useDoorClickGoal, useDoorEventBridge } from "../lib/engine/runtime/useDoorSystem"; import { useInteractionEditorController } from "../lib/engine/runtime/useInteractionEditorController"; import { useDebugPanelController } from "../lib/engine/runtime/useDebugPanelController"; import { useDebugModeEffects } from "../lib/engine/runtime/useDebugModeEffects"; -import { useSceneRuntimeController } from "../lib/engine/runtime/useSceneRuntimeController"; -import { useDoorSystem } from "../lib/engine/runtime/useDoorSystem"; -import { useTransitionSystem } from "../lib/engine/runtime/useTransitionSystem"; import { useTransitionEditorController } from "../lib/engine/runtime/useTransitionEditorController"; -import { legacyRuntimeEventToGameEvent, type RuntimeEvent, type GameSceneTransition, type GameScene, useSceneStore } from "@pointclick-engine/engine-core"; -import { getGameRuntime } from "../lib/engine/publicApi"; -import { webAudioAdapter } from "../lib/platform-web-audio"; -import { audioSettingsStore } from "../store/audio"; import { useMobileInputStore } from "../store/mobileInputStore"; import { useSceneEditorStore } from "../store/sceneEditorStore"; -import { useDialogStore } from "../store/dialogStore"; import { useInventoryStore } from "../store/inventoryStore"; import { selectGameInteractionsDisabled, @@ -47,30 +40,23 @@ import { // táctil se realiza dentro del propio componente con window garantizado. const Joystick = dynamic(() => import("./Joystick"), { ssr: false }); -const CAMERA_POSITION: [number, number, number] = [0, 5.4, 25.0]; -const EMPTY_TRANSITIONS: GameSceneTransition[] = []; - type GameTouchCanvasProps = { + /** Runtime ya creado (page.tsx lo crea antes de montar el canvas). */ + runtime?: GameRuntime | null; debug?: boolean; onRuntimeEvent?: (event: RuntimeEvent) => void; }; /** - * Se monta dentro del Suspense del runtime — cuando este componente llega al - * DOM significa que useLoader ha resuelto todos los assets del personaje. - * Llama onReady una sola vez para señalizar al PixelLoader. + * Juego de la demo: el motor (`useGameViewportController` + `GameViewportView`, en el + * renderer) más lo propio de la demo: puertas, debug/editor, joystick, mochila, + * pantalla de carga y sonidos de UI. */ -function SceneReadyReporter({ onReady }: { onReady: () => void }) { - const onReadyRef = useRef(onReady); - useEffect(() => { onReadyRef.current(); }, []); // intentional: run once on mount - return null; -} - export default function GameTouchCanvas({ + runtime, debug: debugOverride, onRuntimeEvent, }: GameTouchCanvasProps = {}) { - const selectedCharacter: GameCharacterName = "Dave"; const [sceneReady, setSceneReady] = useState(false); const handleSceneReady = useCallback(() => setSceneReady(true), []); @@ -87,440 +73,163 @@ export default function GameTouchCanvas({ }; }, [runtimeDebug]); - const baseRuntimeEvent = useCallback((event: RuntimeEvent) => { - // Legacy callback (backwards compat) - onRuntimeEvent?.(event); - // Also emit to the bidirectional event bus (Phase 4) - const gameEvent = legacyRuntimeEventToGameEvent(event); - getGameRuntime()?.emit(gameEvent); - if (!runtimeDebug) return; - console.debug("[runtime-event]", event); - }, [onRuntimeEvent, runtimeDebug]); - - const { - isDebugGroundVisible, - setIsDebugGroundVisible, - isDebugWallsVisible, - setIsDebugWallsVisible, - wallToolMode, - wallPointResetSignal, - handleWallToolModeChange, - resetWallPointTool, - speechDraft, - setSpeechDraft, - speechCharsPerSecond, - setSpeechCharsPerSecond, - } = useDebugPanelController(); - const { - sceneId, - sceneBackground, - setScene, - sceneInteractions, - requestRespawn, - playerPosition, - scenePlayerSpawn, - updateInteraction, - resetInteractionsFromSceneConfig, - sceneOptions, - } = useSceneRuntimeController(); - - // Doors are demo-only data (not in engine-core's GameScene). Read them from - // the SCENES registry by current sceneId. The door event bridge wraps the - // base runtime handler so `onDrop`+`consume` events open matching doors. - const currentScene = SCENES[sceneId]; - const sceneDoors = currentScene?.doors ?? []; - - // ── Fade curtain for scene transitions ──────────────────────────────────── - // The overlay div is always in the DOM. We manipulate it directly (bypassing - // React state) so the curtain drops synchronously before any re-render with - // the new (backgroundless) scene data. - const fadeOverlayRef = useRef(null); + const debugPanel = useDebugPanelController(); - const handleBeforeSceneChange = useCallback(() => { - const el = fadeOverlayRef.current; - if (!el) return; - el.style.transition = "none"; - el.style.opacity = "1"; - el.style.pointerEvents = "all"; - }, []); - - const handleBackgroundReady = useCallback(() => { - const el = fadeOverlayRef.current; - if (!el || el.style.opacity !== "1") return; - // Force layout flush so the transition triggers on the next style change. - el.getBoundingClientRect(); - el.style.transition = "opacity 0.45s ease"; - el.style.opacity = "0"; - el.style.pointerEvents = "none"; - }, []); - - const { handleTransitionTriggered, wrapRuntimeEventForTransitions } = useTransitionSystem({ - onBeforeChange: handleBeforeSceneChange, - resolveScene: (id) => (SCENES[id] as GameScene | undefined) ?? null, + // Las puertas (demo) observan los eventos del runtime antes que el callback del host: + // un `consume` sobre la diana de una puerta la abre. + const doorSceneId = useSceneStore((s) => s.sceneId); + const handleHostRuntimeEvent = useDoorEventBridge({ + scene: SCENES[doorSceneId], + passthrough: onRuntimeEvent, }); - const afterDoorRuntimeEvent = useDoorSystem({ - scene: currentScene, - passthrough: baseRuntimeEvent, + // Estado de escena, inventario, transiciones, audio y cadena de eventos (renderer). + const controller = useGameViewportController({ + ...DEMO_VIEWPORT_OPTIONS, + runtime, + onRuntimeEvent: handleHostRuntimeEvent, + debug: runtimeDebug, }); + const { sceneId, playerPosition, scenePlayerSpawn, updateInteraction } = controller; + const { sceneOptions, setScene } = useDemoSceneDebug(controller.storeSetScene); - // Sync audio settings (already hydrated from localStorage at module load) - // to the webAudioAdapter on mount AND on every subsequent change. Without - // the initial apply the adapter starts at its defaults and ignores any - // persisted mute until the user toggles a setting. + // Las puertas son datos de la demo (no están en GameScene del core). + const currentScene = SCENES[sceneId]; + const getEffectiveClickGoal = useDoorClickGoal(currentScene); + const handleSpeechLetterSound = useDemoUiSounds(); + + // Soltar un ítem sobre OTRO slot ocupado los combina (`inventory:combine`). Con un slot vacío, + // el mismo ítem o la escena, la suelta sigue su camino de siempre. El arrastre no quita nada + // del inventario: si la combinación falla no se pierde ningún ítem. + const { draggedStack, inventorySlots, clearDrag, showSpeechBubble } = controller; + const handleDropOnSlot = useCallback( + (slotIndex: number): boolean => { + const target = inventorySlots[slotIndex]; + if (!draggedStack || !target) return false; + if (slotIndex === draggedStack.fromSlotIndex || target.id === draggedStack.stack.id) return false; + (runtime ?? getGameRuntime())?.executeCommand({ + type: "inventory:combine", + itemId: draggedStack.stack.id, + withItemId: target.id, + }); + clearDrag(); + return true; + }, + [clearDrag, draggedStack, inventorySlots, runtime], + ); + // Combinación imposible: la demo lo explica con una frase (los ítems siguen donde estaban). useEffect(() => { - const apply = (state: ReturnType) => { - webAudioAdapter.setMuted("master", state.masterMuted); - webAudioAdapter.setMuted("music", state.musicMuted); - webAudioAdapter.setMuted("sfx", state.sfxMuted); - webAudioAdapter.setVolume("master", state.masterVolume); - webAudioAdapter.setVolume("music", state.musicVolume); - webAudioAdapter.setVolume("sfx", state.sfxVolume); - }; - apply(audioSettingsStore.getState()); - return audioSettingsStore.subscribe(apply); - }, []); + const target = runtime ?? getGameRuntime(); + if (!target) return; + return target.on("item:combineFailed", () => { + showSpeechBubble(getRandomPhrase("inventoryCombineFailed"), { dialogKey: "inventoryCombineFailed" }); + }); + }, [runtime, showSpeechBubble]); - // Click sound for inventory toggle const isInventoryOpen = useInventoryStore((s) => s.isOpen); const toggleInventory = useInventoryStore((s) => s.toggle); - useEffect(() => { - webAudioAdapter.playSound({ - id: "click", - url: "/assets/audio/sfx/click.ogg", - category: "ui", - }); - }, [isInventoryOpen]); - - // Initialize audio system - listen to scene changes - const scene = useSceneStore((s) => s.scene); - useEffect(() => { - console.log("[audio] Scene changed:", scene.id, "music:", scene?.music); - if (scene?.music) { - console.log("[audio] Playing music:", scene.music.trackUrl); - webAudioAdapter.playMusic({ - id: scene.music.trackUrl, - url: scene.music.trackUrl, - category: "music", - loop: true, - }, { fadeMs: scene.music.fadeMs ?? 800 }); - } - }, [scene?.music?.trackUrl]); - - // Click sound on canvas for pathfinding - const playerWalkingState = useSceneStore((s) => s.playerWalkingState); - const prevWalkingRef = useRef(null); - useEffect(() => { - // Play click sound when walking starts (transition from null to walking state) - if (playerWalkingState && !prevWalkingRef.current) { - webAudioAdapter.playSound({ - id: "click-canvas", - url: "/assets/audio/sfx/click.ogg", - category: "ui", - }); - } - prevWalkingRef.current = playerWalkingState; - }, [playerWalkingState]); - - // Initialize SFX playback via event bus - useEffect(() => { - let unsubscribe: (() => void) | null = null; - - const trySubscribe = setInterval(() => { - const runtime = getGameRuntime(); - if (!runtime) return; - clearInterval(trySubscribe); - - const subs = [ - runtime.on("item:dropped", (event: any) => { - console.log("[audio] item:dropped -", JSON.stringify(event)); - // Differentiate by outcome: pickup-success = pickup sound, place = drop sound - const soundMap: Record = { - gameboy: { - pickup: "/assets/audio/sfx/pickup-gameboy.ogg", - drop: "/assets/audio/sfx/drop-default.ogg", - }, - default: { - pickup: "/assets/audio/sfx/pickup-default.ogg", - drop: "/assets/audio/sfx/drop-default.ogg", - }, - }; - - const itemSounds = soundMap[event.itemId] || soundMap.default; - - if (event.outcome === "pickup-success") { - webAudioAdapter.playSound({ - id: `pickup-${event.itemId}`, - url: itemSounds.pickup, - category: "sfx", - }); - } else if (event.outcome === "place") { - webAudioAdapter.playSound({ - id: `drop-${event.itemId}`, - url: itemSounds.drop, - category: "sfx", - }); - } - }), - runtime.on("transition:triggered", () => { - console.log("[audio] Playing transition sound"); - webAudioAdapter.playSound({ - id: "transition-default", - url: "/assets/audio/sfx/transition-default.ogg", - category: "sfx", - }); - }), - ]; - - unsubscribe = () => subs.forEach((u) => u?.()); - }, 50); - - return () => { - clearInterval(trySubscribe); - unsubscribe?.(); - }; - }, []); - - // Chain: door system → transition item-drop check - const handleRuntimeEvent = useCallback( - wrapRuntimeEventForTransitions(afterDoorRuntimeEvent.handleRuntimeEvent), - [wrapRuntimeEventForTransitions, afterDoorRuntimeEvent.handleRuntimeEvent], - ); - const { getEffectiveClickGoal } = afterDoorRuntimeEvent; - - // Dialog state lives in dialogStore (also writable via dialog:trigger / dialog:dismiss commands) - const speechText = useDialogStore((s) => s.text); - const speechVisible = useDialogStore((s) => s.visible); - const speechTrigger = useDialogStore((s) => s.triggerCount); - - const handleSpeechLetterSound = useCallback(() => { - const n = Math.floor(Math.random() * 4) + 1; - const url = `/assets/audio/sfx/speak (${n}).mp3`; - webAudioAdapter.playSound({ id: url, url, category: "sfx" }, { volume: 0.35 }); - }, []); - - // Get transitions from scene - const sceneTransitions = useSceneStore((s) => s.scene.transitions ?? EMPTY_TRANSITIONS); - - const { - inventorySlots, - draggedStack, - placedItems, - handleBoundaryHit, - showSpeechBubble, - hideSpeechBubble, - handleInteractionInspect, - handleInventoryDropHit, - handleInventoryDropMiss, - handleInventoryDropOnPlayer, - handlePickupPlacedItem, - updatePlacedItemPosition, - movePlacedItemToPlayer, - removePlacedItemById, - handleStartInventoryDrag, - handleItemInteract, - } = useInventoryRuntimeController({ - sceneId, - sceneInteractions, - playerPosition, - onRuntimeEvent: handleRuntimeEvent, - }); - - const { - updateInteractionPosition, - updateInteractionHalfSize, - updateInteractionRotationDeg, - moveInteractionToPlayer, - } = useInteractionEditorController({ + const interactionEditor = useInteractionEditorController({ playerPosition, scenePlayerSpawnY: scenePlayerSpawn[1], updateInteraction, }); - - const { - updateTransitionPosition, - updateTransitionHalfSize, - updateTransitionTargetScene, - moveTransitionToPlayer, - createTransition, - deleteTransition, - } = useTransitionEditorController(); - - // DI props for renderer-r3f's GameTouchSpriteRuntime - const addWallWithData = useSceneEditorStore((s) => s.addWallWithData); - const selectedWallIndex = useSceneEditorStore((s) => s.selectedWallIndex); - const onSelectWall = useSceneEditorStore((s) => s.selectWall); - const updateSelectedWall = useSceneEditorStore((s) => s.updateSelectedWall); + const transitionEditor = useTransitionEditorController(); // Editor / camera modes (debug only; defaults preserve runtime behavior) const disableClickToMove = useEditorModeStore(selectGameInteractionsDisabled); const sceneEditingBlocked = useEditorModeStore(selectSceneEditingBlocked); - const wallInteractionsEnabled = !sceneEditingBlocked; const wallOpacityMode = useEditorModeStore((s) => s.wallOpacityMode); const cameraMode = useEditorModeStore((s) => s.cameraMode); const showPlayerCollider = useEditorModeStore((s) => s.showPlayerCollider); - const readyMessage = `${selectedCharacter} listo — flechas/WASD o click para moverse`; - - return ( -
+ // DI props for renderer-r3f's GameTouchSpriteRuntime + const addWallWithData = useSceneEditorStore((s) => s.addWallWithData); + const selectedWallIndex = useSceneEditorStore((s) => s.selectedWallIndex); + const onSelectWall = useSceneEditorStore((s) => s.selectWall); + const updateSelectedWall = useSceneEditorStore((s) => s.updateSelectedWall); + const overlay = ( + <> - - useInventoryStore.getState().close()} - onCreated={(state) => { - try { - const glCtx = state.gl.getContext(); - console.log("Three: renderer created", { - contextAttributes: glCtx?.getContextAttributes?.(), - version: glCtx?.getParameter?.(glCtx.VERSION), - shadingLanguageVersion: glCtx?.getParameter?.(glCtx.SHADING_LANGUAGE_VERSION), - }); - state.gl.setClearColor(0x0f0f10, 1); - state.gl.clear(); - } catch (err) { - console.error("Three: onCreated error", err); - } - }} - style={{ position: "absolute", inset: 0, width: "100%", height: "100%", zIndex: 1, background: "transparent", display: "block" }} - > - - {cameraMode === "fixed" && } - {/* */} - - - - {cameraMode === "fixed" && } - - - - - - - - - item.sceneId === sceneId || - (item.sceneId === undefined && sceneId === "personalRoom") - )} - onPickup={handlePickupPlacedItem} - onInteract={handleItemInteract} - canPickup={!isInventoryOpen && !disableClickToMove && !speechVisible} - /> - - - - - - {draggedStack && ( + {controller.draggedStack && ( )} + + ); - {/* Cortina de transición: siempre en DOM, opacidad 0 en reposo. - Se activa/desactiva via ref para evitar el batching de React. */} -
-
+ return ( + } + overlay={overlay} + > + + ); } diff --git a/apps/web-demo/app/components/InventoryUI.tsx b/apps/web-demo/app/components/InventoryUI.tsx index d3f943c..423bc7d 100644 --- a/apps/web-demo/app/components/InventoryUI.tsx +++ b/apps/web-demo/app/components/InventoryUI.tsx @@ -15,6 +15,7 @@ import { type AnimationFrameHandle, type TimerHandle, } from "../lib/platform-web"; +import { clearGameProgress } from "../lib/gamePersistence"; export type InventoryStack = { id: string; @@ -63,11 +64,20 @@ export function InventoryUI({ slots, onToggle, onStartDrag, + isDragging = false, + onDropOnSlot, }: { isOpen: boolean; slots: InventorySlots; onToggle: () => void; onStartDrag: (slotIndex: number, clientX: number, clientY: number) => void; + /** Hay un ítem arrastrado: el panel se queda visible para poder soltarlo sobre otro slot. */ + isDragging?: boolean; + /** + * Se suelta el ítem arrastrado sobre un slot. Devuelve `true` si lo ha consumido (combinación); + * con `false` la suelta sigue su camino de siempre (slot vacío, el mismo slot o la escena). + */ + onDropOnSlot?: (slotIndex: number) => boolean; }) { const [isMobile, setIsMobile] = useState(false); const [isBackpackHovered, setIsBackpackHovered] = useState(false); @@ -87,6 +97,8 @@ export function InventoryUI({ const panelTweenRef = useRef(null); const { t } = useI18n(); + // Al empezar un arrastre el motor cierra la mochila; el panel sigue a la vista hasta soltar. + const isPanelOpen = isOpen || isDragging; useEffect(() => { const media = browserEnvironmentAdapter.matchMedia("(max-width: 768px)"); @@ -263,7 +275,7 @@ export function InventoryUI({ }, [slots, startBackpackSpin]); useEffect(() => { - if (isOpen) { + if (isPanelOpen) { if (!isPanelRendered) { const animationFrameId: AnimationFrameHandle = browserEnvironmentAdapter.requestAnimationFrame(() => { setIsPanelRendered(true); @@ -281,7 +293,7 @@ export function InventoryUI({ if (isPanelRendered) { animatePanel(false); } - }, [animatePanel, isOpen, isPanelRendered]); + }, [animatePanel, isPanelOpen, isPanelRendered]); useEffect(() => { return () => { @@ -308,7 +320,7 @@ export function InventoryUI({ cancelText={t("ui.cancel")} isDangerous={true} onConfirm={() => { - localStorage.clear(); + clearGameProgress(); window.location.reload(); }} onCancel={() => setIsResetConfirmOpen(false)} @@ -502,6 +514,11 @@ export function InventoryUI({ key={`slot-${index}`} type="button" onPointerDown={(event) => handlePointerDown(event, index)} + onPointerUp={(event) => { + // Soltar sobre otro slot ocupado combina; el evento no debe llegar al + // "suelta fuera de una diana" de la escena (escucha en window). + if (onDropOnSlot?.(index)) event.nativeEvent.stopPropagation(); + }} style={slotStyle(Boolean(stack))} aria-label={stack ? `Slot ${index + 1}: ${stack.name}` : t("ui.slot.empty", { vars: { n: index + 1 } })} > diff --git a/apps/web-demo/app/components/SpeechBubble.tsx b/apps/web-demo/app/components/SpeechBubble.tsx deleted file mode 100644 index e4714bb..0000000 --- a/apps/web-demo/app/components/SpeechBubble.tsx +++ /dev/null @@ -1 +0,0 @@ -export { SpeechBubble as default } from "@pointclick-engine/engine-renderer-r3f"; diff --git a/apps/web-demo/app/components/debug/FloatingPanel.tsx b/apps/web-demo/app/components/debug/FloatingPanel.tsx index 6074f61..c602d88 100644 --- a/apps/web-demo/app/components/debug/FloatingPanel.tsx +++ b/apps/web-demo/app/components/debug/FloatingPanel.tsx @@ -2,7 +2,6 @@ import { useCallback, - useEffect, useRef, useState, type CSSProperties, @@ -54,9 +53,12 @@ export function FloatingPanel({ const [isDragging, setIsDragging] = useState(false); // Sync local state when the store changes externally (e.g. reset). - useEffect(() => { + // "Adjust state when a prop changes" pattern: done during render, no effect. + const [prevStoredPosition, setPrevStoredPosition] = useState(storedPosition); + if (storedPosition !== prevStoredPosition) { + setPrevStoredPosition(storedPosition); if (storedPosition) setPosition(storedPosition); - }, [storedPosition]); + } const handlePointerDown = useCallback( (event: ReactPointerEvent) => { diff --git a/apps/web-demo/app/components/intro/IntroScene.tsx b/apps/web-demo/app/components/intro/IntroScene.tsx index a8c5fe8..1a71a8d 100644 --- a/apps/web-demo/app/components/intro/IntroScene.tsx +++ b/apps/web-demo/app/components/intro/IntroScene.tsx @@ -76,17 +76,15 @@ export function IntroScene({ onComplete }: IntroSceneProps) { // restart. The ref is reset to 0 whenever introText changes (locale switch // before clicking). const introTextRef = useRef(t("intro.text")); - // Keep the ref up-to-date while the user hasn't started yet. - if (!started) { - introTextRef.current = t("intro.text"); - indexRef.current = 0; - } - + // The text/cursor are captured in handleStart (an event handler, not render), + // using the locale active at click time. const handleStart = useCallback(() => { if (started) return; + introTextRef.current = t("intro.text"); + indexRef.current = 0; playClickSound(); setStarted(true); - }, [started]); + }, [started, t]); const handleSkip = useCallback(() => { skipTypingRef.current?.(); diff --git a/apps/web-demo/app/components/scene/SceneCollisionSphere.tsx b/apps/web-demo/app/components/scene/SceneCollisionSphere.tsx deleted file mode 100644 index 53498a7..0000000 --- a/apps/web-demo/app/components/scene/SceneCollisionSphere.tsx +++ /dev/null @@ -1 +0,0 @@ -export { SceneCollisionSphere } from "@pointclick-engine/engine-renderer-r3f"; diff --git a/apps/web-demo/app/components/scene/SceneGround.tsx b/apps/web-demo/app/components/scene/SceneGround.tsx deleted file mode 100644 index 90bcdae..0000000 --- a/apps/web-demo/app/components/scene/SceneGround.tsx +++ /dev/null @@ -1 +0,0 @@ -export { SceneGround } from "@pointclick-engine/engine-renderer-r3f"; diff --git a/apps/web-demo/app/components/scene/SceneWallPointPreview.tsx b/apps/web-demo/app/components/scene/SceneWallPointPreview.tsx deleted file mode 100644 index 104481d..0000000 --- a/apps/web-demo/app/components/scene/SceneWallPointPreview.tsx +++ /dev/null @@ -1 +0,0 @@ -export { SceneWallPointPreview } from "@pointclick-engine/engine-renderer-r3f"; diff --git a/apps/web-demo/app/components/scene/SceneWalls.tsx b/apps/web-demo/app/components/scene/SceneWalls.tsx deleted file mode 100644 index 2dd7bf8..0000000 --- a/apps/web-demo/app/components/scene/SceneWalls.tsx +++ /dev/null @@ -1,2 +0,0 @@ -export { SceneWalls } from "@pointclick-engine/engine-renderer-r3f"; -export type { WallResizeHandle } from "@pointclick-engine/engine-renderer-r3f"; diff --git a/apps/web-demo/app/components/sprite/AnimatedSprite.tsx b/apps/web-demo/app/components/sprite/AnimatedSprite.tsx deleted file mode 100644 index a9683e1..0000000 --- a/apps/web-demo/app/components/sprite/AnimatedSprite.tsx +++ /dev/null @@ -1,159 +0,0 @@ -"use client"; - -import { useEffect, useMemo, useRef, forwardRef, useImperativeHandle } from "react"; -import { useFrame, useLoader } from "@react-three/fiber"; -import { - ClampToEdgeWrapping, - FrontSide, - Mesh, - NearestFilter, - SRGBColorSpace, - Texture, - TextureLoader, -} from "three"; - -type AnimationClip = { - x: number; - y: number; - frameWidth: number; - frameHeight: number; - strideX: number; - startFrame: number; - endFrame: number; - fps: number; - loop?: boolean; -}; - -type AtlasGrid = { - width: number; - height: number; -}; - -type AnimatedSpriteProps = { - textureUrl: string; - clip: AnimationClip; - atlas: AtlasGrid; - meshRef?: React.RefObject; - scale?: [number, number, number]; - flipX?: boolean; - isPaused?: boolean; -}; - -export type AnimatedSpriteHandle = { - nextFrame: () => void; -}; - -function applyFrame(texture: Texture, atlas: AtlasGrid, clip: AnimationClip, frame: number) { - const uvWidth = clip.frameWidth / atlas.width; - const uvHeight = clip.frameHeight / atlas.height; - const frameX = clip.x + frame * clip.strideX; - const frameY = clip.y; - - texture.repeat.set(uvWidth, uvHeight); - texture.offset.set(frameX / atlas.width, 1 - (frameY + clip.frameHeight) / atlas.height); -} - -const AnimatedSprite = forwardRef( - ({ - textureUrl, - clip, - atlas, - meshRef, - scale = [2.2, 2.2, 1], - flipX = false, - isPaused = false, - }: AnimatedSpriteProps, ref) => { - const internalRef = useRef(null); - const targetRef = meshRef ?? internalRef; - const sourceTexture = useLoader(TextureLoader, textureUrl); - - const texture = useMemo(() => { - const clonedTexture = sourceTexture.clone(); - clonedTexture.colorSpace = SRGBColorSpace; - clonedTexture.magFilter = NearestFilter; - clonedTexture.minFilter = NearestFilter; - clonedTexture.wrapS = ClampToEdgeWrapping; - clonedTexture.wrapT = ClampToEdgeWrapping; - clonedTexture.generateMipmaps = false; - clonedTexture.needsUpdate = true; - return clonedTexture; - }, [sourceTexture]); - - const frameCursorRef = useRef(clip.startFrame); - const frameTimeRef = useRef(0); - - useEffect(() => { - frameCursorRef.current = clip.startFrame; - frameTimeRef.current = 0; - applyFrame(texture, atlas, clip, clip.startFrame); - }, [atlas, clip, texture]); - - useImperativeHandle( - ref, - () => ({ - nextFrame: () => { - const clipLength = clip.endFrame - clip.startFrame + 1; - const nextFrameIndex = frameCursorRef.current - clip.startFrame + 1; - - if (clip.loop ?? true) { - frameCursorRef.current = clip.startFrame + (nextFrameIndex % clipLength); - } else { - frameCursorRef.current = Math.min(clip.startFrame + nextFrameIndex, clip.endFrame); - } - - applyFrame(texture, atlas, clip, frameCursorRef.current); - }, - }), - [clip, texture, atlas], - ); - - useFrame((_, delta) => { - if (isPaused) { - return; - } - - frameTimeRef.current += delta; - const stepTime = 1 / clip.fps; - - if (frameTimeRef.current < stepTime) { - return; - } - - const steps = Math.floor(frameTimeRef.current / stepTime); - frameTimeRef.current -= steps * stepTime; - - const clipLength = clip.endFrame - clip.startFrame + 1; - const frameAdvance = frameCursorRef.current - clip.startFrame + steps; - - if (clip.loop ?? true) { - frameCursorRef.current = clip.startFrame + (frameAdvance % clipLength); - } else { - frameCursorRef.current = Math.min(clip.startFrame + frameAdvance, clip.endFrame); - } - - applyFrame(texture, atlas, clip, frameCursorRef.current); - }); - - // Memoizar el array de escala para que R3F no re-aplique el prop en cada render - // y no sobreescriba la escala imperativa que gestiona el padre desde useFrame. - const [sx, sy, sz] = scale; - const meshScale = useMemo<[number, number, number]>( - () => [flipX ? -Math.abs(sx) : Math.abs(sx), sy, sz], - [flipX, sx, sy, sz], - ); - - return ( - - - - - ); - }, -); - -AnimatedSprite.displayName = "AnimatedSprite"; - -export default AnimatedSprite; \ No newline at end of file diff --git a/apps/web-demo/app/components/sprite/DavidSprite.tsx b/apps/web-demo/app/components/sprite/DavidSprite.tsx deleted file mode 100644 index 4a76271..0000000 --- a/apps/web-demo/app/components/sprite/DavidSprite.tsx +++ /dev/null @@ -1,2 +0,0 @@ -export { DavidSprite as default } from "@pointclick-engine/engine-renderer-r3f"; -export type { DavidSpriteHandle } from "@pointclick-engine/engine-renderer-r3f"; diff --git a/apps/web-demo/app/components/sprite/clips.ts b/apps/web-demo/app/components/sprite/clips.ts deleted file mode 100644 index b112355..0000000 --- a/apps/web-demo/app/components/sprite/clips.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "@pointclick-engine/engine-renderer-r3f"; diff --git a/apps/web-demo/app/debug/page.tsx b/apps/web-demo/app/debug/page.tsx index d6d5a57..7f5d98e 100644 --- a/apps/web-demo/app/debug/page.tsx +++ b/apps/web-demo/app/debug/page.tsx @@ -1,6 +1,31 @@ +"use client"; + +import { useEffect, useState } from "react"; import { notFound } from "next/navigation"; +import { createGameRuntime, type GameRuntime } from "../lib/engine/publicApi"; +import { DEMO_RUNTIME_CONFIG } from "../lib/engine/runtime/demoViewportOptions"; import GameTouchCanvas from "../components/GameTouchCanvas"; +// Mismo patron que app/page.tsx: el runtime se crea en un efecto (con dispose en +// el cleanup) y el canvas se monta cuando ya existe. Asi /debug resuelve items, +// emite eventos y tiene audio, igual que el juego. +function DebugGame() { + const [runtime, setRuntime] = useState(null); + + useEffect(() => { + const created = createGameRuntime(DEMO_RUNTIME_CONFIG); + // eslint-disable-next-line react-hooks/set-state-in-effect -- publishes the external runtime handle so children mount only once it exists (children effects run before the parent's) + setRuntime(created); + + return () => { + created.dispose(); + setRuntime(null); + }; + }, []); + + return runtime ? : null; +} + export default function DebugPage() { const isDebugEnabled = process.env.NEXT_PUBLIC_ENABLE_DEBUG === "true"; const isProduction = process.env.NODE_ENV === "production"; @@ -9,5 +34,5 @@ export default function DebugPage() { notFound(); } - return ; -} \ No newline at end of file + return ; +} diff --git a/apps/web-demo/app/example-bridge/HtmlBridgePanel.tsx b/apps/web-demo/app/example-bridge/HtmlBridgePanel.tsx index 0fd667a..0db37c3 100644 --- a/apps/web-demo/app/example-bridge/HtmlBridgePanel.tsx +++ b/apps/web-demo/app/example-bridge/HtmlBridgePanel.tsx @@ -117,7 +117,7 @@ export default function HtmlBridgePanel() { style={btnStyle} onClick={() => dispatch({ type: "player:stop" })} > - player:stop (deferred v0.2.0) + player:stop Inventory commands diff --git a/apps/web-demo/app/example-bridge/page.tsx b/apps/web-demo/app/example-bridge/page.tsx index 01beb9a..6bd6ead 100644 --- a/apps/web-demo/app/example-bridge/page.tsx +++ b/apps/web-demo/app/example-bridge/page.tsx @@ -1,14 +1,12 @@ "use client"; -import { useEffect } from "react"; +import { useEffect, useState } from "react"; import { createGameRuntime, - type GameSceneConfig, + type GameRuntime, } from "../lib/engine/publicApi"; -import { SCENES } from "../../demo-content/scenes/scenes"; +import { DEMO_RUNTIME_CONFIG } from "../lib/engine/runtime/demoViewportOptions"; import GameTouchCanvas from "../components/GameTouchCanvas"; -import { useInventoryStore } from "../store/inventoryStore"; -import { useDialogStore } from "../store/dialogStore"; import HtmlBridgePanel from "./HtmlBridgePanel"; /** @@ -20,21 +18,18 @@ import HtmlBridgePanel from "./HtmlBridgePanel"; * Run: `npm run dev` → http://localhost:3000/example-bridge */ export default function ExampleBridgePage() { + // Mismo patrón que app/page.tsx: el canvas se monta cuando el runtime ya + // existe, para que reciba los eventos desde el primer scene:changed. + const [runtime, setRuntime] = useState(null); + useEffect(() => { - const runtime = createGameRuntime({ - scenes: Object.values(SCENES) as GameSceneConfig[], - inventoryAdapter: { - toggle: () => useInventoryStore.getState().toggle(), - isOpen: () => useInventoryStore.getState().isOpen, - }, - dialogAdapter: { - show: (text, key) => useDialogStore.getState().show(text, key), - hide: () => useDialogStore.getState().dismiss(), - }, - }); + const created = createGameRuntime(DEMO_RUNTIME_CONFIG); + // eslint-disable-next-line react-hooks/set-state-in-effect -- publishes the external runtime handle so children mount only once it exists + setRuntime(created); return () => { - runtime.dispose(); + created.dispose(); + setRuntime(null); }; }, []); @@ -48,7 +43,7 @@ export default function ExampleBridgePage() { }} >
- + {runtime ? : null}
diff --git a/apps/web-demo/app/example-minimal/README.md b/apps/web-demo/app/example-minimal/README.md new file mode 100644 index 0000000..1aa044a --- /dev/null +++ b/apps/web-demo/app/example-minimal/README.md @@ -0,0 +1,28 @@ +# example-minimal + +Un juego de dos escenas y un ítem que **solo importa de los paquetes**: +`react`, `@pointclick-engine/engine-core` y `@pointclick-engine/engine-renderer-r3f`. +No usa nada de `app/lib`, `app/components`, `app/store` ni `demo-content`. + +Es la prueba de que la librería es consumible fuera de la demo. + +## Abrirlo + +```bash +npm run dev +# http://localhost:3000/example-minimal +``` + +## Qué hace + +- Registra dos escenas y un ítem con `createGameRuntime`. +- Monta `` con la escena inicial y un trofeo sembrado en el suelo. +- Click sobre el trofeo para recogerlo; camina hacia el fondo (W o click) para + cruzar a la otra escena. +- El panel de arriba lee el estado de los stores del core. + +Sin persistencia, sin audio, sin UI de mochila: son opciones de `GameViewport`. + +## Prueba automática + +`node e2e/smoke-minimal.mjs` (con el servidor en marcha). diff --git a/apps/web-demo/app/example-minimal/page.tsx b/apps/web-demo/app/example-minimal/page.tsx new file mode 100644 index 0000000..72bf8a2 --- /dev/null +++ b/apps/web-demo/app/example-minimal/page.tsx @@ -0,0 +1,173 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { + createGameRuntime, + useSceneStore, + useInventoryStateStore, + usePlacedItemsStateStore, + useWorldStateStore, + act, + otherwise, + type GameRuntime, + type GameSceneConfig, + type GameItemConfig, + sceneTransitionOnCollision, +} from "@pointclick-engine/engine-core"; +import { GameViewport } from "@pointclick-engine/engine-renderer-r3f"; + +/** Escena A: Town-like background con dos spawn points */ +const SCENE_A: GameSceneConfig = { + id: "minimal-a", + label: "Minimal Scene A", + background: "/assets/background/town.jpg", + playerSpawn: [3.08, 1.05, 13.44], + ground: { + minX: -12, + maxX: 17, + minZ: -15, + maxZ: 30, + y: -3.25, + }, + walls: [], + interactions: [], + // Hotspot declarado en la propia escena: con un solo verbo (`look`), un click lo ejecuta + // directamente (sin menú). El guion pone un flag y dice una frase. + hotspots: [ + { + id: "notice", + label: "notice.label", + position: [6.0, 2.6, 13.4], + halfSize: [0.7, 1.2, 0.5], + verbs: { + look: [otherwise(act.setFlag("notice.seen"), act.say("notice.look"))], + }, + }, + ], + // Ítem inicial declarado en la propia escena (sin callback del host). + initialItems: [ + { + item: { + id: "trophy-in-scene-a", + itemId: "trophy", + interactionId: "trophy-pickup-zone", + name: "Trophy", + spriteUrl: "/assets/trophy/trophy.png", + worldPosition: [6.5, -2.4, 13.4], + canPickup: true, + }, + }, + ], + transitions: [ + sceneTransitionOnCollision({ + id: "transition-a-to-b", + targetSceneId: "minimal-b", + position: [2, -1, -12], + halfSize: [6, 4, 2], + spawnPosition: [0, -1.1, 20], + targetPosition: [0, -1.1, 10], + }), + ], +}; + +/** Escena B: Dungeon-like background */ +const SCENE_B: GameSceneConfig = { + id: "minimal-b", + label: "Minimal Scene B", + background: "/assets/background/mazmorra.jpg", + playerSpawn: [0, -1.1, 13.44], + ground: { + minX: -14.4, + maxX: 15.8, + minZ: -20.6, + maxZ: 60.6, + y: -3.15, + }, + walls: [], + interactions: [], + transitions: [ + sceneTransitionOnCollision({ + id: "transition-b-to-a", + targetSceneId: "minimal-a", + position: [0, -2.2, -9], + halfSize: [1, 1, 1], + spawnPosition: [3.08, 1.05, 13.44], + targetPosition: [1.60, -2.10, 14.93], + }), + ], +}; + +/** Trophy item: simple configuration with return-to-inventory default */ +const TROPHY_ITEM: GameItemConfig = { + id: "trophy", + name: "Trophy", + spriteUrl: "/assets/trophy/trophy.png", + interactionRules: {}, + defaultRule: { + outcome: "return", + }, +}; + +/** Status display showing current scene and inventory count */ +function StatusOverlay() { + const sceneId = useSceneStore((s) => s.sceneId); + const inventorySlots = useInventoryStateStore((s) => s.slots); + const inventoryCount = inventorySlots.filter((slot) => slot !== null).length; + const placedCount = usePlacedItemsStateStore((s) => s.items.length); + const noticeSeen = useWorldStateStore((s) => s.flags["notice.seen"] === true); + + return ( +
+ escena: {sceneId} | inventario: {inventoryCount} | en escena: {placedCount} | cartel: {noticeSeen ? "visto" : "sin ver"} +
+ ); +} + +/** Root component: mount runtime once, then viewport */ +function MinimalGame() { + const [runtime, setRuntime] = useState(null); + + useEffect(() => { + const created = createGameRuntime({ + scenes: [SCENE_A, SCENE_B], + items: [TROPHY_ITEM], + // Texto de la frase del hotspot (reglas de diálogo del core). + rules: [{ key: "notice.look", phrases: ["Un cartel de la plaza: 'SE BUSCA... un buen guía.'"] }], + }); + // eslint-disable-next-line react-hooks/set-state-in-effect -- publishes the runtime so child hooks can access it before mounting the viewport + setRuntime(created); + + return () => { + created.dispose(); + setRuntime(null); + }; + }, []); + + if (!runtime) { + return null; + } + + return ( + } + /> + ); +} + +export default MinimalGame; diff --git a/apps/web-demo/app/lib/core/rules/inventoryRules.test.ts b/apps/web-demo/app/lib/core/rules/inventoryRules.test.ts deleted file mode 100644 index 551fc06..0000000 --- a/apps/web-demo/app/lib/core/rules/inventoryRules.test.ts +++ /dev/null @@ -1,130 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { - addOneToInventory, - removeOneFromSlot, - resolveInventoryDropHitDecision, - resolveInventoryDropMissDialogKey, - resolveInventoryDropOnPlayerMessage, - resolvePickupPlacedItemDecision, -} from "./inventoryRules"; - -describe("inventoryRules", () => { - it("decrementa cantidad al remover una unidad", () => { - const next = removeOneFromSlot( - [ - { - id: "gameboy", - name: "Gameboy", - spriteUrl: "/assets/gameboy/gameboy.png", - quantity: 2, - }, - ], - 0, - ); - - expect(next[0]?.quantity).toBe(1); - }); - - it("agrega una unidad a stack existente", () => { - const result = addOneToInventory( - [ - { - id: "gameboy", - name: "Gameboy", - spriteUrl: "/assets/gameboy/gameboy.png", - quantity: 1, - }, - ], - { - id: "gameboy", - name: "Gameboy", - spriteUrl: "/assets/gameboy/gameboy.png", - }, - ); - - expect(result.added).toBe(true); - expect(result.slots[0]?.quantity).toBe(2); - }); - - it("resuelve drop-hit place para gameboy en target valido", () => { - const interaction = { - id: "personal-room-gameboy-drop-target", - kind: "drop-target", - label: "Soporte del Gameboy", - position: [3.27, -1.65, 19.71] as [number, number, number], - halfSize: [0.95, 0.55, 0.95] as [number, number, number], - hasCollision: true, - acceptsItemIds: ["gameboy"], - dialogKeys: { - hit: "inventoryDropHit", - miss: "inventoryDropMiss", - }, - }; - - const decision = resolveInventoryDropHitDecision({ - interaction, - payload: { - stack: { - id: "gameboy", - name: "Gameboy", - spriteUrl: "/assets/gameboy/gameboy.png", - }, - fromSlotIndex: 0, - }, - now: 123, - }); - - expect(decision.kind).toBe("place"); - if (decision.kind !== "place") return; - expect(decision.placedItem.id).toBe("gameboy-personal-room-gameboy-drop-target-123"); - expect(decision.dialogKey).toBe("item.gameboy.drop.personal-room-gameboy-drop-target.hit"); - }); - - it("usa fallback de miss cuando no hay interaction", () => { - const key = resolveInventoryDropMissDialogKey({ - payload: { - stack: { - id: "gameboy", - name: "Gameboy", - spriteUrl: "/assets/gameboy/gameboy.png", - }, - fromSlotIndex: 0, - }, - sceneInteractions: [], - }); - - expect(key).toBe("inventoryDropMiss"); - }); - - it("describe item al soltarlo sobre el player", () => { - const message = resolveInventoryDropOnPlayerMessage({ - payload: { - stack: { - id: "gameboy", - name: "Gameboy", - spriteUrl: "/assets/gameboy/gameboy.png", - }, - fromSlotIndex: 0, - }, - }); - - expect(message.kind).toBe("dialog-key"); - }); - - it("bloquea pickup cuando el item no es levantable", () => { - const decision = resolvePickupPlacedItemDecision({ - placedItem: { - id: "placed-1", - itemId: "gameboy", - interactionId: "personal-room-gameboy-drop-target", - name: "Gameboy", - spriteUrl: "/assets/gameboy/gameboy.png", - worldPosition: [0, 0, 0], - canPickup: false, - }, - }); - - expect(decision.kind).toBe("blocked"); - }); -}); diff --git a/apps/web-demo/app/lib/core/rules/inventoryRules.ts b/apps/web-demo/app/lib/core/rules/inventoryRules.ts deleted file mode 100644 index 522ca2e..0000000 --- a/apps/web-demo/app/lib/core/rules/inventoryRules.ts +++ /dev/null @@ -1,270 +0,0 @@ -import { getItemDefinition, resolveItemRule } from "../../../../demo-content/items"; -import type { DialogKey } from "../../../../demo-content/dialogs/types"; -import type { SceneInteraction } from "../../../../demo-content/scenes/scenes"; -import type { - InventorySlotsState, - PlacedSceneItem, -} from "@pointclick-engine/engine-core"; - -export type { InventorySlotsState, PlacedSceneItem }; - -type DraggedPayloadState = { - stack: { - id: string; - name: string; - spriteUrl: string; - }; - fromSlotIndex: number; -}; - -type DropHitDecision = - | { - kind: "unknown-item"; - message: string; - } - | { - kind: "rule-miss"; - dialogKey: DialogKey; - } - | { - kind: "place"; - fromSlotIndex: number; - placedItem: PlacedSceneItem; - dialogKey: DialogKey; - } - | { - kind: "consume"; - fromSlotIndex: number; - dialogKey: DialogKey; - } - | { - kind: "return"; - dialogKey: DialogKey; - }; - -type PickupDecision = - | { - kind: "ignore"; - } - | { - kind: "blocked"; - dialogKey: DialogKey; - } - | { - kind: "allow"; - placedItemId: string; - stack: { - id: string; - name: string; - spriteUrl: string; - }; - successDialogKey: DialogKey; - }; - -const UNKNOWN_ITEM_MESSAGE = "No conozco este item todavía."; -const DEFAULT_DROP_MISS_DIALOG_KEY: DialogKey = "inventoryDropMiss"; - -function getDefaultPickupDialogKey(itemId: string, type: "allowed" | "blocked"): DialogKey { - return `item.${itemId}.pickup.${type}` as DialogKey; -} - -export function removeOneFromSlot( - slots: InventorySlotsState, - slotIndex: number, -): InventorySlotsState { - const slot = slots[slotIndex]; - if (!slot) return slots; - - const next = [...slots]; - if (slot.quantity <= 1) { - next[slotIndex] = null; - } else { - next[slotIndex] = { ...slot, quantity: slot.quantity - 1 }; - } - return next; -} - -export function addOneToInventory( - slots: InventorySlotsState, - stack: { - id: string; - name: string; - spriteUrl: string; - }, -): { slots: InventorySlotsState; added: boolean } { - const existingIndex = slots.findIndex((current) => current?.id === stack.id); - if (existingIndex >= 0) { - const next = [...slots]; - const existing = next[existingIndex]; - if (!existing) return { slots, added: false }; - next[existingIndex] = { ...existing, quantity: existing.quantity + 1 }; - return { slots: next, added: true }; - } - - const emptyIndex = slots.findIndex((current) => current == null); - if (emptyIndex < 0) { - return { slots, added: false }; - } - - const next = [...slots]; - next[emptyIndex] = { ...stack, quantity: 1 }; - return { slots: next, added: true }; -} - -export function resolveInventoryDropHitDecision({ - interaction, - payload, - now, -}: { - interaction: SceneInteraction; - payload: DraggedPayloadState; - now: number; -}): DropHitDecision { - const itemDefinition = getItemDefinition(payload.stack.id); - if (!itemDefinition) { - return { - kind: "unknown-item", - message: UNKNOWN_ITEM_MESSAGE, - }; - } - - const rule = resolveItemRule(itemDefinition.id, interaction.id); - if (!rule) { - return { - kind: "rule-miss", - dialogKey: interaction.dialogKeys.miss, - }; - } - - if (rule.outcome === "place") { - return { - kind: "place", - fromSlotIndex: payload.fromSlotIndex, - placedItem: { - id: `${itemDefinition.id}-${interaction.id}-${now}`, - itemId: itemDefinition.id, - interactionId: interaction.id, - name: itemDefinition.name, - spriteUrl: itemDefinition.spriteUrl, - worldPosition: [ - interaction.position[0], - interaction.position[1] + interaction.halfSize[1] + 0.175, - interaction.position[2], - ] as [number, number, number], - canPickup: rule.placeCanPickup ?? false, - hasCollision: rule.placeHasCollision ?? false, - collisionHalfSize: rule.placeCollisionHalfSize as [number, number, number] | undefined, - pickupSuccessDialogKey: rule.pickupSuccessDialogKey, - pickupBlockedDialogKey: rule.pickupBlockedDialogKey, - }, - dialogKey: rule.hitDialogKey ?? interaction.dialogKeys.hit, - }; - } - - if (rule.outcome === "consume") { - return { - kind: "consume", - fromSlotIndex: payload.fromSlotIndex, - dialogKey: rule.hitDialogKey ?? interaction.dialogKeys.hit, - }; - } - - return { - kind: "return", - dialogKey: - rule.hitDialogKey ?? rule.missDialogKey ?? interaction.dialogKeys.miss, - }; -} - -export function resolveInventoryDropMissDialogKey({ - payload, - interaction, - sceneInteractions, -}: { - payload: DraggedPayloadState; - interaction?: SceneInteraction; - sceneInteractions: SceneInteraction[]; -}): DialogKey { - const itemRule = interaction - ? resolveItemRule(payload.stack.id, interaction.id) - : null; - - return ( - itemRule?.missDialogKey ?? - interaction?.dialogKeys.miss ?? - sceneInteractions.find( - (currentInteraction) => currentInteraction.kind === "drop-target", - )?.dialogKeys.miss ?? - DEFAULT_DROP_MISS_DIALOG_KEY - ); -} - -export function resolveInventoryDropOnPlayerMessage({ - payload, -}: { - payload: DraggedPayloadState; -}): - | { - kind: "text"; - text: string; - } - | { - kind: "dialog-key"; - dialogKey: DialogKey; - } { - const itemDefinition = getItemDefinition(payload.stack.id); - if (!itemDefinition) { - return { - kind: "text", - text: UNKNOWN_ITEM_MESSAGE, - }; - } - - if (itemDefinition.descriptionDialogKey) { - return { - kind: "dialog-key", - dialogKey: itemDefinition.descriptionDialogKey, - }; - } - - return { - kind: "text", - text: `Es ${itemDefinition.name}.`, - }; -} - -export function resolvePickupPlacedItemDecision({ - placedItem, -}: { - placedItem: PlacedSceneItem; -}): PickupDecision { - const itemDefinition = getItemDefinition(placedItem.itemId); - if (!itemDefinition) { - return { kind: "ignore" }; - } - - if (!placedItem.canPickup) { - return { - kind: "blocked", - dialogKey: - placedItem.pickupBlockedDialogKey ?? getDefaultPickupDialogKey(placedItem.itemId, "blocked"), - }; - } - - return { - kind: "allow", - placedItemId: placedItem.id, - stack: { - id: itemDefinition.id, - name: itemDefinition.name, - spriteUrl: itemDefinition.spriteUrl, - }, - successDialogKey: - placedItem.pickupSuccessDialogKey ?? getDefaultPickupDialogKey(placedItem.itemId, "allowed"), - }; -} - -export const inventoryRuleMessages = { - unknownItem: UNKNOWN_ITEM_MESSAGE, - inventoryFull: "Inventario lleno.", -}; diff --git a/apps/web-demo/app/lib/engine/publicApi.test.ts b/apps/web-demo/app/lib/engine/publicApi.test.ts index 6bcd56e..5f35c8e 100644 --- a/apps/web-demo/app/lib/engine/publicApi.test.ts +++ b/apps/web-demo/app/lib/engine/publicApi.test.ts @@ -2,6 +2,9 @@ import { describe, expect, it, vi, afterEach, beforeEach } from "vitest"; import { createElement } from "react"; import { renderToString } from "react-dom/server"; +import { useGameViewportController } from "@pointclick-engine/engine-renderer-r3f"; +import type { RuntimeEvent } from "@pointclick-engine/engine-core"; + import { DEFAULT_SCENE_ID, SCENES } from "../../../demo-content/scenes/scenes"; import { useInventoryStore } from "../../store/inventoryStore"; import { useDialogStore } from "../../store/dialogStore"; @@ -15,6 +18,8 @@ import { registerRule, registerScene, useGameActions, + type GameActions, + type GameViewportProps, type GameItemConfig, type GameRuleConfig, type GameSceneConfig, @@ -118,35 +123,54 @@ describe("publicApi", () => { Object.values(SCENES).forEach(registerScene); const sceneIds = Object.keys(SCENES); - let actionsFromHook: ReturnType | null = null; + const holder: { actions: GameActions | null } = { actions: null }; function Probe() { - actionsFromHook = useGameActions(); + holder.actions = useGameActions(); return null; } renderToString(createElement(Probe)); - expect(actionsFromHook).not.toBeNull(); - expect(typeof actionsFromHook?.setScene).toBe("function"); - expect(typeof actionsFromHook?.setPlayerPosition).toBe("function"); - expect(typeof actionsFromHook?.requestRespawn).toBe("function"); + expect(holder.actions).not.toBeNull(); + expect(typeof holder.actions?.setScene).toBe("function"); + expect(typeof holder.actions?.setPlayerPosition).toBe("function"); + expect(typeof holder.actions?.requestRespawn).toBe("function"); // Test that setScene actually works - actionsFromHook?.setScene(sceneIds[0]); + holder.actions?.setScene(sceneIds[0]); const afterSetScene = getGameState(); expect(afterSetScene.sceneId).toBe(sceneIds[0]); }); - it("GameViewport reenvia debug y onRuntimeEvent al componente base", () => { - const onRuntimeEvent = () => {}; - const element = GameViewport({ - debug: true, - onRuntimeEvent, - }); + it("GameViewport reenvia debug y onRuntimeEvent a su destino", () => { + // GameViewport ya no es un envoltorio sin hooks sobre GameCanvasCore: vive en el + // renderer y delega en useGameViewportController (+ GameViewportView). Las dos props + // del contrato llegan al controlador, que es quien las consume: `onRuntimeEvent` + // recibe cada evento (ademas del bus) y `debug` activa el log de eventos. + expect(typeof GameViewport).toBe("function"); + const runtime = createGameRuntime(); + const busSpy = vi.fn(); + runtime.on("player:moved", busSpy); + const debugSpy = vi.spyOn(console, "debug").mockImplementation(() => {}); + const onRuntimeEvent = vi.fn(); + const props = { debug: true, onRuntimeEvent } satisfies GameViewportProps; + const holder: { handle: ((event: RuntimeEvent) => void) | null } = { handle: null }; + + function Probe() { + holder.handle = useGameViewportController(props).handleRuntimeEvent; + return null; + } + renderToString(createElement(Probe)); + + const event: RuntimeEvent = { type: "onMove", position: [1, 0, 2], action: "idle" }; + holder.handle?.(event); - expect(element.props.debug).toBe(true); - expect(element.props.onRuntimeEvent).toBe(onRuntimeEvent); + expect(onRuntimeEvent).toHaveBeenCalledWith(event); + expect(busSpy).toHaveBeenCalledOnce(); + expect(debugSpy).toHaveBeenCalledWith("[runtime-event]", event); + debugSpy.mockRestore(); + runtime.dispose(); }); }); @@ -238,6 +262,20 @@ describe("publicApi — bidirectional API (Phase 4)", () => { // Phase 5: Wired commands // --------------------------------------------------------------------------- +function createWiredRuntime(config: Parameters[0] = {}) { + return createGameRuntime({ + ...config, + inventoryAdapter: { + toggle: () => useInventoryStore.getState().toggle(), + isOpen: () => useInventoryStore.getState().isOpen, + }, + dialogAdapter: { + show: (text, key) => useDialogStore.getState().show(text, key), + hide: () => useDialogStore.getState().dismiss(), + }, + }); +} + describe("publicApi — wired commands (Phase 5)", () => { beforeEach(() => { // Reset stores before each test @@ -250,7 +288,7 @@ describe("publicApi — wired commands (Phase 5)", () => { }); it("inventory:toggle toggles inventoryStore.isOpen", () => { - const runtime = createGameRuntime(); + const runtime = createWiredRuntime(); expect(useInventoryStore.getState().isOpen).toBe(false); runtime.executeCommand({ type: "inventory:toggle" }); @@ -261,7 +299,7 @@ describe("publicApi — wired commands (Phase 5)", () => { }); it("dialog:trigger shows text in dialogStore and emits event", () => { - const runtime = createGameRuntime({ + const runtime = createWiredRuntime({ rules: [{ key: "test.dialog", phrases: ["Hello world"] }], }); const spy = vi.fn(); @@ -282,13 +320,13 @@ describe("publicApi — wired commands (Phase 5)", () => { }); it("dialog:trigger uses dialogKey as fallback when rule not registered", () => { - const runtime = createGameRuntime(); + const runtime = createWiredRuntime(); runtime.executeCommand({ type: "dialog:trigger", dialogKey: "unregistered.key" }); expect(useDialogStore.getState().text).toBe("unregistered.key"); }); it("dialog:dismiss hides dialogStore and emits event", () => { - const runtime = createGameRuntime({ + const runtime = createWiredRuntime({ rules: [{ key: "test.dismiss", phrases: ["Dismiss me"] }], }); const spy = vi.fn(); @@ -305,4 +343,30 @@ describe("publicApi — wired commands (Phase 5)", () => { dialogKey: "test.dismiss", }); }); + + it("without adapters, inventory:toggle acts on the default core store and does not throw", () => { + const runtime = createGameRuntime(); + expect(() => runtime.executeCommand({ type: "inventory:toggle" })).not.toThrow(); + // Los stores de la demo son los del core: el toggle por defecto SI abre el inventario. + expect(useInventoryStore.getState().isOpen).toBe(true); + runtime.executeCommand({ type: "inventory:toggle" }); + expect(useInventoryStore.getState().isOpen).toBe(false); + }); + + it("without adapters, dialog:trigger does not throw and still emits dialog:triggered", () => { + const runtime = createGameRuntime({ + rules: [{ key: "test.noadapter", phrases: ["No adapter"] }], + }); + const spy = vi.fn(); + runtime.on("dialog:triggered", spy); + + expect(() => + runtime.executeCommand({ type: "dialog:trigger", dialogKey: "test.noadapter" }), + ).not.toThrow(); + // Sin adapter se usa el store por defecto del core (el mismo objeto que el de la demo). + expect(useDialogStore.getState().visible).toBe(true); + expect(useDialogStore.getState().text).toBe("No adapter"); + expect(useDialogStore.getState().key).toBe("test.noadapter"); + expect(spy).toHaveBeenCalledOnce(); + }); }); diff --git a/apps/web-demo/app/lib/engine/publicApi.ts b/apps/web-demo/app/lib/engine/publicApi.ts index ba2e783..e5f872d 100644 --- a/apps/web-demo/app/lib/engine/publicApi.ts +++ b/apps/web-demo/app/lib/engine/publicApi.ts @@ -1,11 +1,24 @@ "use client"; +/** + * Public API mínima del motor de juego (barrel). + * + * El runtime agnóstico vive en `@pointclick-engine/engine-core`, los hooks y + * el canvas en `@pointclick-engine/engine-renderer-r3f`. Este módulo mantiene + * el contrato v1 estable re-exportando ambos. + */ + +import { type GameSceneInteractionFull } from "@pointclick-engine/engine-core"; + // Re-exports from renderer (stable public API) -export { useR3FGameLoop, WebKeyboardInput } from "@pointclick-engine/engine-renderer-r3f"; +export { + useR3FGameLoop, + WebKeyboardInput, + useGameState, + useGameActions, +} from "@pointclick-engine/engine-renderer-r3f"; -// --------------------------------------------------------------------------- -// i18n public surface (Phase 13, v0.4.0+) — additions only, no breaking change -// --------------------------------------------------------------------------- +// i18n public surface (Phase 13) — additions only export type { Locale, @@ -53,44 +66,12 @@ export type { I18nProviderProps, } from "@pointclick-engine/engine-renderer-r3f"; -/** - * Public API mínima del motor de juego. - * - * Este módulo expone contratos estables e independientes de demo/content. - * Usa estos tipos y funciones para integrar el engine desde fuera sin - * acoplar a imports internos de app/demo/content. - */ - -import { useShallow } from "zustand/react/shallow"; -import { createElement } from "react"; -import type { ComponentType } from "react"; +// Runtime (vive en engine-core) -import { - useSceneStore, - setSceneStoreEmitter, - EventBus, - CommandHandler, - findPath, - type GameVec3, - type GameSceneGround, - type GameSceneWall, - type GameSceneInteractionFull, - type GameEvent, - type GameEventType, - type GameEventHandler, - type GameCommand, - type SceneMusicConfig, -} from "@pointclick-engine/engine-core"; -import { GameCanvasCore } from "@pointclick-engine/engine-renderer-r3f"; - -// --------------------------------------------------------------------------- -// Tipos públicos reutilizables (importados o re-exportados de engine-core) -// --------------------------------------------------------------------------- - -// Re-export key types from engine-core for API stability -export type { GameVec3, GameSceneGround, GameSceneWall } from "@pointclick-engine/engine-core"; -// Re-export bidirectional API types export type { + GameVec3, + GameSceneGround, + GameSceneWall, GameEvent, GameEventType, GameEventHandler, @@ -100,527 +81,33 @@ export type { // Alias for public API compatibility export type GameSceneInteraction = GameSceneInteractionFull; -/** Configuración de escena registrable via API pública. */ -export type GameSceneConfig = { - id: string; - label: string; - background: string; - playerSpawn: GameVec3; - ground: GameSceneGround; - walls: GameSceneWall[]; - interactions: GameSceneInteraction[]; - music?: SceneMusicConfig; -}; - -export type GameItemDropOutcome = - | "consume" - | "place" - | "return" - | "rule-miss" - | "unknown-item" - | "on-player" - | "pickup-blocked" - | "pickup-success"; - -export type GameItemRule = { - outcome: GameItemDropOutcome; - hitDialogKey?: string; - missDialogKey?: string; - placeCanPickup?: boolean; - placeHasCollision?: boolean; - placeCollisionHalfSize?: GameVec3; - pickupSuccessDialogKey?: string; - pickupBlockedDialogKey?: string; - dropSoundUrl?: string; -}; - -/** Configuración de ítem registrable via API pública. */ -export type GameItemConfig = { - id: string; - name: string; - spriteUrl: string; - descriptionDialogKey?: string; - pickupSoundUrl?: string; - dropSoundUrl?: string; - interactionRules: Record; - defaultRule: GameItemRule; -}; - -/** Regla de texto/diálogo registrable via API pública. */ -export type GameRuleConfig = { - key: string; - phrases: string[]; -}; - -/** Props del punto de integración GameViewport (canvas + runtime). */ -export type GameViewportProps = { - debug?: boolean; - onRuntimeEvent?: GameRuntimeEventHandler; -}; - -// --------------------------------------------------------------------------- -// Eventos de runtime (legacy — mantenidos por backwards compat) -// --------------------------------------------------------------------------- - -export type GameRuntimeEvent = - | { - type: "onMove"; - position: GameVec3; - action: "idle" | "north" | "south" | "west" | "east"; - } - | { type: "onCollide"; reason: "boundary" | "stuck"; position: GameVec3 } - | { type: "onDrop"; outcome: string; itemId: string; interactionId?: string } - | { type: "onDialog"; text: string; dialogKey?: string; source: string }; - -export type GameRuntimeEventHandler = (event: GameRuntimeEvent) => void; - -// --------------------------------------------------------------------------- -// Handle de runtime devuelto por createGameRuntime (Phase 4) -// --------------------------------------------------------------------------- - -export type GameRuntime = { - // Registro (existentes) - getScenes: () => Record; - getItems: () => Record; - getRules: () => Record; - // Bidirectional API (Phase 4) - /** - * Envía un comando al motor. Sync, fire-and-forget. - * Comandos sin executor registrado loguean warn y no hacen nada. - * Ver ADR-0006 y docs/architecture/05-bidirectional-communication.md. - */ - executeCommand: (cmd: GameCommand) => void; - /** - * Suscribe a un tipo de evento del motor. - * @returns unsubscribe — llámalo para cancelar la suscripción (ej. en useEffect cleanup). - */ - on: (type: T, handler: GameEventHandler) => () => void; - /** - * Emite un evento al bus del runtime. - * Útil para que el renderer envíe eventos sin conocer el store. - */ - emit: (event: GameEvent) => void; - /** - * Libera el bus y desactiva las emisiones del store. - * Llamar al desmontar la app / en tests cleanup. - */ - dispose: () => void; -}; - -type SceneStoreSnapshot = ReturnType; - -export type GameState = Pick< - SceneStoreSnapshot, - "sceneId" | "scene" | "playerPosition" | "respawnSignal" ->; - -export type GameActions = Pick< - SceneStoreSnapshot, - "setScene" | "setPlayerPosition" | "requestRespawn" ->; - -function toGameState(state: SceneStoreSnapshot): GameState { - return { - sceneId: state.sceneId, - scene: state.scene, - playerPosition: state.playerPosition, - respawnSignal: state.respawnSignal, - }; -} - -// --------------------------------------------------------------------------- -// Configuración de createGameRuntime -// --------------------------------------------------------------------------- - -/** Adapter para conectar el engine con la UI de inventario del host. */ -export interface InventoryUIAdapter { - toggle(): void; - isOpen(): boolean; -} - -/** Adapter para conectar el engine con el sistema de diálogos del host. */ -export interface DialogUIAdapter { - show(text: string, dialogKey?: string): void; - hide(): void; -} - -export type GameRuntimeConfig = { - scenes?: GameSceneConfig[]; - items?: GameItemConfig[]; - rules?: GameRuleConfig[]; - /** Adapter de UI para inventory. Si no se pasa, inventory:toggle es no-op. */ - inventoryAdapter?: InventoryUIAdapter; - /** Adapter de UI para diálogos. Si no se pasa, dialog:trigger es no-op. */ - dialogAdapter?: DialogUIAdapter; -}; - -// --------------------------------------------------------------------------- -// Registros internos (singleton de módulo) -// --------------------------------------------------------------------------- - -const _sceneRegistry = new Map(); -const _itemRegistry = new Map(); -const _ruleRegistry = new Map(); - -/** Singleton del runtime activo. Accesible vía getGameRuntime(). */ -let _runtimeHandle: GameRuntime | null = null; - -/** - * Registra una escena en el motor. - * Idempotente: registrar la misma id sobreescribe la anterior. - */ -export function registerScene(config: GameSceneConfig): void { - _sceneRegistry.set(config.id, config); -} - -/** - * Registra un ítem en el motor. - * Idempotente: registrar el mismo id sobreescribe el anterior. - */ -export function registerItem(config: GameItemConfig): void { - _itemRegistry.set(config.id, config); -} - -/** - * Registra una regla de diálogo en el motor. - * Idempotente: registrar la misma key sobreescribe la anterior. - */ -export function registerRule(config: GameRuleConfig): void { - _ruleRegistry.set(config.key, config); -} - -// --------------------------------------------------------------------------- -// Factory principal -// --------------------------------------------------------------------------- - -/** - * Inicializa el runtime con las escenas, ítems y reglas proporcionadas. - * - * Registra cada config en el registry global, crea el EventBus y el - * CommandHandler, y devuelve un handle con acceso completo a la API - * bidireccional (`executeCommand`, `on`, `emit`, `dispose`). - * - * El handle se almacena como singleton accesible vía `getGameRuntime()`. - * - * @example - * ```ts - * const runtime = createGameRuntime({ scenes: [myScene], items: [myItem] }); - * runtime.on("scene:changed", (e) => console.log("now in:", e.sceneId)); - * runtime.executeCommand({ type: "scene:set", sceneId: myScene.id }); - * ``` - */ -export function createGameRuntime(config: GameRuntimeConfig = {}): GameRuntime { - // Register content - for (const scene of config.scenes ?? []) { - registerScene(scene); - } - for (const item of config.items ?? []) { - registerItem(item); - } - for (const rule of config.rules ?? []) { - registerRule(rule); - } - - // Create bus and command handler - const bus = new EventBus(); - const commands = new CommandHandler(); - - // Wire store → bus - setSceneStoreEmitter((event) => bus.emit(event.type, event)); - - // Register executors: scene commands - commands.register("scene:set", (cmd) => { - const sceneConfig = _sceneRegistry.get(cmd.sceneId); - if (!sceneConfig) { - console.warn(`[runtime] scene:set — scene not registered: ${cmd.sceneId}`); - return; - } - useSceneStore.getState().setScene(sceneConfig.id, { - id: sceneConfig.id, - label: sceneConfig.label, - background: sceneConfig.background, - playerSpawn: sceneConfig.playerSpawn, - ground: sceneConfig.ground, - walls: sceneConfig.walls, - interactions: sceneConfig.interactions, - }); - }); - - commands.register("scene:respawn", () => { - useSceneStore.getState().requestRespawn(); - }); - - commands.register("player:move", (cmd) => { - useSceneStore.getState().setPlayerPosition(cmd.position); - }); - - commands.register("player:walkTo", (cmd) => { - const state = useSceneStore.getState(); - const from: [number, number, number] = [ - state.playerPosition[0], - state.playerPosition[1], - state.playerPosition[2], - ]; - const to: [number, number, number] = [ - cmd.position[0], - cmd.position[1], - cmd.position[2], - ]; - - // console.log(`[walkTo] from ${JSON.stringify(from)} to ${JSON.stringify(to)}`); - - // Calculate path using existing pathfinding - const pathResult = findPath({ - start: { x: from[0], z: from[2] }, - goal: { x: to[0], z: to[2] }, - bounds: { - minX: state.scene.ground.minX, - maxX: state.scene.ground.maxX, - minZ: state.scene.ground.minZ, - maxZ: state.scene.ground.maxZ, - }, - walls: state.scene.walls, - interactions: state.scene.interactions, - }); - - // console.log(`[walkTo] pathResult length:`, pathResult?.length ?? 0); - - if (pathResult && pathResult.length > 0) { - // Convert path points back to GameVec3 format - // Always include start point + pathfinding results to ensure ≥2 points for interpolation - const pathPoints: typeof cmd.position[] = [ - from, // Start position - ...pathResult.map((point) => [ - point.x, - state.scene.ground.y, - point.z, - ] as typeof cmd.position), - ]; - - // console.log(`[walkTo] setting walk state with ${pathPoints.length} points`); - - // Create walk state and activate animation - state.setPlayerWalkingState({ - targetPosition: cmd.position, - pathPoints, - progress: 0, - isActive: true, - }); - - // Emit event for listeners - bus.emit("player:walkStarted", { - type: "player:walkStarted", - targetPosition: cmd.position, - }); - } else { - console.log(`[walkTo] no path found - aborting`); - // Path not found - bus.emit("player:walkAborted", { - type: "player:walkAborted", - reason: "unreachable", - }); - } - }); - - // --------------------------------------------------------------------------- - // Wired executors (Phase 5) - // --------------------------------------------------------------------------- - - commands.register("inventory:toggle", () => { - config.inventoryAdapter?.toggle(); - }); - - // Track the active dialog key so dialog:dismiss can include it in the event - let _activeDialogKey: string | undefined; - - commands.register("dialog:trigger", (cmd) => { - const entry = _ruleRegistry.get(cmd.dialogKey); - const phrases = entry?.phrases ?? []; - const text = - phrases.length > 0 - ? phrases[Math.floor(Math.random() * phrases.length)]! - : cmd.dialogKey; - _activeDialogKey = cmd.dialogKey; - config.dialogAdapter?.show(text, cmd.dialogKey); - bus.emit("dialog:triggered", { - type: "dialog:triggered", - text, - dialogKey: cmd.dialogKey, - source: "command", - }); - }); - - commands.register("dialog:dismiss", () => { - const key = _activeDialogKey; - _activeDialogKey = undefined; - config.dialogAdapter?.hide(); - bus.emit("dialog:dismissed", { - type: "dialog:dismissed", - dialogKey: key, - }); - }); - - // --------------------------------------------------------------------------- - // Transition executors (Phase 8) - // --------------------------------------------------------------------------- - - commands.register("transition:activate", (cmd) => { - const state = useSceneStore.getState(); - const transition = state.scene.transitions?.find( - (t) => t.id === cmd.transitionId, - ); - if (!transition) { - console.warn(`[runtime] transition:activate — unknown transition: ${cmd.transitionId}`); - return; - } - const fromSceneId = state.sceneId; - bus.emit("transition:started", { - type: "transition:started", - transitionId: cmd.transitionId, - }); - const sceneConfig = _sceneRegistry.get(transition.targetSceneId); - if (!sceneConfig) { - console.warn(`[runtime] transition:activate — target scene not registered: ${transition.targetSceneId}`); - return; - } - useSceneStore.getState().setScene(sceneConfig.id, { - id: sceneConfig.id, - label: sceneConfig.label, - background: sceneConfig.background, - playerSpawn: sceneConfig.playerSpawn, - ground: sceneConfig.ground, - walls: sceneConfig.walls, - interactions: sceneConfig.interactions, - }); - bus.emit("transition:completed", { - type: "transition:completed", - fromSceneId, - toSceneId: transition.targetSceneId, - }); - }); - - commands.register("transition:cancel", (cmd) => { - useSceneStore.getState().setTransitionItemOccupying(cmd.transitionId, undefined); - }); - - // --------------------------------------------------------------------------- - // Formally deferred executors (v0.2.0) - // --------------------------------------------------------------------------- - - commands.register("player:stop", (cmd) => - console.warn( - `[runtime] executor deferred to v0.2.0: ${cmd.type} — requires renderer-r3f DI prop for cancelTarget. See docs/phases/phase-5-publish/tasks/02-wire-pending-commands.md#aplazados`, - ), - ); - - commands.register("inventory:pickup", (cmd) => - console.warn( - `[runtime] executor deferred to v0.2.0: ${cmd.type} — requires UI context (which interaction was clicked). See docs/phases/phase-9-placed-items-agnóstic/README.md#phase-d`, - ), - ); - - commands.register("inventory:drop", (cmd) => - console.warn( - `[runtime] executor deferred to v0.2.0: ${cmd.type} — requires UI context (drag coordinates, target interaction). See docs/phases/phase-9-placed-items-agnóstic/README.md#phase-d`, - ), - ); - - const runtime: GameRuntime = { - getScenes: () => Object.fromEntries(_sceneRegistry), - getItems: () => Object.fromEntries(_itemRegistry), - getRules: () => Object.fromEntries(_ruleRegistry), - executeCommand: (cmd) => commands.execute(cmd), - on: (type: T, handler: GameEventHandler) => - bus.on(type, handler as (data: unknown) => void), - emit: (event: GameEvent) => bus.emit(event.type, event), - dispose: () => { - bus.clear(); - commands.clear(); - setSceneStoreEmitter(null); - if (_runtimeHandle === runtime) _runtimeHandle = null; - }, - }; - - _runtimeHandle = runtime; - return runtime; -} - -/** - * Devuelve el handle del runtime activo (creado por `createGameRuntime`). - * Retorna `null` si no se ha inicializado o tras llamar a `dispose()`. - * - * Útil para acceder al runtime desde componentes o callbacks que no - * tienen acceso directo al handle (ej. GameTouchCanvas). - */ -export function getGameRuntime(): GameRuntime | null { - return _runtimeHandle; -} - -/** Lee snapshot del estado público del runtime sin usar hooks React. */ -export function getGameState(): GameState { - return toGameState(useSceneStore.getState()); -} - -/** Lee acciones públicas del runtime sin usar hooks React. */ -export function getGameActions(): GameActions { - const state = useSceneStore.getState(); - return { - setScene: (id: string) => { - const sceneConfig = _sceneRegistry.get(id); - if (!sceneConfig) { - console.warn(`Scene not registered: ${id}`); - return; - } - state.setScene(id, { - id: sceneConfig.id, - label: sceneConfig.label, - background: sceneConfig.background, - playerSpawn: sceneConfig.playerSpawn, - ground: sceneConfig.ground, - walls: sceneConfig.walls, - interactions: sceneConfig.interactions, - }); - }, - setPlayerPosition: state.setPlayerPosition, - requestRespawn: state.requestRespawn, - }; -} - -/** Hook para seleccionar estado de juego desde la API pública. */ -export function useGameState(selector: (state: GameState) => T): T { - return useSceneStore((state) => selector(toGameState(state))); -} +export type { + GameSceneConfig, + GameItemDropOutcome, + GameItemRule, + GameItemConfig, + GameRuleConfig, + GameRuntimeEvent, + GameRuntimeEventHandler, + GameRuntime, + GameState, + GameActions, + InventoryUIAdapter, + DialogUIAdapter, + GameRuntimeConfig, +} from "@pointclick-engine/engine-core"; -/** Hook para obtener acciones públicas con referencia estable. */ -export function useGameActions(): GameActions { - return useSceneStore( - useShallow((state) => ({ - setScene: (id: string) => { - const sceneConfig = _sceneRegistry.get(id); - if (!sceneConfig) { - console.warn(`Scene not registered: ${id}`); - return; - } - state.setScene(id, { - id: sceneConfig.id, - label: sceneConfig.label, - background: sceneConfig.background, - playerSpawn: sceneConfig.playerSpawn, - ground: sceneConfig.ground, - walls: sceneConfig.walls, - interactions: sceneConfig.interactions, - }); - }, - setPlayerPosition: state.setPlayerPosition, - requestRespawn: state.requestRespawn, - })), - ); -} +export { + registerScene, + registerItem, + registerRule, + createGameRuntime, + getGameRuntime, + getGameState, + getGameActions, +} from "@pointclick-engine/engine-core"; -/** Integración pública de viewport/canvas para consumir el runtime. */ -export function GameViewport({ debug, onRuntimeEvent }: GameViewportProps) { - return createElement(GameCanvasCore as ComponentType, { - debug, - onRuntimeEvent, - }); -} +// Viewport jugable (vive en el renderer). Mantiene el contrato v1: `GameViewport` +// y `GameViewportProps` con `debug` y `onRuntimeEvent`. +export { GameViewport } from "@pointclick-engine/engine-renderer-r3f"; +export type { GameViewportProps } from "@pointclick-engine/engine-renderer-r3f"; diff --git a/apps/web-demo/app/lib/engine/render/SpeechBubble.tsx b/apps/web-demo/app/lib/engine/render/SpeechBubble.tsx deleted file mode 100644 index b63a71c..0000000 --- a/apps/web-demo/app/lib/engine/render/SpeechBubble.tsx +++ /dev/null @@ -1,242 +0,0 @@ -"use client"; - -import { RoundedBox, Text } from "@react-three/drei"; -import { useEffect, useMemo, useRef, useState } from "react"; - -import { browserTimerAdapter, type TimerHandle } from "../../platform-web"; -import { useSceneStore } from "@pointclick-engine/engine-core"; - -type SpeechBubbleProps = { - text: string; - visible: boolean; - trigger: number; - charsPerSecond?: number; - onDismiss?: () => void; -}; - -const SPRITE_HALF_WIDTH_WORLD = 0.62; -const BUBBLE_GAP_WORLD = 0.22; -const DEPTH_FAR_Z = -16; -const DEPTH_NEAR_Z = 8; -const SPRITE_MIN_SCALE = 1.4; -const SPRITE_MAX_SCALE = 2.94; -const SPRITE_HALF_WIDTH_FACTOR = 0.36; -const BORDER_PADDING = 0.09; -const SPRITE_CENTER_Y_OFFSET = -0.95; -const BUBBLE_HEADROOM = -1; -const TEXT_PADDING_X = 0.2; -const TEXT_PADDING_Y = 0.16; -const FONT_SIZE = 0.2; -const LINE_HEIGHT = 1.18; -const AVG_CHAR_WIDTH_WORLD = 0.096; -const MIN_BUBBLE_WIDTH = 0.6; -const MAX_BUBBLE_WIDTH = 5.2; -const MIN_BUBBLE_HEIGHT = 0.45; -const MAX_BUBBLE_HEIGHT = 3.8; -const MS_PER_WORD_READ = 286; -const MIN_READ_MS = 2080; -const MAX_READ_MS = 10400; - -function clamp(value: number, min: number, max: number) { - return Math.max(min, Math.min(max, value)); -} - -function lerp(start: number, end: number, t: number) { - return start + (end - start) * t; -} - -function wrapParagraphByWords(paragraph: string, maxCharsPerLine: number) { - const words = paragraph.trim().split(/\s+/).filter(Boolean); - if (words.length === 0) return [""]; - - const lines: string[] = []; - let currentLine = words[0]; - - for (let index = 1; index < words.length; index += 1) { - const candidate = `${currentLine} ${words[index]}`; - if (candidate.length <= maxCharsPerLine) { - currentLine = candidate; - } else { - lines.push(currentLine); - currentLine = words[index]; - } - } - - lines.push(currentLine); - return lines; -} - -export default function SpeechBubble({ - text, - visible, - trigger, - charsPerSecond = 30, - onDismiss, -}: SpeechBubbleProps) { - const playerPosition = useSceneStore((state) => state.playerPosition); - const ground = useSceneStore((state) => state.scene.ground); - const normalizedText = useMemo(() => text.trim(), [text]); - const [displayedText, setDisplayedText] = useState(""); - const dismissTimerRef = useRef(null); - - // ── Layout estático: calculado UNA vez por diálogo (dep: normalizedText) ── - // wrappedText: el texto con \n explícitos en los saltos de línea. - // - El efecto tipea sobre wrappedText → cada palabra aparece ya en su - // línea final desde el primer carácter. Nunca salta de línea. - // bubbleWidth / textMaxWidth fijos desde el inicio → troika nunca - // re-envuelve mientras se tipea, eliminando el baile de palabras. - // NOTA: los espacios entre palabras que se convierten en \n tienen la - // misma longitud (1 char) → los índices del tipeo coinciden exactamente. - const { bubbleWidth, textMaxWidth, fullBubbleHeight, wrappedText } = useMemo(() => { - const fullText = normalizedText.length > 0 ? normalizedText : " "; - const totalChars = Math.max(1, fullText.length); - const targetCPL = clamp(Math.round(Math.sqrt(totalChars) * 2.4), 18, 36); - const paragraphs = fullText.split("\n"); - const wrappedFull = paragraphs.flatMap((p) => - p.trim().length === 0 ? [""] : wrapParagraphByWords(p, targetCPL), - ); - const longestChars = Math.max(1, ...wrappedFull.map((l) => l.length)); - const rawTextWidth = clamp( - longestChars * AVG_CHAR_WIDTH_WORLD, - MIN_BUBBLE_WIDTH - TEXT_PADDING_X * 2, - MAX_BUBBLE_WIDTH - TEXT_PADDING_X * 2, - ); - const bw = clamp(rawTextWidth + TEXT_PADDING_X * 2, MIN_BUBBLE_WIDTH, MAX_BUBBLE_WIDTH); - const fullLineCount = Math.max(1, wrappedFull.length); - const fbh = clamp( - fullLineCount * FONT_SIZE * LINE_HEIGHT + TEXT_PADDING_Y * 2, - MIN_BUBBLE_HEIGHT, - MAX_BUBBLE_HEIGHT, - ); - return { - bubbleWidth: bw, - textMaxWidth: bw - TEXT_PADDING_X * 2, - fullBubbleHeight: fbh, - wrappedText: wrappedFull.join("\n"), - }; - }, [normalizedText]); - - // ── Efecto de tipeo ──────────────────────────────────────────────────────── - useEffect(() => { - if (!visible || wrappedText.length === 0) return; - - let index = 0; - const msPerChar = Math.max(14, Math.floor(1000 / Math.max(1, charsPerSecond))); - - const timer = browserTimerAdapter.setInterval(() => { - index += 1; - setDisplayedText(wrappedText.slice(0, index)); - - if (index >= wrappedText.length) { - browserTimerAdapter.clearInterval(timer); - - if (onDismiss) { - const wordCount = normalizedText.trim().split(/\s+/).filter(Boolean).length; - const readMs = clamp(wordCount * MS_PER_WORD_READ, MIN_READ_MS, MAX_READ_MS); - dismissTimerRef.current = browserTimerAdapter.setTimeout(onDismiss, readMs); - } - } - }, msPerChar); - - return () => { - browserTimerAdapter.clearInterval(timer); - if (dismissTimerRef.current !== null) { - browserTimerAdapter.clearTimeout(dismissTimerRef.current); - dismissTimerRef.current = null; - } - }; - }, [charsPerSecond, wrappedText, normalizedText, onDismiss, trigger, visible]); - - const shouldShowLeft = useMemo(() => { - const worldEdgePadding = 0.9; - const spaceLeft = playerPosition[0] - ground.minX - worldEdgePadding; - const spaceRight = ground.maxX - playerPosition[0] - worldEdgePadding; - return spaceLeft > spaceRight; - }, [ground.maxX, ground.minX, playerPosition]); - - const depthFactor = useMemo(() => { - return clamp((playerPosition[2] - DEPTH_FAR_Z) / (DEPTH_NEAR_Z - DEPTH_FAR_Z), 0, 1); - }, [playerPosition]); - - const spriteScale = useMemo(() => { - return lerp(SPRITE_MIN_SCALE, SPRITE_MAX_SCALE, depthFactor); - }, [depthFactor]); - - // ── Alto dinámico: displayedText ya tiene \n → solo contar líneas ───────── - const bubbleHeight = useMemo(() => { - const lineCount = Math.max(1, displayedText.split("\n").length); - const textHeight = lineCount * FONT_SIZE * LINE_HEIGHT; - return clamp(textHeight + TEXT_PADDING_Y * 2, MIN_BUBBLE_HEIGHT, MAX_BUBBLE_HEIGHT); - }, [displayedText]); - - if (!visible || normalizedText.length === 0) { - return null; - } - - const spriteHalfWidthWorld = Math.max(SPRITE_HALF_WIDTH_WORLD, spriteScale * SPRITE_HALF_WIDTH_FACTOR); - const sideOffset = spriteHalfWidthWorld + BUBBLE_GAP_WORLD; - const offsetX = shouldShowLeft ? -sideOffset : sideOffset; - // offsetY = borde SUPERIOR del bocadillo. Crece hacia abajo desde aquí. - const offsetY = (2 * spriteScale) + SPRITE_CENTER_Y_OFFSET + BUBBLE_HEADROOM; - const bubbleCenterX = shouldShowLeft - ? offsetX - bubbleWidth / 2 - : offsetX + bubbleWidth / 2; - const arrowBaseX = shouldShowLeft ? offsetX + 0.07 : offsetX - 0.07; - const arrowRotationZ = shouldShowLeft ? -Math.PI / 2 : Math.PI / 2; - - return ( - // Grupo anclado al borde superior del bocadillo - - {/* Bocadillo: centro en -bubbleHeight/2 → parte superior fija en Y=0 */} - - - - - - - - {/* maxWidth = textMaxWidth → padding simétrico izquierda/derecha. - Las líneas ya vienen pre-envueltas con \n explícitos, así que - troika no necesita re-envolver; el valor actúa solo como límite - de borde derecho para igualar el padding izquierdo. */} - - {displayedText} - - - - {/* Rabillo: 30% desde el borde superior del bocadillo completo — - fijo durante el tipeo, entre el borde superior y el centro */} - - - - - - - - - - ); -} diff --git a/apps/web-demo/app/lib/engine/render/scene/SceneCollisionSphere.tsx b/apps/web-demo/app/lib/engine/render/scene/SceneCollisionSphere.tsx deleted file mode 100644 index e5abac6..0000000 --- a/apps/web-demo/app/lib/engine/render/scene/SceneCollisionSphere.tsx +++ /dev/null @@ -1,31 +0,0 @@ -"use client"; - -import { useLoader } from "@react-three/fiber"; -import { BallCollider, RigidBody } from "@react-three/rapier"; -import { TextureLoader } from "three"; - -import { useSceneStore } from "@pointclick-engine/engine-core"; - -export function SceneCollisionSphere() { - const globeTexture = useLoader(TextureLoader, "/globe.svg"); - const groundY = useSceneStore((s) => s.scene.ground.y); - const posY = groundY + 0.1 + 0.5; - - return ( - - - - - - - - ); -} diff --git a/apps/web-demo/app/lib/engine/render/scene/SceneGround.tsx b/apps/web-demo/app/lib/engine/render/scene/SceneGround.tsx deleted file mode 100644 index c0fd86f..0000000 --- a/apps/web-demo/app/lib/engine/render/scene/SceneGround.tsx +++ /dev/null @@ -1,126 +0,0 @@ -"use client"; - -import { useMemo } from "react"; -import { CuboidCollider, RigidBody } from "@react-three/rapier"; - -import { useSceneStore } from "@pointclick-engine/engine-core"; - -const checkerVertexShader = /* glsl */` - varying vec2 vUv; - void main() { - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); - } -`; - -const checkerFragmentShader = /* glsl */` - varying vec2 vUv; - uniform float uCells; - void main() { - vec2 cell = floor(vUv * uCells); - float checker = mod(cell.x + cell.y, 2.0); - vec3 col = checker > 0.5 ? vec3(0.0, 1.0, 0.25) : vec3(0.0, 0.0, 0.0); - float alpha = checker > 0.5 ? 0.28 : 0.04; - gl_FragColor = vec4(col, alpha); - } -`; - -export function SceneGround({ - onClickWorld, - onHoverWorld, - debug, - depthNearZ, - depthFarZ, -}: { - onClickWorld: (x: number, z: number) => void; - onHoverWorld?: (x: number, z: number) => void; - debug: boolean; - depthNearZ: number; - depthFarZ: number; -}) { - const ground = useSceneStore((s) => s.scene.ground); - - const width = ground.maxX - ground.minX; - const depth = ground.maxZ - ground.minZ; - const centerX = (ground.minX + ground.maxX) / 2; - const centerZ = (ground.minZ + ground.maxZ) / 2; - - const segX = Math.round(width / 2); - const segZ = Math.round(depth / 2); - - const gy = ground.y + 0.02; - const t = 0.05; - const borderWallHalfHeight = 3; - const borderWallHalfThickness = 0.35; - const borderWallCenterY = ground.y + borderWallHalfHeight; - - const cells = Math.max(segX, segZ); - const checkerUniforms = useMemo(() => ({ uCells: { value: cells } }), [cells]); - - return ( - <> - - - { - e.stopPropagation(); - onClickWorld(e.point.x, e.point.z); - }} - onPointerMove={(e) => { - if (!onHoverWorld) return; - onHoverWorld(e.point.x, e.point.z); - }} - > - - - - - - - - - - - - - - - - - - - {debug && ( - <> - null}> - - - - null}> - - - - - - - - - - - - - - - - - - )} - - ); -} diff --git a/apps/web-demo/app/lib/engine/render/scene/SceneWallPointPreview.tsx b/apps/web-demo/app/lib/engine/render/scene/SceneWallPointPreview.tsx deleted file mode 100644 index 2f5af67..0000000 --- a/apps/web-demo/app/lib/engine/render/scene/SceneWallPointPreview.tsx +++ /dev/null @@ -1,49 +0,0 @@ -"use client"; - -import { useMemo } from "react"; -import type { Vector2 } from "three"; - -type WallPointPreview = { - start: Vector2; - end: Vector2; -}; - -export function SceneWallPointPreview({ - preview, - groundY, -}: { - preview: WallPointPreview | null; - groundY: number; -}) { - const pointPreviewLength = useMemo(() => { - if (!preview) return 0; - return Math.sqrt((preview.end.x - preview.start.x) ** 2 + (preview.end.y - preview.start.y) ** 2); - }, [preview]); - - const pointPreviewMidX = preview ? (preview.start.x + preview.end.x) / 2 : 0; - const pointPreviewMidZ = preview ? (preview.start.y + preview.end.y) / 2 : 0; - const pointPreviewRotationY = preview - ? -Math.atan2(preview.end.y - preview.start.y, preview.end.x - preview.start.x) - : 0; - - if (!preview) return null; - - return ( - <> - - - - - - - - - {pointPreviewLength >= 0.01 && ( - - - - - )} - - ); -} diff --git a/apps/web-demo/app/lib/engine/render/scene/SceneWalls.tsx b/apps/web-demo/app/lib/engine/render/scene/SceneWalls.tsx deleted file mode 100644 index 7ac0f2b..0000000 --- a/apps/web-demo/app/lib/engine/render/scene/SceneWalls.tsx +++ /dev/null @@ -1,130 +0,0 @@ -"use client"; - -import { CuboidCollider, RigidBody } from "@react-three/rapier"; - -import { type GameSceneWall, useSceneStore } from "@pointclick-engine/engine-core"; -import { useSceneEditorStore } from "../../../../store/sceneEditorStore"; -import { computeWallSegments } from "@pointclick-engine/engine-renderer-r3f"; -import { SceneWallPlane } from "@pointclick-engine/engine-renderer-r3f"; - -export type WallResizeHandle = "x+" | "x-" | "z+" | "z-"; - -export function SceneWalls({ - debug, - onStartWallMove, - onStartWallResize, -}: { - debug: boolean; - onStartWallMove: (index: number, pointX: number, pointZ: number) => void; - onStartWallResize: (index: number, handle: WallResizeHandle) => void; -}) { - const walls = useSceneStore((s) => s.scene.walls); - const selectedWallIndex = useSceneEditorStore((s) => s.selectedWallIndex); - const selectWall = useSceneEditorStore((s) => s.selectWall); - - return ( - <> - {walls.map((wall: GameSceneWall, i: number) => { - const segments = computeWallSegments(wall.halfSize, wall.openings); - const isSelected = selectedWallIndex === i; - - return ( - - {/* One collider per solid segment → openings have no collision */} - {segments.map((seg, si) => ( - - ))} - - {debug && ( - <> - {/* One wireframe mesh per segment — the gaps ARE the openings */} - {segments.map((seg, si) => ( - { - e.stopPropagation(); - selectWall(i); - onStartWallMove(i, e.point.x, e.point.z); - }} - > - - - - ))} - - {/* Resize handles — always based on full wall halfSize */} - {isSelected && ( - <> - { - e.stopPropagation(); - onStartWallResize(i, "x+"); - }} - > - - - - { - e.stopPropagation(); - onStartWallResize(i, "x-"); - }} - > - - - - { - e.stopPropagation(); - onStartWallResize(i, "z+"); - }} - > - - - - { - e.stopPropagation(); - onStartWallResize(i, "z-"); - }} - > - - - - - )} - - )} - - ); - })} - - {/* Wall texture planes — rendered outside RigidBody, camera-facing */} - {walls.map((wall: GameSceneWall, i: number) => - wall.textureUrl ? ( - - ) : null, - )} - - ); -} diff --git a/apps/web-demo/app/lib/engine/render/sprite/DavidSprite.tsx b/apps/web-demo/app/lib/engine/render/sprite/DavidSprite.tsx deleted file mode 100644 index a3ce1c9..0000000 --- a/apps/web-demo/app/lib/engine/render/sprite/DavidSprite.tsx +++ /dev/null @@ -1,230 +0,0 @@ -"use client"; - -import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from "react"; -import { useFrame, useLoader, useThree } from "@react-three/fiber"; -import { - ClampToEdgeWrapping, - FrontSide, - Mesh, - MeshBasicMaterial, - NearestFilter, - SRGBColorSpace, - Texture, - TextureLoader, -} from "three"; - -import type { SpriteAnimation } from "./clips"; - -const SHOULD_LOG_SPRITE_STATE = process.env.NODE_ENV !== "production"; -let spriteInstanceCounter = 0; - -function logSpriteState(event: string, payload: Record) { - if (!SHOULD_LOG_SPRITE_STATE) return; - if (typeof window !== "undefined") { - const nextEntry = { scope: "sprite", event, payload, ts: Date.now() }; - const currentTrace = ((window as unknown as { __gameTrace?: unknown[] }).__gameTrace ?? []); - (window as unknown as { __gameTrace: unknown[] }).__gameTrace = [...currentTrace, nextEntry].slice(-300); - } - console.info(`[sprite-state] ${event}`, payload); -} - -type DavidSpriteProps = { - animation: SpriteAnimation; - preloadAnimations?: readonly SpriteAnimation[]; - meshRef?: React.RefObject; - scale?: [number, number, number]; - isPaused?: boolean; -}; - -export type DavidSpriteHandle = { - nextFrame: () => void; -}; - -function cloneTexture(sourceTexture: Texture) { - const clonedTexture = sourceTexture.clone(); - clonedTexture.colorSpace = SRGBColorSpace; - clonedTexture.magFilter = NearestFilter; - clonedTexture.minFilter = NearestFilter; - clonedTexture.wrapS = ClampToEdgeWrapping; - clonedTexture.wrapT = ClampToEdgeWrapping; - clonedTexture.generateMipmaps = false; - clonedTexture.needsUpdate = true; - return clonedTexture; -} - -const DavidSprite = forwardRef( - ({ animation, preloadAnimations, meshRef, scale = [2.2, 2.2, 1], isPaused = false }, ref) => { - const spriteInstanceIdRef = useRef(null); - if (spriteInstanceIdRef.current == null) { - spriteInstanceIdRef.current = ++spriteInstanceCounter; - } - - const internalRef = useRef(null); - const targetRef = meshRef ?? internalRef; - const materialRef = useRef(null); - const renderer = useThree((state) => state.gl); - const preloadedFrames = useMemo(() => { - if (!preloadAnimations?.length) { - return null; - } - - const uniqueFrames = new Set(); - preloadAnimations.forEach((clip) => { - clip.frames.forEach((frame) => { - uniqueFrames.add(frame); - }); - }); - - return Array.from(uniqueFrames); - }, [preloadAnimations]); - - const framesToLoad = preloadedFrames ?? animation.frames; - - const sourceTextures = useLoader(TextureLoader, framesToLoad) as unknown as Texture[]; - - const texturesByFrame = useMemo(() => { - const byFrame = new Map(); - framesToLoad.forEach((frame, index) => { - const sourceTexture = sourceTextures[index]; - if (!sourceTexture) return; - byFrame.set(frame, cloneTexture(sourceTexture)); - }); - return byFrame; - }, [framesToLoad, sourceTextures]); - - const textures = useMemo( - () => - animation.frames - .map((frame) => texturesByFrame.get(frame)) - .filter((texture): texture is Texture => Boolean(texture)), - [animation.frames, texturesByFrame], - ); - - useEffect(() => { - const initTexture = (renderer as unknown as { initTexture?: (texture: Texture) => void }).initTexture; - if (!initTexture) return; - - texturesByFrame.forEach((texture) => { - initTexture(texture); - }); - }, [renderer, texturesByFrame]); - - const frameAspect = useMemo(() => { - const image = textures[0]?.image as { width?: number; height?: number } | undefined; - if (!image?.width || !image?.height) { - return 1; - } - - return image.width / image.height; - }, [textures]); - const frameCursorRef = useRef(0); - const frameTimeRef = useRef(0); - - useEffect(() => { - const instanceId = spriteInstanceIdRef.current; - logSpriteState("mount", { - instanceId, - preloadClipCount: preloadAnimations?.length ?? 1, - loadedFrameCount: framesToLoad.length, - }); - - return () => { - logSpriteState("unmount", { instanceId }); - }; - }, [framesToLoad.length, preloadAnimations]); - - useEffect(() => { - logSpriteState("animation-change", { - instanceId: spriteInstanceIdRef.current, - fps: animation.fps, - frameCount: animation.frames.length, - firstFrame: animation.frames[0], - }); - }, [animation]); - - useEffect(() => { - frameCursorRef.current = 0; - frameTimeRef.current = 0; - - const firstTexture = textures[0]; - const material = materialRef.current; - - if (material && firstTexture) { - material.map = firstTexture; - material.needsUpdate = true; - } - }, [animation, textures]); - - useImperativeHandle( - ref, - () => ({ - nextFrame: () => { - if (textures.length <= 1) { - return; - } - - const clipLength = textures.length; - frameCursorRef.current = animation.loop ?? true - ? (frameCursorRef.current + 1) % clipLength - : Math.min(frameCursorRef.current + 1, clipLength - 1); - - const material = materialRef.current; - const nextTexture = textures[frameCursorRef.current]; - - if (material && nextTexture) { - material.map = nextTexture; - material.needsUpdate = true; - } - }, - }), - [animation.loop, textures], - ); - - useFrame((_, delta) => { - if (isPaused || textures.length <= 1) { - return; - } - - frameTimeRef.current += delta; - const stepTime = 1 / animation.fps; - - if (frameTimeRef.current < stepTime) { - return; - } - - const steps = Math.floor(frameTimeRef.current / stepTime); - frameTimeRef.current -= steps * stepTime; - - frameCursorRef.current = animation.loop ?? true - ? (frameCursorRef.current + steps) % textures.length - : Math.min(frameCursorRef.current + steps, textures.length - 1); - - const material = materialRef.current; - const nextTexture = textures[frameCursorRef.current]; - - if (material && nextTexture) { - material.map = nextTexture; - material.needsUpdate = true; - } - }); - - const [sx, sy, sz] = scale; - const meshScale = useMemo<[number, number, number]>( - () => [animation.flipX ? -Math.abs(sx) : Math.abs(sx), sy, sz], - [animation.flipX, sx, sy, sz], - ); - const planeWidth = 2 * frameAspect; - const planeHeight = 2; - - return ( - - - - - ); - }, -); - -DavidSprite.displayName = "DavidSprite"; - -export default DavidSprite; diff --git a/apps/web-demo/app/lib/engine/render/sprite/clips.ts b/apps/web-demo/app/lib/engine/render/sprite/clips.ts deleted file mode 100644 index b9d63ab..0000000 --- a/apps/web-demo/app/lib/engine/render/sprite/clips.ts +++ /dev/null @@ -1,72 +0,0 @@ -export type SpriteAnimation = { - frames: readonly string[]; - fps: number; - loop?: boolean; - flipX?: boolean; -}; - -export type GameCharacterName = "Dave"; - -export type GameDirection = "idle" | "north" | "south" | "west" | "east"; - -type CharacterSprites = Record; - -type CharacterGridPosition = { - name: GameCharacterName; - column: 0 | 1 | 2; - row: 0 | 1 | 2; -}; - -const DAVE_SPRITE_ROOT = "/assets/sprites/david"; - -const createFrameUrls = (prefix: string, count: number, startIndex = 1) => - Array.from( - { length: count }, - (_, index) => - `${DAVE_SPRITE_ROOT}/${prefix}_${String(startIndex + index).padStart(4, "0")}.png`, - ); - -const DAVE_CHARACTER_SPRITES: CharacterSprites = { - idle: { - frames: [`${DAVE_SPRITE_ROOT}/david_idle.png`], - fps: 1, - loop: true, - }, - north: { - frames: createFrameUrls("david-walk-north", 9).slice().reverse(), - fps: 16, - loop: true, - }, - south: { - frames: createFrameUrls("david-walk-south", 8, 3), - fps: 16, - loop: true, - }, - west: { - frames: createFrameUrls("david-walk-west", 9).slice().reverse(), - fps: 16, - loop: true, - flipX: true, - }, - east: { - frames: createFrameUrls("david-walk-west", 9).slice().reverse(), - fps: 16, - loop: true, - }, -}; - -export const DAVE_IDLE_SPEAKING: SpriteAnimation = { - frames: createFrameUrls("david_speaking", 8), - fps: 8, - loop: true, -}; - -export const GAME_CHARACTERS = [ - { name: "Dave", column: 0, row: 0 }, -] as const satisfies ReadonlyArray; - -export const GAME_CHARACTER_SPRITES = Object.fromEntries( - GAME_CHARACTERS.map((character) => [character.name, DAVE_CHARACTER_SPRITES]), -) as Record; - -export const DAVE_SPRITES = DAVE_CHARACTER_SPRITES; diff --git a/apps/web-demo/app/lib/engine/render/sprite/speakingAnimation.ts b/apps/web-demo/app/lib/engine/render/sprite/speakingAnimation.ts deleted file mode 100644 index 2752f47..0000000 --- a/apps/web-demo/app/lib/engine/render/sprite/speakingAnimation.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { DAVE_IDLE_SPEAKING, type SpriteAnimation } from "./clips"; - -const BASE_FRAMES = DAVE_IDLE_SPEAKING.frames; -const FRAME_COUNT = BASE_FRAMES.length; - -/** - * Builds a varied speaking animation from the base idle-speaking frames. - * - * Strategy: generates chunks of 2–3 consecutive frames with 1–2 repetitions - * each, then jumps to an overlapping or skipped position. The result is a - * pre-computed frame sequence (~15–20 frames) that loops, giving natural - * mouth movement without a mechanical cycle. - * - * @param seed speechTrigger value — stabilises the pattern for one - * speech event; different dialogues get different patterns. - * @param charsPerSecond text reveal speed → drives fps so mouth matches pace. - */ -export function buildSpeakingAnimation( - seed: number, - charsPerSecond: number, -): SpriteAnimation { - const result: string[] = []; - let pos = seed % FRAME_COUNT; - - // 6 chunks → roughly 15–20 frames before the loop point - for (let chunk = 0; chunk < 6; chunk++) { - const chunkSize = 2 + ((seed * 7 + chunk * 3) % 2); // 2 or 3 - const repeats = 1 + ((seed * 5 + chunk * 11) % 2); // 1 or 2 - - for (let r = 0; r < repeats; r++) { - for (let i = 0; i < chunkSize; i++) { - result.push(BASE_FRAMES[(pos + i) % FRAME_COUNT]); - } - } - - // Advance by chunkSize + a small irregular offset (1 or 2) - const jump = chunkSize + 1 + ((seed * 3 + chunk * 7) % 2); - pos = (pos + jump) % FRAME_COUNT; - } - - // Sync fps to text reveal speed: ~1 mouth move per 4 characters, - // clamped so it always looks natural regardless of text speed. - const fps = Math.max(4, Math.min(10, Math.round(charsPerSecond * 0.25))); - - return { frames: result, fps, loop: true }; -} diff --git a/apps/web-demo/app/lib/engine/runtime/demoViewportOptions.ts b/apps/web-demo/app/lib/engine/runtime/demoViewportOptions.ts new file mode 100644 index 0000000..cf8a485 --- /dev/null +++ b/apps/web-demo/app/lib/engine/runtime/demoViewportOptions.ts @@ -0,0 +1,103 @@ +import { npcToHotspot, useDialogStore } from "@pointclick-engine/engine-core"; +import type { + DialogUIAdapter, + GameRuntimeConfig, + GameScene, + GameSceneTransition, + PlacedSceneItem, +} from "@pointclick-engine/engine-core"; +import type { + GameViewportControllerOptions, + SceneProgressStorage, +} from "@pointclick-engine/engine-renderer-r3f"; + +import { SCENES, DEFAULT_SCENE_ID } from "../../../../demo-content/scenes/scenes"; +import { ITEMS } from "../../../../demo-content/items"; +import { getRandomPhrase } from "../../../../demo-content/dialogs/getRandomPhrase"; +import { demoDictionaries } from "../../../../demo-content/dialogs"; +import { demoDialogues } from "../../../../demo-content/dialogues/guide"; +import { localStorageAdapter } from "../../platform-web"; +import { webAudioAdapter } from "../../platform-web-audio"; +import { audioSettingsStore } from "../../../store/audio"; +import { + loadCurrentSceneId, + saveCurrentSceneId, + startGamePersistence, +} from "../../gamePersistence"; +import { DEMO_AUDIO_DEFAULTS } from "./useDemoAudio"; + +const SCENE_STORAGE: SceneProgressStorage = { + loadSceneId: loadCurrentSceneId, + saveSceneId: saveCurrentSceneId, +}; + +// Transiciones de la demo por id (para el sonido declarativo `triggerSoundUrl`). +const DEMO_TRANSITIONS: Record = Object.fromEntries( + Object.values(SCENES).flatMap((sc) => (sc.transitions ?? []).map((t) => [t.id, t] as const)), +); + +/** En la demo, los items sin `sceneId` (partidas antiguas) cuentan como de personalRoom. */ +const filterDemoPlacedItems = (item: PlacedSceneItem, sceneId: string): boolean => + item.sceneId === sceneId || (item.sceneId === undefined && sceneId === "personalRoom"); + +/** + * La demo mantiene en el store su escena completa (SCENES) y no la proyeccion del registro del + * core (`toRuntimeScene`), asi que proyecta ella los NPC a hotspots: `hotspot:interact` los + * busca en `scene.hotspots` de la escena activa. + */ +function resolveDemoScene(id: string): GameScene | null { + const scene = SCENES[id]; + if (!scene) return null; + if (!scene.npcs?.length) return scene; + return { ...scene, hotspots: [...(scene.hotspots ?? []), ...scene.npcs.map(npcToHotspot)] }; +} + +/** Opciones propias de la demo para `useGameViewportController` (datos y callbacks de su juego). */ +export const DEMO_VIEWPORT_OPTIONS: GameViewportControllerOptions = { + initialSceneId: DEFAULT_SCENE_ID, + storage: SCENE_STORAGE, + // La demo mantiene en el store su escena completa (SCENES), no la proyeccion del registro del core. + resolveScene: resolveDemoScene, + // Los diccionarios de la demo se registran en su getRandomPhrase. + getPhrase: (key) => getRandomPhrase(key), + filterPlacedItems: filterDemoPlacedItems, + // Guardado automatico de la partida (ya hidratada al importar gamePersistence). + startPersistence: startGamePersistence, + audio: { + port: webAudioAdapter, + defaults: DEMO_AUDIO_DEFAULTS, + scenes: SCENES, + items: ITEMS, + transitions: DEMO_TRANSITIONS, + settingsStore: audioSettingsStore, + }, +}; + +/** + * `dialog:trigger` (y por tanto `say`, `onEnter`, `blocked`...) resuelve el texto en las reglas + * del runtime, no en los diccionarios i18n de la demo. Este adaptador muestra el bocadillo con + * la frase del diccionario del idioma activo para la clave. + */ +const DEMO_DIALOG_ADAPTER: DialogUIAdapter = { + show: (text, dialogKey, speaker) => + useDialogStore.getState().show(dialogKey ? getRandomPhrase(dialogKey) : text, dialogKey, speaker), + hide: () => useDialogStore.getState().dismiss(), +}; + +/** Claves de dialogo de la demo (en cualquier idioma), para que `validateContent` las compruebe. */ +const DEMO_DIALOG_KEYS: ReadonlySet = new Set( + Object.values(demoDictionaries).flatMap((dictionary) => Object.keys(dictionary)), +); + +/** + * Configuracion de `createGameRuntime` de la demo (la comparten `/`, `/debug` y + * `/example-bridge`): contenido, almacenamiento de la partida y puerto de dialogo. + */ +export const DEMO_RUNTIME_CONFIG: GameRuntimeConfig = { + scenes: Object.values(SCENES), + items: Object.values(ITEMS), + dialogues: demoDialogues, + storage: localStorageAdapter, + dialogAdapter: DEMO_DIALOG_ADAPTER, + dialogKeys: DEMO_DIALOG_KEYS, +}; diff --git a/apps/web-demo/app/lib/engine/runtime/useDemoAudio.ts b/apps/web-demo/app/lib/engine/runtime/useDemoAudio.ts new file mode 100644 index 0000000..415832f --- /dev/null +++ b/apps/web-demo/app/lib/engine/runtime/useDemoAudio.ts @@ -0,0 +1,77 @@ +import { useCallback, useEffect, useRef } from "react"; + +import { + useSceneStore, + type AudioDefaultsConfig, + type PlayerWalkingState, +} from "@pointclick-engine/engine-core"; +import { webAudioAdapter } from "../../platform-web-audio"; +import { audioSettingsStore } from "../../../store/audio"; +import { useInventoryStore } from "../../../store/inventoryStore"; + +/** + * Sonidos por defecto de la demo (datos, no lógica). Los sonidos específicos + * viven en los datos de cada ítem (`pickupSoundUrl`/`dropSoundUrl`) y de cada + * transición (`triggerSoundUrl`). + */ +export const DEMO_AUDIO_DEFAULTS: AudioDefaultsConfig = { + clickSoundUrl: "/assets/audio/sfx/click.ogg", + pickupSoundUrl: "/assets/audio/sfx/pickup-default.ogg", + dropSoundUrl: "/assets/audio/sfx/drop-default.ogg", + transitionSoundUrl: "/assets/audio/sfx/transition-default.ogg", +}; + +/** + * Sonidos de UI de la demo: sincroniza los ajustes de audio con el adaptador web y + * suena el click de la mochila y el de empezar a caminar. Devuelve el sonido de las + * letras del bocadillo. + */ +export function useDemoUiSounds() { + // Sync audio settings (already hydrated from localStorage at module load) + // to the webAudioAdapter on mount AND on every subsequent change. Without + // the initial apply the adapter starts at its defaults and ignores any + // persisted mute until the user toggles a setting. + useEffect(() => { + const apply = (state: ReturnType) => { + webAudioAdapter.setMuted("master", state.masterMuted); + webAudioAdapter.setMuted("music", state.musicMuted); + webAudioAdapter.setMuted("sfx", state.sfxMuted); + webAudioAdapter.setVolume("master", state.masterVolume); + webAudioAdapter.setVolume("music", state.musicVolume); + webAudioAdapter.setVolume("sfx", state.sfxVolume); + }; + apply(audioSettingsStore.getState()); + return audioSettingsStore.subscribe(apply); + }, []); + + // Click sound for inventory toggle + const isInventoryOpen = useInventoryStore((s) => s.isOpen); + useEffect(() => { + webAudioAdapter.playSound({ + id: "click", + url: "/assets/audio/sfx/click.ogg", + category: "ui", + }); + }, [isInventoryOpen]); + + // Click sound on canvas for pathfinding + const playerWalkingState = useSceneStore((s) => s.playerWalkingState); + const prevWalkingRef = useRef(null); + useEffect(() => { + // Play click sound when walking starts (transition from null to walking state) + if (playerWalkingState && !prevWalkingRef.current) { + webAudioAdapter.playSound({ + id: "click-canvas", + url: "/assets/audio/sfx/click.ogg", + category: "ui", + }); + } + prevWalkingRef.current = playerWalkingState; + }, [playerWalkingState]); + + return useCallback(() => { + const n = Math.floor(Math.random() * 4) + 1; + const url = `/assets/audio/sfx/speak (${n}).mp3`; + webAudioAdapter.playSound({ id: url, url, category: "sfx" }, { volume: 0.35 }); + }, []); +} diff --git a/apps/web-demo/app/lib/engine/runtime/useDemoSceneDebug.ts b/apps/web-demo/app/lib/engine/runtime/useDemoSceneDebug.ts new file mode 100644 index 0000000..6455beb --- /dev/null +++ b/apps/web-demo/app/lib/engine/runtime/useDemoSceneDebug.ts @@ -0,0 +1,59 @@ +"use client"; + +import { useMemo } from "react"; + +import { SCENES } from "../../../../demo-content/scenes/scenes"; +import { useSceneStore } from "@pointclick-engine/engine-core"; +import { getGameRuntime } from "../publicApi"; + +type StoreSetScene = ReturnType["setScene"]; + +/** + * Selector de escena del panel de debug: opciones y `setScene` con entrada animada. + * El estado de escena, la siembra y la persistencia viven en `useGameViewportController` + * (renderer); este hook solo recibe su `storeSetScene`. + */ +export function useDemoSceneDebug(storeSetScene: StoreSetScene) { + const sceneOptions = useMemo( + () => Object.values(SCENES).map((s) => ({ label: s.label, value: s.id })), + [], + ); + + const setScene = useMemo( + () => (id: string) => { + const scene = SCENES[id]; + if (!scene) { + console.warn(`Scene not found: ${id}`); + return; + } + // When changing scene from debug menu, look for a transition to that scene + // and use its spawn/target positions for animated entry + const currentScene = useSceneStore.getState().scene; + const transitionToTarget = currentScene?.transitions?.find((t) => t.targetSceneId === id); + + if (transitionToTarget && "spawnPosition" in transitionToTarget && transitionToTarget.spawnPosition) { + // Use transition's spawn position + const spawnPos = transitionToTarget.spawnPosition; + const targetPos = "targetPosition" in transitionToTarget ? transitionToTarget.targetPosition : undefined; + + storeSetScene(id, scene, spawnPos); + + // Execute walk command if target position exists + if (targetPos) { + setTimeout(() => { + getGameRuntime()?.executeCommand({ + type: "player:walkTo", + position: targetPos, + }); + }, 0); + } + } else { + // No transition found, just change scene normally + storeSetScene(id, scene); + } + }, + [storeSetScene], + ); + + return { sceneOptions, setScene }; +} diff --git a/apps/web-demo/app/lib/engine/runtime/useDoorSystem.ts b/apps/web-demo/app/lib/engine/runtime/useDoorSystem.ts index 4d5de18..9c90d48 100644 --- a/apps/web-demo/app/lib/engine/runtime/useDoorSystem.ts +++ b/apps/web-demo/app/lib/engine/runtime/useDoorSystem.ts @@ -28,11 +28,11 @@ const DOOR_APPROACH_GAP = 1.2; * inside the demo layer, free to evolve into a first-class engine * primitive later without breaking the existing rule wiring. * - * Returns a handler you can plug into `useInventoryRuntimeController`'s - * `onRuntimeEvent` prop. Composable: chain it with other handlers if you + * Returns a handler you can pass as the viewport controller's + * `onRuntimeEvent` option. Composable: chain it with other handlers if you * already have one. */ -export function useDoorSystem({ +export function useDoorEventBridge({ scene, passthrough, }: { @@ -63,21 +63,25 @@ export function useDoorSystem({ [scene, setOpen, passthrough], ); - /** - * Click-goal preprocessor for the runtime's click-to-move pipeline. - * - * Behavior: for each closed door in the active scene, check whether the - * click point is past the door's wall from the player's perspective. - * If so, replace the goal with an "approach point" — a position on the - * player's side of the wall, aligned with the door, offset by the - * wall depth + a small gap. This stops the player in front of the - * locked door instead of routing them around the entire wall. - * - * Limitation: assumes axis-aligned walls (rotationY ≈ 0). For rotated - * walls we currently bail out and return null (use the original goal), - * so the path may still route around. Generalizing this is a future task. - */ - const getEffectiveClickGoal = useCallback( + return handleRuntimeEvent; +} + +/** + * Click-goal preprocessor for the runtime's click-to-move pipeline. + * + * Behavior: for each closed door in the active scene, check whether the + * click point is past the door's wall from the player's perspective. + * If so, replace the goal with an "approach point" — a position on the + * player's side of the wall, aligned with the door, offset by the + * wall depth + a small gap. This stops the player in front of the + * locked door instead of routing them around the entire wall. + * + * Limitation: assumes axis-aligned walls (rotationY ≈ 0). For rotated + * walls we currently bail out and return null (use the original goal), + * so the path may still route around. Generalizing this is a future task. + */ +export function useDoorClickGoal(scene: Scene | undefined) { + return useCallback( (clickX: number, clickZ: number, playerX: number, playerZ: number) => { const doors = scene?.doors; const walls = scene?.walls; @@ -116,6 +120,17 @@ export function useDoorSystem({ }, [scene], ); +} +/** Puente de eventos + preprocesador de click en un solo hook (uso conjunto). */ +export function useDoorSystem({ + scene, + passthrough, +}: { + scene: Scene | undefined; + passthrough?: (event: RuntimeEvent) => void; +}) { + const handleRuntimeEvent = useDoorEventBridge({ scene, passthrough }); + const getEffectiveClickGoal = useDoorClickGoal(scene); return { handleRuntimeEvent, getEffectiveClickGoal }; } diff --git a/apps/web-demo/app/lib/engine/runtime/useInventoryRuntimeController.ts b/apps/web-demo/app/lib/engine/runtime/useInventoryRuntimeController.ts deleted file mode 100644 index d1131e4..0000000 --- a/apps/web-demo/app/lib/engine/runtime/useInventoryRuntimeController.ts +++ /dev/null @@ -1,564 +0,0 @@ -"use client"; - -import { useCallback, useEffect, useRef, useState } from "react"; - -import { getRandomPhrase } from "../../../../demo-content/dialogs/getRandomPhrase"; -import { getGameRuntime } from "../publicApi"; -import { browserEnvironmentAdapter } from "../../platform-web"; -import type { SceneInteraction } from "../../../../demo-content/scenes/scenes"; -import type { PlacedSceneItem } from "@pointclick-engine/engine-core"; -import { useProximityHintController } from "./useProximityHintController"; -import { - emitRuntimeEvent, - type RuntimeEventHandler, -} from "@pointclick-engine/engine-core"; -import { useDialogStore } from "../../../store/dialogStore"; -import { useInventoryStore } from "../../../store/inventoryStore"; -import { usePlacedItemsStore } from "../../../store/placedItemsStore"; -import { - addOneToInventory, - inventoryRuleMessages, - removeOneFromSlot, - resolveInventoryDropHitDecision, - resolveInventoryDropMissDialogKey, - resolveInventoryDropOnPlayerMessage, - resolvePickupPlacedItemDecision, -} from "../../core/rules/inventoryRules"; - -type InventoryStack = { - id: string; - name: string; - spriteUrl: string; - quantity: number; -}; - -type InventorySlots = Array; - -type DraggedInventoryPayload = { - stack: InventoryStack; - fromSlotIndex: number; -}; - -type RuntimeDraggedStack = DraggedInventoryPayload & { - pointerX: number; - pointerY: number; -}; - -function createInitialInventorySlots(): InventorySlots { - return Array.from({ length: 9 }, (_, index) => { - if (index === 0) { - return { - id: "gameboy", - name: "Gameboy", - spriteUrl: "/assets/gameboy/gameboy.png", - quantity: 1, - }; - } - if (index === 1) { - // Gold key seeded so the player can immediately test the dungeon door - // pipeline. Once items can be picked up from scene placements, this - // seed should be removed and the key dropped into a scene instead. - return { - id: "gold-key", - name: "Llave dorada", - spriteUrl: "/assets/key/gold-key.png", - quantity: 1, - }; - } - return null; - }); -} - -function createInitialPlacedItems(sceneId: string): PlacedSceneItem[] { - return [ - { - id: "trophy-ground", - itemId: "trophy", - interactionId: "trophy-ground-pickup", - name: "Trophy", - spriteUrl: "/assets/trophy/trophy.png", - worldPosition: [5.5, -1.3, 22.0], - canPickup: true, - hasCollision: true, - collisionHalfSize: [0.5, 0.8, 0.5], - sceneId, // Track which scene this item belongs to - // No dialog keys for ground pickup - will use defaults from resolvePickupPlacedItemDecision - }, - ]; -} - -export function useInventoryRuntimeController({ - sceneId, - sceneInteractions, - playerPosition, - onRuntimeEvent, -}: { - sceneId: string; - sceneInteractions: SceneInteraction[]; - playerPosition: [number, number, number]; - onRuntimeEvent?: RuntimeEventHandler; -}) { - // Dialog state now lives in dialogStore (wirable via dialog:trigger / dialog:dismiss commands) - const showDialog = useDialogStore((s) => s.show); - const dismissDialog = useDialogStore((s) => s.dismiss); - - // Inventory visibility now lives in inventoryStore (wirable via inventory:toggle command) - const isInventoryOpen = useInventoryStore((s) => s.isOpen); - - const [inventorySlots, setInventorySlots] = useState(() => { - // Try to load from localStorage - if (typeof window !== "undefined") { - const saved = localStorage.getItem("inventory-slots"); - if (saved) { - try { - return JSON.parse(saved); - } catch { - // Fall back to initial if parse fails - } - } - } - return createInitialInventorySlots(); - }); - const [draggedStack, setDraggedStack] = useState( - null, - ); - const [placedItems, setPlacedItems] = useState([]); - const pickupLockRef = useRef>(new Set()); - const inventorySlotsRef = useRef(inventorySlots); - const setPlacedItemsInStore = usePlacedItemsStore((s) => s.setItems); - - // Keep ref in sync with current state (avoids stale closure in callbacks) - useEffect(() => { - inventorySlotsRef.current = inventorySlots; - }); - - // Persist inventory slots to localStorage whenever they change - useEffect(() => { - localStorage.setItem("inventory-slots", JSON.stringify(inventorySlots)); - }, [inventorySlots]); - - useEffect(() => { - if (pickupLockRef.current.size === 0) { - return; - } - - for (const lockedItemId of Array.from(pickupLockRef.current)) { - const stillExists = placedItems.some((item) => item.id === lockedItemId); - if (!stillExists) { - pickupLockRef.current.delete(lockedItemId); - } - } - }, [placedItems]); - - // Manage placed items: maintain all items in state (persisted to store) - useEffect(() => { - const { items: storedItems, initialItemsCreated } = usePlacedItemsStore.getState(); - - setPlacedItems((prev) => { - // Start with all stored items (already persisted in localStorage) - const allItems = storedItems.length > 0 ? storedItems : prev; - - // For personalRoom, create initial spawn items only once per session - // Only create if the item doesn't exist in ANY scene (not just this one) - if (sceneId === "personalRoom" && !initialItemsCreated) { - const trophyTakenOrMovedElsewhere = allItems.some((i) => i.itemId === "trophy"); - // Only recreate the trophy if it has never left this room - // If it exists anywhere, assume it was taken/moved by the player - if (!trophyTakenOrMovedElsewhere) { - return [...allItems, ...createInitialPlacedItems(sceneId)]; - } - } - - return allItems; - }); - - // Mark initial items as created AFTER setState - if (sceneId === "personalRoom" && !initialItemsCreated) { - usePlacedItemsStore.getState().markInitialItemsCreated(); - } - }, [sceneId]); - - // Sync all placed items to localStorage via store - useEffect(() => { - setPlacedItemsInStore(placedItems); - }, [placedItems, setPlacedItemsInStore]); - - const handleBoundaryHit = useCallback( - (phrase: string) => { - showDialog(phrase, "boundaryHit"); - emitRuntimeEvent(onRuntimeEvent, { - type: "onDialog", - source: "boundary", - text: phrase, - dialogKey: "boundaryHit", - }); - }, - [onRuntimeEvent, showDialog], - ); - - const showSpeechBubble = useCallback( - ( - nextText: string, - meta?: { source?: "inventory" | "debug"; dialogKey?: string }, - ) => { - showDialog(nextText, meta?.dialogKey); - emitRuntimeEvent(onRuntimeEvent, { - type: "onDialog", - source: meta?.source ?? "inventory", - text: nextText, - dialogKey: meta?.dialogKey, - }); - }, - [onRuntimeEvent, showDialog], - ); - - const hideSpeechBubble = useCallback(() => { - dismissDialog(); - }, [dismissDialog]); - - const handleInventoryDropHit = useCallback( - (interaction: SceneInteraction, payload: DraggedInventoryPayload) => { - const decision = resolveInventoryDropHitDecision({ - interaction, - payload, - now: Date.now(), - }); - - if (decision.kind === "unknown-item") { - emitRuntimeEvent(onRuntimeEvent, { - type: "onDrop", - outcome: "unknown-item", - itemId: payload.stack.id, - interactionId: interaction.id, - }); - showSpeechBubble(decision.message); - setDraggedStack(null); - return; - } - - if (decision.kind === "rule-miss") { - emitRuntimeEvent(onRuntimeEvent, { - type: "onDrop", - outcome: "rule-miss", - itemId: payload.stack.id, - interactionId: interaction.id, - }); - showSpeechBubble(getRandomPhrase(decision.dialogKey), { - dialogKey: decision.dialogKey, - }); - setDraggedStack(null); - return; - } - - if (decision.kind === "place") { - emitRuntimeEvent(onRuntimeEvent, { - type: "onDrop", - outcome: "place", - itemId: payload.stack.id, - interactionId: interaction.id, - }); - setInventorySlots((currentSlots) => - removeOneFromSlot(currentSlots, decision.fromSlotIndex), - ); - setPlacedItems((currentPlaced) => [ - ...currentPlaced, - { ...decision.placedItem, sceneId }, // Add sceneId to track which scene this item belongs to - ]); - showSpeechBubble(getRandomPhrase(decision.dialogKey), { - dialogKey: decision.dialogKey, - }); - setDraggedStack(null); - return; - } - - if (decision.kind === "consume") { - emitRuntimeEvent(onRuntimeEvent, { - type: "onDrop", - outcome: "consume", - itemId: payload.stack.id, - interactionId: interaction.id, - }); - setInventorySlots((currentSlots) => - removeOneFromSlot(currentSlots, decision.fromSlotIndex), - ); - showSpeechBubble(getRandomPhrase(decision.dialogKey), { - dialogKey: decision.dialogKey, - }); - setDraggedStack(null); - return; - } - - emitRuntimeEvent(onRuntimeEvent, { - type: "onDrop", - outcome: "return", - itemId: payload.stack.id, - interactionId: interaction.id, - }); - showSpeechBubble(getRandomPhrase(decision.dialogKey), { - dialogKey: decision.dialogKey, - }); - setDraggedStack(null); - }, - [onRuntimeEvent, showSpeechBubble], - ); - - const handleInventoryDropMiss = useCallback( - (payload: DraggedInventoryPayload, interaction?: SceneInteraction) => { - const fallbackMiss = resolveInventoryDropMissDialogKey({ - payload, - interaction, - sceneInteractions, - }); - - emitRuntimeEvent(onRuntimeEvent, { - type: "onDrop", - outcome: "return", - itemId: payload.stack.id, - interactionId: interaction?.id, - }); - showSpeechBubble(getRandomPhrase(fallbackMiss), { - dialogKey: fallbackMiss, - }); - setDraggedStack(null); - }, - [onRuntimeEvent, sceneInteractions, showSpeechBubble], - ); - - const handleInventoryDropOnPlayer = useCallback( - (payload: DraggedInventoryPayload) => { - const message = resolveInventoryDropOnPlayerMessage({ payload }); - emitRuntimeEvent(onRuntimeEvent, { - type: "onDrop", - outcome: "on-player", - itemId: payload.stack.id, - }); - if (message.kind === "dialog-key") { - showSpeechBubble(getRandomPhrase(message.dialogKey), { - dialogKey: message.dialogKey, - }); - } else { - showSpeechBubble(message.text); - } - - setDraggedStack(null); - }, - [onRuntimeEvent, showSpeechBubble], - ); - - const handlePickupPlacedItem = useCallback( - (placedItem: PlacedSceneItem) => { - if (isInventoryOpen) { - return; - } - - if (pickupLockRef.current.has(placedItem.id)) { - return; - } - - pickupLockRef.current.add(placedItem.id); - - const decision = resolvePickupPlacedItemDecision({ placedItem }); - if (decision.kind === "ignore") { - pickupLockRef.current.delete(placedItem.id); - return; - } - - if (decision.kind === "blocked") { - emitRuntimeEvent(onRuntimeEvent, { - type: "onDrop", - outcome: "pickup-blocked", - itemId: placedItem.itemId, - interactionId: placedItem.interactionId, - }); - showSpeechBubble(getRandomPhrase(decision.dialogKey), { - dialogKey: decision.dialogKey, - }); - pickupLockRef.current.delete(placedItem.id); - return; - } - - // Try to add to inventory first, but don't apply state changes yet - const inventoryResult = addOneToInventory( - inventorySlotsRef.current, - decision.stack, - ); - - if (!inventoryResult.added) { - showSpeechBubble(inventoryRuleMessages.inventoryFull); - pickupLockRef.current.delete(placedItem.id); - return; - } - - // If we get here, inventory has space. Apply both changes atomically: - // 1. Update inventory - setInventorySlots(inventoryResult.slots); - - // 2. Remove from placed items - setPlacedItems((currentPlaced) => - currentPlaced.filter( - (currentItem) => currentItem.id !== decision.placedItemId, - ), - ); - - emitRuntimeEvent(onRuntimeEvent, { - type: "onDrop", - outcome: "pickup-success", - itemId: placedItem.itemId, - interactionId: placedItem.interactionId, - }); - showSpeechBubble(getRandomPhrase(decision.successDialogKey)); - }, - [isInventoryOpen, onRuntimeEvent, showSpeechBubble], - ); - - const updatePlacedItemPosition = useCallback( - (id: string, axis: 0 | 1 | 2, value: number) => { - setPlacedItems((currentPlaced) => - currentPlaced.map((item) => { - if (item.id !== id) return item; - const worldPosition = [...item.worldPosition] as [ - number, - number, - number, - ]; - worldPosition[axis] = value; - return { ...item, worldPosition }; - }), - ); - }, - [], - ); - - const movePlacedItemToPlayer = useCallback( - (id: string) => { - setPlacedItems((currentPlaced) => - currentPlaced.map((item) => { - if (item.id !== id) return item; - return { - ...item, - worldPosition: [ - playerPosition[0], - item.worldPosition[1], - playerPosition[2], - ], - }; - }), - ); - }, - [playerPosition], - ); - - const removePlacedItemById = useCallback((id: string) => { - setPlacedItems((currentPlaced) => - currentPlaced.filter((item) => item.id !== id), - ); - }, []); - - const handleStartInventoryDrag = useCallback( - (slotIndex: number, clientX: number, clientY: number) => { - const stack = inventorySlots[slotIndex]; - if (!stack) return; - - useInventoryStore.getState().close(); - setDraggedStack({ - stack, - fromSlotIndex: slotIndex, - pointerX: clientX, - pointerY: clientY, - }); - }, - [inventorySlots], - ); - - const handleInteractionInspect = useCallback( - (interaction: SceneInteraction) => { - if (!interaction.hintDialogKeys) return; - - // Si hay un ítem colocado que puede recogerse, no disparamos el hint: - // el click será gestionado por el sistema de pickup, no por el de pistas. - const hasPickableItem = placedItems.some( - (item) => item.interactionId === interaction.id && item.canPickup, - ); - if (hasPickableItem) return; - - const isOccupied = placedItems.some( - (item) => item.interactionId === interaction.id, - ); - const dialogKey = isOccupied - ? interaction.hintDialogKeys.occupied - : interaction.hintDialogKeys.empty; - - showSpeechBubble(getRandomPhrase(dialogKey), { dialogKey }); - }, - [placedItems, showSpeechBubble], - ); - - useProximityHintController({ - playerPosition, - interactions: sceneInteractions, - placedItems, - showSpeechBubble, - }); - - useEffect(() => { - if (sceneId !== "personalRoom") return; - - // Double-rAF: el speech inicial dispara DESPUÉS de que R3F haya corrido - // al menos un useFrame. setTimeout(0) se ejecutaba antes del primer - // requestAnimationFrame, dejando el sprite en SPRITE_MIN_SCALE sin que - // useFrame hubiera corregido aún la escala por profundidad. - let outerHandle: number | null = null; - let innerHandle: number | null = null; - - outerHandle = browserEnvironmentAdapter.requestAnimationFrame(() => { - outerHandle = null; - innerHandle = browserEnvironmentAdapter.requestAnimationFrame(() => { - innerHandle = null; - showSpeechBubble(getRandomPhrase("personalRoomWelcome"), { - dialogKey: "personalRoomWelcome", - }); - }); - }); - - return () => { - if (outerHandle !== null) browserEnvironmentAdapter.cancelAnimationFrame(outerHandle); - if (innerHandle !== null) browserEnvironmentAdapter.cancelAnimationFrame(innerHandle); - }; - }, [sceneId, showSpeechBubble]); - - const handleItemInteract = useCallback( - (item: PlacedSceneItem) => { - // Emit item interaction event — useTransitionSystem listens for this - // to check if there's a matching transition - emitRuntimeEvent(onRuntimeEvent, { - type: "onDrop", - outcome: "item-interact", - itemId: item.itemId, - interactionId: item.interactionId, - }); - }, - [onRuntimeEvent], - ); - - return { - // Note: speechText, speechVisible, speechTrigger are now in dialogStore - // Note: isInventoryOpen is now in inventoryStore - isInventoryOpen, - inventorySlots, - draggedStack, - placedItems, - handleBoundaryHit, - showSpeechBubble, - hideSpeechBubble, - handleInteractionInspect, - handleInventoryDropHit, - handleInventoryDropMiss, - handleInventoryDropOnPlayer, - handlePickupPlacedItem, - updatePlacedItemPosition, - movePlacedItemToPlayer, - removePlacedItemById, - handleStartInventoryDrag, - handleItemInteract, - }; -} diff --git a/apps/web-demo/app/lib/engine/runtime/useSceneRuntimeController.ts b/apps/web-demo/app/lib/engine/runtime/useSceneRuntimeController.ts deleted file mode 100644 index 43c923e..0000000 --- a/apps/web-demo/app/lib/engine/runtime/useSceneRuntimeController.ts +++ /dev/null @@ -1,106 +0,0 @@ -"use client"; - -import { useEffect, useMemo } from "react"; - -import { SCENES, DEFAULT_SCENE_ID } from "../../../../demo-content/scenes/scenes"; -import { useSceneStore, type GameScene } from "@pointclick-engine/engine-core"; -import { getGameRuntime } from "../publicApi"; - -export function useSceneRuntimeController() { - const sceneId = useSceneStore((s) => s.sceneId); - const sceneBackground = useSceneStore((s) => s.scene.background); - const storeSetScene = useSceneStore((s) => s.setScene); - const sceneInteractions = useSceneStore((s) => s.scene.interactions); - const requestRespawn = useSceneStore((s) => s.requestRespawn); - const playerPosition = useSceneStore((s) => s.playerPosition); - const scenePlayerSpawn = useSceneStore((s) => s.scene.playerSpawn); - const updateInteraction = useSceneStore((s) => s.updateInteraction); - const resetInteractionsFromSceneConfig = useSceneStore( - (s) => s.resetInteractionsFromSceneConfig, - ); - - const sceneOptions = useMemo( - () => Object.values(SCENES).map((s) => ({ label: s.label, value: s.id })), - [], - ); - - const setScene = useMemo( - () => (id: string) => { - const scene = SCENES[id]; - if (!scene) { - console.warn(`Scene not found: ${id}`); - return; - } - // When changing scene from debug menu, look for a transition to that scene - // and use its spawn/target positions for animated entry - const currentScene = useSceneStore.getState().scene; - const transitionToTarget = currentScene?.transitions?.find((t) => t.targetSceneId === id); - - if (transitionToTarget && "spawnPosition" in transitionToTarget && transitionToTarget.spawnPosition) { - // Use transition's spawn position - const spawnPos = transitionToTarget.spawnPosition; - const targetPos = "targetPosition" in transitionToTarget ? transitionToTarget.targetPosition : undefined; - - storeSetScene(id, scene as GameScene, spawnPos); - - // Execute walk command if target position exists - if (targetPos) { - setTimeout(() => { - getGameRuntime()?.executeCommand({ - type: "player:walkTo", - position: targetPos, - }); - }, 0); - } - } else { - // No transition found, just change scene normally - storeSetScene(id, scene as GameScene); - } - }, - [storeSetScene], - ); - - // Load default scene on mount if the store is empty (engine-core store - // is agnostic and starts blank — the demo is responsible for seeding it). - // Try to load last visited scene from localStorage, fallback to default. - useEffect(() => { - if (!useSceneStore.getState().sceneId) { - // Try to load from localStorage - const savedSceneId = - typeof window !== "undefined" ? localStorage.getItem("current-scene-id") : null; - const initialSceneId = savedSceneId || DEFAULT_SCENE_ID; - const initialScene = SCENES[initialSceneId]; - - if (initialScene) { - storeSetScene(initialSceneId, initialScene as GameScene); - } else { - // Fallback to default if saved scene doesn't exist - const defaultScene = SCENES[DEFAULT_SCENE_ID]; - if (defaultScene) { - storeSetScene(DEFAULT_SCENE_ID, defaultScene as GameScene); - } - } - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - - // Persist current scene to localStorage whenever it changes - useEffect(() => { - if (sceneId) { - localStorage.setItem("current-scene-id", sceneId); - } - }, [sceneId]); - - return { - sceneId, - sceneBackground, - setScene, - sceneInteractions, - requestRespawn, - playerPosition, - scenePlayerSpawn, - updateInteraction, - resetInteractionsFromSceneConfig, - sceneOptions, - }; -} diff --git a/apps/web-demo/app/lib/engine/runtime/useTransitionSystem.ts b/apps/web-demo/app/lib/engine/runtime/useTransitionSystem.ts deleted file mode 100644 index e8371b6..0000000 --- a/apps/web-demo/app/lib/engine/runtime/useTransitionSystem.ts +++ /dev/null @@ -1,196 +0,0 @@ -"use client"; - -import { useCallback, useEffect, useRef } from "react"; -import { useSceneStore } from "@pointclick-engine/engine-core"; -import { resolveTransitionFromItemDrop, resolveTransitionFromItemInteraction } from "@pointclick-engine/engine-core"; -import { getGameRuntime } from "../publicApi"; -import { useDialogStore } from "../../../store/dialogStore"; -import { usePlacedItemsStore } from "../../../store/placedItemsStore"; -import { getRandomPhrase } from "../../../../demo-content/dialogs/getRandomPhrase"; -import { preloadSceneBackground } from "../../../components/scene/SceneBackgroundPlane"; -import type { RuntimeEvent, GameScene } from "@pointclick-engine/engine-core"; - -/** - * Wires scene transitions into the demo. - * - * Handles: - * - Collision-based transitions (via `handleTransitionTriggered` callback) - * - Item-drop-based transitions (by watching `item:dropped` events) - * - * Scene changes are applied directly via sceneStore for demo compatibility - * (scenes are defined in SCENES, not registered via createGameRuntime). - */ -export interface UseTransitionSystemOpts { - onBeforeChange?: () => void; - /** Resuelve el objeto de escena completo por ID. Usado para validación y precarga de fondo. */ - resolveScene?: (sceneId: string) => GameScene | null; -} - -export function useTransitionSystem(opts?: UseTransitionSystemOpts) { - const storeSetScene = useSceneStore((s) => s.setScene); - const placedItems = usePlacedItemsStore((s) => s.items); - const isTransitioningRef = useRef(false); - const showDialog = useDialogStore((s) => s.show); - const dialogVisible = useDialogStore((s) => s.visible); - const pendingTransitionRef = useRef<{ id: string; targetSceneId: string } | null>(null); - const optsRef = useRef(opts); - useEffect(() => { optsRef.current = opts; }); - - const changeScene = useCallback( - (targetSceneId: string, transitionId: string) => { - if (isTransitioningRef.current) return; - isTransitioningRef.current = true; - - // Emit transition:started via runtime bus (if runtime is active) - getGameRuntime()?.emit({ - type: "transition:started", - transitionId, - }); - - // Notify caller synchronously so it can show the curtain overlay before - // any state update causes a re-render with the new (backgroundless) scene. - optsRef.current?.onBeforeChange?.(); - - const fromSceneId = useSceneStore.getState().sceneId; - const fromScene = useSceneStore.getState().scene; - - // Find the transition that was used to trigger this scene change - const usedTransition = fromScene.transitions?.find((t) => t.id === transitionId); - - // Change scene first with optional custom spawn position - const spawnPos = usedTransition && "spawnPosition" in usedTransition ? usedTransition.spawnPosition : undefined; - const resolvedScene = optsRef.current?.resolveScene?.(targetSceneId) ?? null; - storeSetScene(targetSceneId, resolvedScene as Parameters[1], spawnPos); - - // Then emit walk command in the new scene with correct pathfinding context - if (usedTransition && "targetPosition" in usedTransition && usedTransition.targetPosition) { - const targetPos = usedTransition.targetPosition; - // console.log(`[useTransitionSystem] Emitting walkTo to ${JSON.stringify(targetPos)}`); - // Emit walk command via runtime - getGameRuntime()?.executeCommand({ - type: "player:walkTo", - position: targetPos, - }); - } else { - // console.log(`[useTransitionSystem] No targetPosition found on transition`, usedTransition); - } - - getGameRuntime()?.emit({ - type: "transition:completed", - fromSceneId, - toSceneId: targetSceneId, - }); - - // Reset guard after a brief delay so re-entering the same zone works - setTimeout(() => { - isTransitioningRef.current = false; - }, 800); - }, - [storeSetScene], - ); - - /** Called by SceneTransitions renderer when player enters a collision zone. */ - const handleTransitionTriggered = useCallback( - (transitionId: string, targetSceneId: string) => { - const currentSceneId = useSceneStore.getState().sceneId; - const currentScene = useSceneStore.getState().scene; - const transition = currentScene.transitions?.find((t) => t.id === transitionId); - - if (!transition) { - console.warn(`[transition] transition not found: ${transitionId}`); - return; - } - - // Special case: leaving personalRoom requires having taken the trophy - // The trophy must not be placed in personalRoom (can be in inventory or another room) - if (currentSceneId === "personalRoom" && targetSceneId === "dungeon") { - const trophyStillInRoom = placedItems.some( - (item) => item.itemId === "trophy" && item.sceneId === "personalRoom", - ); - - console.log("[transition-debug] personalRoom exit check:", { - allPlacedItems: placedItems.map((i) => ({ id: i.id, itemId: i.itemId, sceneId: i.sceneId })), - trophyStillInRoom, - }); - - if (trophyStillInRoom) { - showDialog( - "Sería mejor recoger todo lo que pueda del cuarto antes de irme...", - "interaction.trophy-pedestal.empty", - ); - return; - } - } - - // Preload the target scene background so it's in browser cache when we switch. - const targetBg = optsRef.current?.resolveScene?.(targetSceneId)?.background; - if (targetBg) preloadSceneBackground(targetBg); - - getGameRuntime()?.emit({ - type: "transition:triggered", - transitionId, - targetSceneId, - }); - changeScene(targetSceneId, transitionId); - }, - [changeScene, showDialog, placedItems], - ); - - /** - * Handles item-drop and item-interact events from the inventory system. - * Returns a passthrough handler that checks if the drop/interact matches a transition. - * Defers the scene change until the dialog is dismissed. - */ - const wrapRuntimeEventForTransitions = useCallback( - (passthrough: (event: RuntimeEvent) => void) => - (event: RuntimeEvent) => { - const scene = useSceneStore.getState().scene; - - if (event.type === "onDrop" && (event.outcome === "consume" || event.outcome === "place") && event.interactionId) { - const gameEvent = { - type: "item:dropped" as const, - itemId: event.itemId, - outcome: event.outcome as "consume" | "place", - interactionId: event.interactionId, - }; - const matching = resolveTransitionFromItemDrop(scene, gameEvent); - if (matching) { - getGameRuntime()?.emit({ - type: "transition:triggered", - transitionId: matching.id, - targetSceneId: matching.targetSceneId, - }); - // Store transition to trigger after dialog closes - pendingTransitionRef.current = { id: matching.id, targetSceneId: matching.targetSceneId }; - } - } - - if (event.type === "onDrop" && event.outcome === "item-interact" && event.interactionId) { - const matching = resolveTransitionFromItemInteraction(scene, event.itemId, event.interactionId); - if (matching) { - getGameRuntime()?.emit({ - type: "transition:triggered", - transitionId: matching.id, - targetSceneId: (matching as any).targetSceneId, - }); - // Store transition to trigger after dialog closes - pendingTransitionRef.current = { id: matching.id, targetSceneId: (matching as any).targetSceneId }; - } - } - - passthrough(event); - }, - [], - ); - - // Execute pending transition after dialog is dismissed - useEffect(() => { - if (!dialogVisible && pendingTransitionRef.current) { - const t = pendingTransitionRef.current; - pendingTransitionRef.current = null; - changeScene(t.targetSceneId, t.id); - } - }, [dialogVisible, changeScene]); - - return { handleTransitionTriggered, wrapRuntimeEventForTransitions }; -} diff --git a/apps/web-demo/app/lib/gamePersistence.ts b/apps/web-demo/app/lib/gamePersistence.ts new file mode 100644 index 0000000..55aa74f --- /dev/null +++ b/apps/web-demo/app/lib/gamePersistence.ts @@ -0,0 +1,282 @@ +/** + * gamePersistence – Punto único de acceso al guardado del progreso de la demo. + * + * Toda la partida vive en UNA instantánea (`GameSnapshot`, clave `pointclick-save`) + * que escribe el comando `game:save` del core. Lo propio de la demo, las puertas, va en + * `snapshot.extra`: + * + * extra = { doors: { "": true | false, ... } } + * + * Las partidas con el formato de 0.5.0 (cuatro claves sueltas: `inventory-slots`, + * `current-scene-id`, `placed-items-state`, `door-states`) se migran al arrancar con + * `migrateLegacySave` y las claves antiguas se borran. + * + * Todos los accesos pasan por `localStorageAdapter` (fallback seguro en SSR). + */ + +import { + clearSave, + getGameRuntime, + loadGame, + migrateLegacySave, + resetGameState, + saveGame, + SAVE_STORAGE_KEY, + useInventoryStateStore, + usePlacedItemsStateStore, + useSceneStore, + useWorldStateStore, + type GameSnapshot, + type InventorySlotsState, +} from "@pointclick-engine/engine-core"; + +import { DEFAULT_SCENE_ID } from "../../demo-content/scenes/scenes"; +import { useDoorStore } from "../store/doorStore"; +import { localStorageAdapter } from "./platform-web"; + +// ============================================================================ +// Claves antiguas (formato 0.5.0): solo se leen para migrar y se borran +// ============================================================================ + +export const LEGACY_GAME_STORAGE_KEYS = { + inventorySlots: "inventory-slots", + currentSceneId: "current-scene-id", + doorStates: "door-states", + placedItems: "placed-items-state", +} as const; + +const LEGACY_KEYS: string[] = Object.values(LEGACY_GAME_STORAGE_KEYS); + +/** Escena que sembraba el antiguo flag `initialItemsCreated` de las partidas guardadas. */ +export const LEGACY_SEEDED_SCENE_ID = "personalRoom"; + +/** Inventario de una partida nueva: gameboy y llave dorada (para probar la puerta de la mazmorra). */ +export function createInitialInventorySlots(): InventorySlotsState { + return Array.from({ length: 9 }, (_, index) => { + if (index === 0) { + return { + id: "gameboy", + name: "Gameboy", + spriteUrl: "/assets/gameboy/gameboy.png", + quantity: 1, + }; + } + if (index === 1) { + return { + id: "gold-key", + name: "Llave dorada", + spriteUrl: "/assets/key/gold-key.png", + quantity: 1, + }; + } + return null; + }); +} + +// ============================================================================ +// Puertas: el estado vive en `extra`, no en su propia clave +// ============================================================================ + +const DOORS_EXTRA_KEY = "doors"; + +type DoorStates = Record; + +function isDoorStates(value: unknown): value is DoorStates { + return ( + typeof value === "object" && + value !== null && + !Array.isArray(value) && + Object.values(value).every((v) => typeof v === "boolean") + ); +} + +function readDoors(snapshot: GameSnapshot | null): DoorStates { + const doors = snapshot?.extra?.[DOORS_EXTRA_KEY]; + return isDoorStates(doors) ? { ...doors } : {}; +} + +// ============================================================================ +// Lectura: instantánea nueva o migración de las claves antiguas +// ============================================================================ + +function removeLegacyKeys(): void { + for (const key of LEGACY_KEYS) localStorageAdapter.removeItem(key); +} + +/** Migra las claves de 0.5.0 a la instantánea nueva, la escribe y borra las antiguas. */ +function migrateLegacy(): GameSnapshot | null { + const hadInventory = localStorageAdapter.getItem(LEGACY_GAME_STORAGE_KEYS.inventorySlots) !== null; + const snapshot = migrateLegacySave(localStorageAdapter, { + legacySeededSceneId: LEGACY_SEEDED_SCENE_ID, + defaultSceneId: DEFAULT_SCENE_ID, + extraKeys: [LEGACY_GAME_STORAGE_KEYS.doorStates], + }); + if (!snapshot) return null; + + // Sin inventario guardado, la partida antigua arrancaba con el inventario inicial. + if (!hadInventory) snapshot.inventory = createInitialInventorySlots(); + + // `door-states` era un envoltorio zustand `{ state: { doorOpenStates }, version }`. + const legacyDoors = snapshot.extra?.[LEGACY_GAME_STORAGE_KEYS.doorStates] as + | { state?: { doorOpenStates?: unknown } } + | undefined; + delete snapshot.extra?.[LEGACY_GAME_STORAGE_KEYS.doorStates]; + const doors = legacyDoors?.state?.doorOpenStates; + snapshot.extra = isDoorStates(doors) ? { [DOORS_EXTRA_KEY]: doors } : {}; + + localStorageAdapter.setItem(SAVE_STORAGE_KEY, JSON.stringify(snapshot)); + removeLegacyKeys(); + return snapshot; +} + +function readSavedGame(): GameSnapshot | null { + return loadGame(localStorageAdapter) ?? migrateLegacy(); +} + +// ============================================================================ +// Hidratación de los stores +// ============================================================================ + +let hydrated = false; +let loadedSnapshot: GameSnapshot | null = null; + +/** + * Vuelca la partida guardada en los stores (inventario, ítems colocados, flags, puertas). + * Idempotente. Se ejecuta al importar este módulo en cliente (antes del primer render que + * lea los stores) y NO guarda nada: el guardado solo se activa en `startGamePersistence`. + * + * La escena NO se aplica aquí: la siembra `useSceneRuntime` con `loadCurrentSceneId` (con la + * escena completa de la demo y el aviso `scene:changed` al audio). Tampoco se restaura la + * posición del jugador: como siempre, al cargar aparece en el spawn de la escena. + */ +export function hydrateGameState(): void { + if (hydrated || typeof window === "undefined") return; + hydrated = true; + loadedSnapshot = readSavedGame(); + const snapshot = loadedSnapshot; + + useInventoryStateStore.getState().setSlots(snapshot?.inventory ?? createInitialInventorySlots()); + if (snapshot) { + const placed = usePlacedItemsStateStore.getState(); + placed.setItems(snapshot.placedItems); + placed.setSeededSceneIds(snapshot.seededSceneIds); + useWorldStateStore.getState().setAll({ + flags: snapshot.flags, + visitedSceneIds: snapshot.visitedSceneIds, + }); + } + useDoorStore.setState({ doorOpenStates: readDoors(snapshot) }); +} + +hydrateGameState(); + +// ============================================================================ +// Guardado automático +// ============================================================================ + +let persistenceUsers = 0; +let unsubscribers: Array<() => void> = []; +let suspended = false; +let saveScheduled = false; + +function saveNow(): void { + if (suspended) return; + // Sin escena todavía no hay partida que guardar. + if (!useSceneStore.getState().sceneId) return; + const extra = { [DOORS_EXTRA_KEY]: { ...useDoorStore.getState().doorOpenStates } }; + const runtime = getGameRuntime(); + if (runtime) runtime.executeCommand({ type: "game:save", extra }); + else saveGame(localStorageAdapter, { extra }); +} + +/** Agrupa los cambios del mismo instante en un solo guardado. */ +function scheduleSave(): void { + if (saveScheduled || suspended) return; + saveScheduled = true; + queueMicrotask(() => { + saveScheduled = false; + saveNow(); + }); +} + +function stopSubscriptions(): void { + unsubscribers.forEach((off) => off()); + unsubscribers = []; +} + +/** + * Activa el guardado automático (escribe el estado actual, ya hidratado, y después cada + * cambio de inventario, ítems colocados, flags/escenas visitadas, escena o puertas). + * Con contador de usos para StrictMode. Devuelve la función de baja. + */ +export function startGamePersistence(): () => void { + hydrateGameState(); + if (persistenceUsers === 0 && !suspended) { + scheduleSave(); + unsubscribers = [ + useInventoryStateStore.subscribe((state, prev) => { + if (state.slots !== prev.slots) scheduleSave(); + }), + usePlacedItemsStateStore.subscribe((state, prev) => { + if (state.items !== prev.items || state.seededSceneIds !== prev.seededSceneIds) { + scheduleSave(); + } + }), + useWorldStateStore.subscribe((state, prev) => { + if (state.flags !== prev.flags || state.visitedSceneIds !== prev.visitedSceneIds) { + scheduleSave(); + } + }), + useSceneStore.subscribe((state, prev) => { + if (state.sceneId !== prev.sceneId) scheduleSave(); + }), + useDoorStore.subscribe((state, prev) => { + if (state.doorOpenStates !== prev.doorOpenStates) scheduleSave(); + }), + ]; + } + persistenceUsers += 1; + let released = false; + return () => { + if (released) return; + released = true; + persistenceUsers -= 1; + if (persistenceUsers === 0) stopSubscriptions(); + }; +} + +// ============================================================================ +// Escena actual (puerto del renderer) +// ============================================================================ + +/** Escena de la partida guardada (para que el renderer la siembre al montar). */ +export function loadCurrentSceneId(): string | null { + return loadedSnapshot?.sceneId ?? null; +} + +/** La escena se guarda con la instantánea (suscripción al `sceneStore`): nada que hacer aquí. */ +export function saveCurrentSceneId(): void {} + +// ============================================================================ +// Limpieza de progreso +// ============================================================================ + +/** + * Borra solo el progreso de la partida actual: `game:reset` (vacía los stores y borra + * la instantánea con `clearSave`) y las claves antiguas por si quedaran. Antes se corta + * el guardado automático para que el vaciado de los stores no reescriba la partida. + * + * Preserva idioma (`i18n-locale`), ajustes de audio (`audio-settings`) y cualquier clave + * ajena. Nunca usa `localStorage.clear()`. + */ +export function clearGameProgress(): void { + suspended = true; + stopSubscriptions(); + const runtime = getGameRuntime(); + if (runtime) runtime.executeCommand({ type: "game:reset" }); + else resetGameState(); + // Idempotente: cubre un runtime creado sin `storage`. + clearSave(localStorageAdapter); + useDoorStore.setState({ doorOpenStates: {} }); + removeLegacyKeys(); +} diff --git a/apps/web-demo/app/lib/platform-web-audio.test.ts b/apps/web-demo/app/lib/platform-web-audio.test.ts index 2086bdf..09a592c 100644 --- a/apps/web-demo/app/lib/platform-web-audio.test.ts +++ b/apps/web-demo/app/lib/platform-web-audio.test.ts @@ -42,10 +42,7 @@ function FakeAudio(this: FakeAudioInstance, url: string) { function unlockAdapter() { // The adapter queues plays until a user gesture. Simulate it. - const handlers = (globalThis as any).__windowHandlers as Map< - string, - Array - >; + const handlers = (globalThis as unknown as { __windowHandlers: Map> }).__windowHandlers; const pointerHandlers = handlers.get("pointerdown") ?? []; for (const h of pointerHandlers) { if (typeof h === "function") h(new Event("pointerdown")); @@ -55,7 +52,7 @@ function unlockAdapter() { beforeEach(() => { audioInstances.length = 0; const handlers = new Map>(); - (globalThis as any).__windowHandlers = handlers; + (globalThis as unknown as { __windowHandlers?: Map> }).__windowHandlers = handlers; vi.stubGlobal("window", { addEventListener: (name: string, h: EventListenerOrEventListenerObject) => { const list = handlers.get(name) ?? []; diff --git a/apps/web-demo/app/lib/platform-web-audio.ts b/apps/web-demo/app/lib/platform-web-audio.ts index cbaf78f..96e1187 100644 --- a/apps/web-demo/app/lib/platform-web-audio.ts +++ b/apps/web-demo/app/lib/platform-web-audio.ts @@ -254,7 +254,7 @@ export class WebAudioAdapter implements AudioPort { resolve(); }; audio.addEventListener("canplaythrough", onReady, { once: true }); - const timeout = setTimeout(() => { + setTimeout(() => { audio.removeEventListener("canplaythrough", onReady); resolve(); }, 5000); diff --git a/apps/web-demo/app/page.tsx b/apps/web-demo/app/page.tsx index 636618e..49b8ab6 100644 --- a/apps/web-demo/app/page.tsx +++ b/apps/web-demo/app/page.tsx @@ -1,15 +1,13 @@ "use client"; -import { useEffect, useMemo, useState } from "react"; +import { useEffect, useState } from "react"; import { createGameRuntime, - type GameSceneConfig, + type GameRuntime, } from "./lib/engine/publicApi"; import { CRTEffectWrapper } from "./lib/components/CRTEffectWrapper"; -import { SCENES } from "../demo-content/scenes/scenes"; +import { DEMO_RUNTIME_CONFIG } from "./lib/engine/runtime/demoViewportOptions"; import GameTouchCanvas from "./components/GameTouchCanvas"; -import { useInventoryStore } from "./store/inventoryStore"; -import { useDialogStore } from "./store/dialogStore"; import { IntroScene } from "./components/intro/IntroScene"; import { useLocaleDetection } from "@pointclick-engine/engine-renderer-r3f"; import { createWebI18nAdapter } from "./lib/platform-web"; @@ -33,25 +31,27 @@ const I18N_CONFIG = { }; function Game() { + // El runtime se crea en un efecto (con su dispose en el cleanup) y el canvas + // solo se monta cuando ya existe: los efectos de los hijos corren antes que + // los del padre, y useSceneRuntimeController fija la escena inicial en uno de + // ellos. Montando el canvas despues, el `scene:changed` inicial llega al bus + // (musica inicial) y no hace falta esperar al runtime con polling. + // StrictMode (create -> dispose -> create) es seguro: cada ciclo del efecto + // crea su propio runtime y el estado final apunta al ultimo, que sigue vivo. + const [runtime, setRuntime] = useState(null); + useEffect(() => { - const runtime = createGameRuntime({ - scenes: Object.values(SCENES) as GameSceneConfig[], - inventoryAdapter: { - toggle: () => useInventoryStore.getState().toggle(), - isOpen: () => useInventoryStore.getState().isOpen, - }, - dialogAdapter: { - show: (text, key) => useDialogStore.getState().show(text, key), - hide: () => useDialogStore.getState().dismiss(), - }, - }); + const created = createGameRuntime(DEMO_RUNTIME_CONFIG); + // eslint-disable-next-line react-hooks/set-state-in-effect -- publishes the external runtime handle so children mount only once it exists (children effects run before the parent's) + setRuntime(created); return () => { - runtime.dispose(); + created.dispose(); + setRuntime(null); }; }, []); - return ; + return runtime ? : null; } export default function Home() { diff --git a/apps/web-demo/app/store/dialogStore.ts b/apps/web-demo/app/store/dialogStore.ts index c6b738c..216b429 100644 --- a/apps/web-demo/app/store/dialogStore.ts +++ b/apps/web-demo/app/store/dialogStore.ts @@ -1,33 +1,5 @@ -import { create } from "zustand"; - /** - * dialogStore — estado del diálogo/speech bubble activo. - * - * Accesible desde ejecutores de comandos (`publicApi.ts`) y componentes UI. - * Reemplaza el estado local de speech en `useInventoryRuntimeController` para - * que `dialog:trigger` y `dialog:dismiss` funcionen sin acceso al scope React. + * dialogStore — el store vive en engine-core (`useDialogStore`). + * Re-export para que los consumidores de la demo no cambien. */ -type DialogStoreState = { - text: string; - key: string | undefined; - visible: boolean; - /** Incrementado en cada `show()` para forzar re-animación del speech bubble. */ - triggerCount: number; - show: (text: string, key?: string) => void; - dismiss: () => void; -}; - -export const useDialogStore = create((set) => ({ - text: "", - key: undefined, - visible: false, - triggerCount: 0, - show: (text, key) => - set((s) => ({ - text, - key, - visible: true, - triggerCount: s.triggerCount + 1, - })), - dismiss: () => set({ visible: false }), -})); +export { useDialogStore } from "@pointclick-engine/engine-core"; diff --git a/apps/web-demo/app/store/doorStore.ts b/apps/web-demo/app/store/doorStore.ts index 5fb19a6..bb79c26 100644 --- a/apps/web-demo/app/store/doorStore.ts +++ b/apps/web-demo/app/store/doorStore.ts @@ -1,5 +1,4 @@ import { create } from "zustand"; -import { persist } from "zustand/middleware"; /** * doorStore — estado abierto/cerrado de las puertas de la escena. @@ -13,7 +12,8 @@ import { persist } from "zustand/middleware"; * "closed" — the same default used by `SceneDoors` if a scene declares the * door without a starting state. * - * Door state is persisted to localStorage so doors remain open after page reload. + * Door state is saved inside the game snapshot (`extra.doors`) by + * `gamePersistence.ts`, so doors remain open after page reload. */ type DoorStoreState = { doorOpenStates: Record; @@ -27,26 +27,19 @@ type DoorStoreState = { reset: (initial: Record) => void; }; -export const useDoorStore = create()( - persist( - (set, get) => ({ - doorOpenStates: {}, - isOpen: (id) => Boolean(get().doorOpenStates[id]), - setOpen: (id, isOpen) => - set((s) => ({ - doorOpenStates: { ...s.doorOpenStates, [id]: isOpen }, - })), - toggle: (id) => - set((s) => ({ - doorOpenStates: { - ...s.doorOpenStates, - [id]: !s.doorOpenStates[id], - }, - })), - reset: (initial) => set({ doorOpenStates: { ...initial } }), - }), - { - name: "door-states", - }, - ), -); +export const useDoorStore = create()((set, get) => ({ + doorOpenStates: {}, + isOpen: (id) => Boolean(get().doorOpenStates[id]), + setOpen: (id, isOpen) => + set((s) => ({ + doorOpenStates: { ...s.doorOpenStates, [id]: isOpen }, + })), + toggle: (id) => + set((s) => ({ + doorOpenStates: { + ...s.doorOpenStates, + [id]: !s.doorOpenStates[id], + }, + })), + reset: (initial) => set({ doorOpenStates: { ...initial } }), +})); diff --git a/apps/web-demo/app/store/inventoryStore.ts b/apps/web-demo/app/store/inventoryStore.ts index 10e6801..c3d23c9 100644 --- a/apps/web-demo/app/store/inventoryStore.ts +++ b/apps/web-demo/app/store/inventoryStore.ts @@ -1,22 +1,5 @@ -import { create } from "zustand"; - /** - * inventoryStore — estado de visibilidad del inventario. - * - * Accesible desde ejecutores de comandos (`publicApi.ts`) y componentes UI. - * Separado de `useInventoryRuntimeController` para que `inventory:toggle` - * funcione sin acceso al scope React del componente. + * inventoryStore — el store vive en engine-core (`useInventoryUiStore`). + * Alias con el nombre historico de la demo para no tocar a los consumidores. */ -type InventoryStoreState = { - isOpen: boolean; - toggle: () => void; - open: () => void; - close: () => void; -}; - -export const useInventoryStore = create((set) => ({ - isOpen: false, - toggle: () => set((s) => ({ isOpen: !s.isOpen })), - open: () => set({ isOpen: true }), - close: () => set({ isOpen: false }), -})); +export { useInventoryUiStore as useInventoryStore } from "@pointclick-engine/engine-core"; diff --git a/apps/web-demo/app/store/placedItemsStore.ts b/apps/web-demo/app/store/placedItemsStore.ts deleted file mode 100644 index 401710d..0000000 --- a/apps/web-demo/app/store/placedItemsStore.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { create } from "zustand"; -import { persist } from "zustand/middleware"; -import type { PlacedSceneItem } from "@pointclick-engine/engine-core"; - -type PlacedItemsStoreState = { - items: PlacedSceneItem[]; - setItems: (items: PlacedSceneItem[]) => void; - initialItemsCreated: boolean; - markInitialItemsCreated: () => void; -}; - -const STORAGE_KEY = "placed-items-state"; - -export const usePlacedItemsStore = create()( - persist( - (set) => ({ - items: [], - setItems: (items: PlacedSceneItem[]) => set({ items }), - initialItemsCreated: false, - markInitialItemsCreated: () => set({ initialItemsCreated: true }), - }), - { - name: STORAGE_KEY, - }, - ), -); diff --git a/apps/web-demo/assets-src/README.md b/apps/web-demo/assets-src/README.md new file mode 100644 index 0000000..09c3f21 --- /dev/null +++ b/apps/web-demo/assets-src/README.md @@ -0,0 +1,24 @@ +# Fuentes de arte (no se sirven) + +Material de terceros descargado tal cual, para elegir de aquí los assets de la demo con historia (Fase 18). Esta carpeta **no** está bajo `public/`: no se sirve ni se despliega. Lo que se use en el juego se copia a `public/assets/` y se anota en el `LICENSES.md` de arte correspondiente. + +## Packs + +| Carpeta | Pack | Autor | Licencia | Origen | Descargado | +|---|---|---|---|---|---| +| `items/7soul-rpg-icons/` | 496 pixel art icons for medieval/fantasy RPG — 496 PNG de 34×34 | Henrique Lazarini (7Soul1) | CC0 | https://opengameart.org/node/39455 | 2026-10-10 | +| `items/idylwild-inventory/` | Idylwild's Inventory — 51 PNG de 32×32 y el `.ase` fuente | Idylwild | CC0 | https://opengameart.org/content/idylwilds-inventory | 2026-10-10 | +| `backgrounds/sci-fi-level/` | Sci Fi Level — fondo y primer plano de 5121×841 (PNG) y las capas sueltas en dos tamaños (`.tar.gz`) | Jeremy Gooch (jeremygooch.blogspot.com) | CC-BY 3.0 (también CC-BY-SA 3.0, GPL 2.0 y GPL 3.0) | https://opengameart.org/content/sci-fi-level | 2026-10-11 | +| `characters/helix-male/` | 8 Directional 2D Point and Click Male Character — una hoja de sprites (`helix_full_sheet.png`) con reposo y paseo en 8 direcciones, pensada para 64×64 | DeMoNiCaTeD | CC-BY-SA 4.0 (también GPL 3.0) | https://opengameart.org/content/8-directional-2d-point-and-click-male-character | 2026-10-11 | + +Los dos packs de ítems están en dominio público (CC0): se pueden usar, modificar y redistribuir sin condiciones. La atribución no es obligatoria, pero se mantiene esta tabla. + +**Sci Fi Level exige atribución** (CC-BY 3.0): donde se use hay que acreditar "Jeremy Gooch (jeremygooch.blogspot.com)", en los créditos del juego y en el `LICENSES.md` de arte. + +**El personaje Helix es CC-BY-SA 4.0**: exige acreditar al autor (DeMoNiCaTeD), enlazar la licencia e indicar los cambios, y cualquier versión modificada (frames recortados, tintes, reescalados) debe publicarse con la misma licencia. + +## Convenciones + +- Los archivos se guardan sin modificar, con su nombre original. +- Los iconos se escalan ×2 sin suavizado al copiarlos a `public/assets/`, para igualar los 64×64 de los ítems actuales. +- Antes de añadir otro pack, comprobar su licencia y anotarla aquí. El repositorio es público: solo material que permita redistribución. diff --git a/apps/web-demo/assets-src/backgrounds/sci-fi-level/sci-fi-level[background_layer].png b/apps/web-demo/assets-src/backgrounds/sci-fi-level/sci-fi-level[background_layer].png new file mode 100644 index 0000000..b40d9a0 Binary files /dev/null and b/apps/web-demo/assets-src/backgrounds/sci-fi-level/sci-fi-level[background_layer].png differ diff --git a/apps/web-demo/assets-src/backgrounds/sci-fi-level/sci-fi-level[foreground_layer].png b/apps/web-demo/assets-src/backgrounds/sci-fi-level/sci-fi-level[foreground_layer].png new file mode 100644 index 0000000..2e51e29 Binary files /dev/null and b/apps/web-demo/assets-src/backgrounds/sci-fi-level/sci-fi-level[foreground_layer].png differ diff --git a/apps/web-demo/assets-src/backgrounds/sci-fi-level/sciFi_layers[large].tar.gz b/apps/web-demo/assets-src/backgrounds/sci-fi-level/sciFi_layers[large].tar.gz new file mode 100644 index 0000000..5ba48bc Binary files /dev/null and b/apps/web-demo/assets-src/backgrounds/sci-fi-level/sciFi_layers[large].tar.gz differ diff --git a/apps/web-demo/assets-src/backgrounds/sci-fi-level/sciFi_layers[small].tar.gz b/apps/web-demo/assets-src/backgrounds/sci-fi-level/sciFi_layers[small].tar.gz new file mode 100644 index 0000000..9e5fed9 Binary files /dev/null and b/apps/web-demo/assets-src/backgrounds/sci-fi-level/sciFi_layers[small].tar.gz differ diff --git a/apps/web-demo/assets-src/characters/helix-male/helix_full_sheet.png b/apps/web-demo/assets-src/characters/helix-male/helix_full_sheet.png new file mode 100644 index 0000000..b6bd011 Binary files /dev/null and b/apps/web-demo/assets-src/characters/helix-male/helix_full_sheet.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Armor04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Armor04.png new file mode 100644 index 0000000..a31e04f Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Armor04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Armor05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Armor05.png new file mode 100644 index 0000000..cc7d88b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Armor05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Armour01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Armour01.png new file mode 100644 index 0000000..747f7e4 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Armour01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Armour02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Armour02.png new file mode 100644 index 0000000..b680d01 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Armour02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Armour03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Armour03.png new file mode 100644 index 0000000..a30ab9e Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Armour03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Clothing01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Clothing01.png new file mode 100644 index 0000000..86d24da Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Clothing01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Clothing02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Clothing02.png new file mode 100644 index 0000000..4cd9027 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Clothing02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Shoes01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Shoes01.png new file mode 100644 index 0000000..1fcf2f1 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Shoes01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Shoes02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Shoes02.png new file mode 100644 index 0000000..c25544b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Shoes02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Shoes03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Shoes03.png new file mode 100644 index 0000000..afd5b3d Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Shoes03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Shoes04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Shoes04.png new file mode 100644 index 0000000..fee4be8 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Shoes04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Shoes05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Shoes05.png new file mode 100644 index 0000000..abc2bbc Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Shoes05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Shoes06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Shoes06.png new file mode 100644 index 0000000..de882c9 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Shoes06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Shoes07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Shoes07.png new file mode 100644 index 0000000..79dd46d Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/A_Shoes07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Medal01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Medal01.png new file mode 100644 index 0000000..c94f84e Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Medal01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Medal02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Medal02.png new file mode 100644 index 0000000..9058757 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Medal02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Medal03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Medal03.png new file mode 100644 index 0000000..590219e Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Medal03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Medal04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Medal04.png new file mode 100644 index 0000000..824147b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Medal04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace01.png new file mode 100644 index 0000000..50872bc Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace02.png new file mode 100644 index 0000000..7891a34 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace03.png new file mode 100644 index 0000000..f7c10fe Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace04.png new file mode 100644 index 0000000..e929dfa Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace05.png new file mode 100644 index 0000000..2ef38b7 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace06.png new file mode 100644 index 0000000..23c90ae Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace07.png new file mode 100644 index 0000000..5f52a76 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace08.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace08.png new file mode 100644 index 0000000..824da05 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Necklace08.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Ring01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Ring01.png new file mode 100644 index 0000000..dfee3ee Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Ring01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Ring02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Ring02.png new file mode 100644 index 0000000..9d6161c Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/Ac_Ring02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/C_Elm01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/C_Elm01.png new file mode 100644 index 0000000..3144561 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/C_Elm01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/C_Elm03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/C_Elm03.png new file mode 100644 index 0000000..b045d4b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/C_Elm03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/C_Elm04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/C_Elm04.png new file mode 100644 index 0000000..0b232eb Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/C_Elm04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/C_Hat01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/C_Hat01.png new file mode 100644 index 0000000..620880e Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/C_Hat01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/C_Hat02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/C_Hat02.png new file mode 100644 index 0000000..08335ee Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/C_Hat02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Bones02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Bones02.png new file mode 100644 index 0000000..b49ed1a Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Bones02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Bones03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Bones03.png new file mode 100644 index 0000000..c3adb4b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Bones03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Gold01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Gold01.png new file mode 100644 index 0000000..0129e82 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Gold01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Gold02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Gold02.png new file mode 100644 index 0000000..115ee12 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Gold02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal01.png new file mode 100644 index 0000000..394b70d Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal02.png new file mode 100644 index 0000000..1f4900a Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal03.png new file mode 100644 index 0000000..f746ac4 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal04.png new file mode 100644 index 0000000..0f0bc49 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal05.png new file mode 100644 index 0000000..850d5ed Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal06.png new file mode 100644 index 0000000..1b6cc99 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal07.png new file mode 100644 index 0000000..e916d6d Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal08.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal08.png new file mode 100644 index 0000000..7850875 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal08.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal09.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal09.png new file mode 100644 index 0000000..32e51de Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Metal09.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Wood01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Wood01.png new file mode 100644 index 0000000..32cd977 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Wood01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Wood02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Wood02.png new file mode 100644 index 0000000..9b03dc4 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Wood02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Wood03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Wood03.png new file mode 100644 index 0000000..03e76d3 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Wood03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Wood04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Wood04.png new file mode 100644 index 0000000..b98c337 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/E_Wood04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Agate.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Agate.png new file mode 100644 index 0000000..a701852 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Agate.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Amethist.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Amethist.png new file mode 100644 index 0000000..684937f Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Amethist.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Antidote.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Antidote.png new file mode 100644 index 0000000..4dea993 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Antidote.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_BatWing.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_BatWing.png new file mode 100644 index 0000000..ef3cbf8 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_BatWing.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_BirdsBeak.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_BirdsBeak.png new file mode 100644 index 0000000..26bf7ef Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_BirdsBeak.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Bone.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Bone.png new file mode 100644 index 0000000..972d44a Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Bone.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Book.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Book.png new file mode 100644 index 0000000..8e5b687 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Book.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Bottle01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Bottle01.png new file mode 100644 index 0000000..401be59 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Bottle01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Bottle02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Bottle02.png new file mode 100644 index 0000000..8390d80 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Bottle02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Bottle03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Bottle03.png new file mode 100644 index 0000000..0093b07 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Bottle03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Bottle04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Bottle04.png new file mode 100644 index 0000000..6b87204 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Bottle04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_BronzeBar.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_BronzeBar.png new file mode 100644 index 0000000..a226465 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_BronzeBar.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_BronzeCoin.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_BronzeCoin.png new file mode 100644 index 0000000..a35da87 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_BronzeCoin.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Banana.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Banana.png new file mode 100644 index 0000000..4a492a9 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Banana.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Bread.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Bread.png new file mode 100644 index 0000000..71bfa9e Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Bread.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Carrot.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Carrot.png new file mode 100644 index 0000000..be2c0bf Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Carrot.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Cheese.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Cheese.png new file mode 100644 index 0000000..384e1c4 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Cheese.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Cherry.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Cherry.png new file mode 100644 index 0000000..a9f151e Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Cherry.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Fish.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Fish.png new file mode 100644 index 0000000..517fbef Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Fish.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Grapes.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Grapes.png new file mode 100644 index 0000000..bfb7e68 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Grapes.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_GreenGrapes.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_GreenGrapes.png new file mode 100644 index 0000000..da957de Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_GreenGrapes.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_GreenPepper.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_GreenPepper.png new file mode 100644 index 0000000..c675b5b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_GreenPepper.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Lemon.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Lemon.png new file mode 100644 index 0000000..0474910 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Lemon.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Meat.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Meat.png new file mode 100644 index 0000000..42df984 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Meat.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Mulberry.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Mulberry.png new file mode 100644 index 0000000..ceceacb Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Mulberry.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Mushroom.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Mushroom.png new file mode 100644 index 0000000..b9b9f51 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Mushroom.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Nut.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Nut.png new file mode 100644 index 0000000..44f10c8 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Nut.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Orange.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Orange.png new file mode 100644 index 0000000..e6c298b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Orange.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Pear.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Pear.png new file mode 100644 index 0000000..688e588 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Pear.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Pie.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Pie.png new file mode 100644 index 0000000..5fed405 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Pie.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Pineapple.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Pineapple.png new file mode 100644 index 0000000..9ef6dad Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Pineapple.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Radish.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Radish.png new file mode 100644 index 0000000..957f0d7 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Radish.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_RawFish.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_RawFish.png new file mode 100644 index 0000000..086e6dd Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_RawFish.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_RawMeat.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_RawMeat.png new file mode 100644 index 0000000..22c279f Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_RawMeat.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_RedPepper.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_RedPepper.png new file mode 100644 index 0000000..64703c7 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_RedPepper.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Strawberry.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Strawberry.png new file mode 100644 index 0000000..bc22727 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Strawberry.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Watermellon.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Watermellon.png new file mode 100644 index 0000000..92760bf Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_Watermellon.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_YellowPepper.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_YellowPepper.png new file mode 100644 index 0000000..460000e Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_C_YellowPepper.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Cannon01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Cannon01.png new file mode 100644 index 0000000..cc0624c Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Cannon01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Cannon02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Cannon02.png new file mode 100644 index 0000000..1ea7c56 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Cannon02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Cannon03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Cannon03.png new file mode 100644 index 0000000..30b7965 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Cannon03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Cannon04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Cannon04.png new file mode 100644 index 0000000..655d77b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Cannon04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Cannon05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Cannon05.png new file mode 100644 index 0000000..36ecb00 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Cannon05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Chest01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Chest01.png new file mode 100644 index 0000000..71cf24e Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Chest01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Chest02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Chest02.png new file mode 100644 index 0000000..58e470f Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Chest02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Clock.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Clock.png new file mode 100644 index 0000000..29db742 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Clock.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Clover.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Clover.png new file mode 100644 index 0000000..e4c977b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Clover.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Coal.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Coal.png new file mode 100644 index 0000000..110f497 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Coal.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Crystal01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Crystal01.png new file mode 100644 index 0000000..d398c4f Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Crystal01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Crystal02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Crystal02.png new file mode 100644 index 0000000..8a0ef08 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Crystal02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Crystal03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Crystal03.png new file mode 100644 index 0000000..9f53e3d Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Crystal03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Diamond.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Diamond.png new file mode 100644 index 0000000..22c2d02 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Diamond.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Eye.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Eye.png new file mode 100644 index 0000000..3147f90 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Eye.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Fabric.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Fabric.png new file mode 100644 index 0000000..210d2cf Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Fabric.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Fang.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Fang.png new file mode 100644 index 0000000..25f8daf Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Fang.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Feather01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Feather01.png new file mode 100644 index 0000000..26ea804 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Feather01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Feather02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Feather02.png new file mode 100644 index 0000000..03ef83b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Feather02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_FishTail.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_FishTail.png new file mode 100644 index 0000000..ffde951 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_FishTail.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_FoxTail.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_FoxTail.png new file mode 100644 index 0000000..6f6e848 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_FoxTail.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_FrogLeg.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_FrogLeg.png new file mode 100644 index 0000000..0f3ef81 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_FrogLeg.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_GoldBar.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_GoldBar.png new file mode 100644 index 0000000..649df55 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_GoldBar.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_GoldCoin.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_GoldCoin.png new file mode 100644 index 0000000..d94762a Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_GoldCoin.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Ink.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Ink.png new file mode 100644 index 0000000..a909d04 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Ink.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_IronBall.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_IronBall.png new file mode 100644 index 0000000..1bb3bf8 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_IronBall.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Jade.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Jade.png new file mode 100644 index 0000000..0c951f5 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Jade.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Key01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Key01.png new file mode 100644 index 0000000..8a84d23 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Key01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Key02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Key02.png new file mode 100644 index 0000000..9d63f0b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Key02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Key03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Key03.png new file mode 100644 index 0000000..a72d37b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Key03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Key04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Key04.png new file mode 100644 index 0000000..59548ed Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Key04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Key05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Key05.png new file mode 100644 index 0000000..3a18db6 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Key05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Key06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Key06.png new file mode 100644 index 0000000..54d5a7a Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Key06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Key07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Key07.png new file mode 100644 index 0000000..8895c0f Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Key07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Leaf.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Leaf.png new file mode 100644 index 0000000..3b67c05 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Leaf.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Map.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Map.png new file mode 100644 index 0000000..89f3605 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Map.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Mirror.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Mirror.png new file mode 100644 index 0000000..a7b9ed2 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Mirror.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Opal.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Opal.png new file mode 100644 index 0000000..9295f2c Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Opal.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_RabbitPaw.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_RabbitPaw.png new file mode 100644 index 0000000..adc3c3f Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_RabbitPaw.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Rock01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Rock01.png new file mode 100644 index 0000000..6064034 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Rock01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Rock02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Rock02.png new file mode 100644 index 0000000..9cfc57b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Rock02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Rock03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Rock03.png new file mode 100644 index 0000000..6124aba Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Rock03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Rock04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Rock04.png new file mode 100644 index 0000000..5439ff8 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Rock04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Rock05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Rock05.png new file mode 100644 index 0000000..903a270 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Rock05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Ruby.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Ruby.png new file mode 100644 index 0000000..188862e Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Ruby.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Sapphire.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Sapphire.png new file mode 100644 index 0000000..a0a6d63 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Sapphire.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_ScorpionClaw.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_ScorpionClaw.png new file mode 100644 index 0000000..8a85d42 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_ScorpionClaw.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Scroll.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Scroll.png new file mode 100644 index 0000000..23cd50e Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Scroll.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Scroll02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Scroll02.png new file mode 100644 index 0000000..f2411b3 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Scroll02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_SilverBar.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_SilverBar.png new file mode 100644 index 0000000..4a1b60b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_SilverBar.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_SilverCoin.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_SilverCoin.png new file mode 100644 index 0000000..875c925 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_SilverCoin.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_SnailShell.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_SnailShell.png new file mode 100644 index 0000000..0cb7bc2 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_SnailShell.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_SolidShell.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_SolidShell.png new file mode 100644 index 0000000..e196416 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_SolidShell.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Telescope.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Telescope.png new file mode 100644 index 0000000..bafa4cb Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Telescope.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Tentacle.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Tentacle.png new file mode 100644 index 0000000..97cb2e4 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Tentacle.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Torch01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Torch01.png new file mode 100644 index 0000000..a5c37be Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Torch01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Torch02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Torch02.png new file mode 100644 index 0000000..0e2c906 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Torch02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Water.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Water.png new file mode 100644 index 0000000..e347cd9 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_Water.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/I_WolfFur.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_WolfFur.png new file mode 100644 index 0000000..31244bb Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/I_WolfFur.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue01.png new file mode 100644 index 0000000..399cf44 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue02.png new file mode 100644 index 0000000..d4ea865 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue03.png new file mode 100644 index 0000000..81470f6 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue04.png new file mode 100644 index 0000000..0b9faef Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue05.png new file mode 100644 index 0000000..b1abdca Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue06.png new file mode 100644 index 0000000..76f2b66 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue07.png new file mode 100644 index 0000000..eda9089 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue08.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue08.png new file mode 100644 index 0000000..9d4a58b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Blue08.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Green01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Green01.png new file mode 100644 index 0000000..6dcd755 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Green01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Green02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Green02.png new file mode 100644 index 0000000..1221400 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Green02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Green03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Green03.png new file mode 100644 index 0000000..c657a0b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Green03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Green04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Green04.png new file mode 100644 index 0000000..fb5a330 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Green04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Green05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Green05.png new file mode 100644 index 0000000..446f8c8 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Green05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Green06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Green06.png new file mode 100644 index 0000000..d3cf6cd Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Green06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine01.png new file mode 100644 index 0000000..e7ed77c Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine02.png new file mode 100644 index 0000000..f730b88 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine03.png new file mode 100644 index 0000000..97481ba Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine04.png new file mode 100644 index 0000000..81c9257 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine05.png new file mode 100644 index 0000000..785adf7 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine06.png new file mode 100644 index 0000000..3746c9b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine07.png new file mode 100644 index 0000000..ade454f Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine08.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine08.png new file mode 100644 index 0000000..cef28a0 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine08.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine09.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine09.png new file mode 100644 index 0000000..9d7fa1c Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Medicine09.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Orange01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Orange01.png new file mode 100644 index 0000000..ee7da21 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Orange01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Orange02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Orange02.png new file mode 100644 index 0000000..294ce63 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Orange02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Orange03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Orange03.png new file mode 100644 index 0000000..170173d Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Orange03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Orange04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Orange04.png new file mode 100644 index 0000000..89b3a52 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Orange04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Orange05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Orange05.png new file mode 100644 index 0000000..316d696 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Orange05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Orange06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Orange06.png new file mode 100644 index 0000000..5dd417e Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Orange06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink01.png new file mode 100644 index 0000000..f90e006 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink02.png new file mode 100644 index 0000000..f5a2d7a Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink03.png new file mode 100644 index 0000000..7c0371d Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink04.png new file mode 100644 index 0000000..45434b0 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink05.png new file mode 100644 index 0000000..61b4a77 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink06.png new file mode 100644 index 0000000..913bd83 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink07.png new file mode 100644 index 0000000..36e116c Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink08.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink08.png new file mode 100644 index 0000000..2998b25 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Pink08.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Red01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Red01.png new file mode 100644 index 0000000..d9d5c96 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Red01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Red02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Red02.png new file mode 100644 index 0000000..56ff726 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Red02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Red03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Red03.png new file mode 100644 index 0000000..bbb80a6 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Red03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Red04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Red04.png new file mode 100644 index 0000000..66a6065 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Red04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Red05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Red05.png new file mode 100644 index 0000000..7ad082d Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Red05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Red06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Red06.png new file mode 100644 index 0000000..eea7e70 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Red06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Red07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Red07.png new file mode 100644 index 0000000..c0c1dd5 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Red07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_White01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_White01.png new file mode 100644 index 0000000..68f24d2 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_White01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_White02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_White02.png new file mode 100644 index 0000000..6bcdea5 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_White02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_White03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_White03.png new file mode 100644 index 0000000..25535dd Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_White03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_White04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_White04.png new file mode 100644 index 0000000..645ca48 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_White04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_White05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_White05.png new file mode 100644 index 0000000..fc6a1f6 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_White05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow01.png new file mode 100644 index 0000000..248267b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow02.png new file mode 100644 index 0000000..8b686f5 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow03.png new file mode 100644 index 0000000..5d26d82 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow04.png new file mode 100644 index 0000000..7221938 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow05.png new file mode 100644 index 0000000..71eae8f Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow06.png new file mode 100644 index 0000000..3cd1523 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow07.png new file mode 100644 index 0000000..3086400 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow08.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow08.png new file mode 100644 index 0000000..ae8afb4 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/P_Yellow08.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Axe01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Axe01.png new file mode 100644 index 0000000..1716410 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Axe01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Axe02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Axe02.png new file mode 100644 index 0000000..f900f9f Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Axe02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Axe03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Axe03.png new file mode 100644 index 0000000..9bf6229 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Axe03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Axe04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Axe04.png new file mode 100644 index 0000000..4722ba9 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Axe04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Axe05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Axe05.png new file mode 100644 index 0000000..a6a956d Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Axe05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Axe06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Axe06.png new file mode 100644 index 0000000..1bdb356 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Axe06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Axe07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Axe07.png new file mode 100644 index 0000000..2f28ba0 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Axe07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow01.png new file mode 100644 index 0000000..eb3655b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow02.png new file mode 100644 index 0000000..8feae95 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow03.png new file mode 100644 index 0000000..d598d65 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow04.png new file mode 100644 index 0000000..44e8986 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow05.png new file mode 100644 index 0000000..74ca3bb Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow06.png new file mode 100644 index 0000000..b212035 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow07.png new file mode 100644 index 0000000..50236ef Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow08.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow08.png new file mode 100644 index 0000000..0d47949 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow08.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow09.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow09.png new file mode 100644 index 0000000..c35b24f Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow09.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow10.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow10.png new file mode 100644 index 0000000..4561fdb Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow10.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow11.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow11.png new file mode 100644 index 0000000..bfbb27f Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow11.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow12.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow12.png new file mode 100644 index 0000000..f84f180 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow12.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow13.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow13.png new file mode 100644 index 0000000..1bb188b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow13.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow14.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow14.png new file mode 100644 index 0000000..d6c243c Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Bow14.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff01.png new file mode 100644 index 0000000..ab1756f Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff02.png new file mode 100644 index 0000000..46e9ab2 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff03.png new file mode 100644 index 0000000..0f9ecca Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff04.png new file mode 100644 index 0000000..9d0d3e9 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff05.png new file mode 100644 index 0000000..ff8fc59 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff06.png new file mode 100644 index 0000000..c562bce Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff07.png new file mode 100644 index 0000000..c562bce Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff08.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff08.png new file mode 100644 index 0000000..2fd69f6 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff08.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff09.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff09.png new file mode 100644 index 0000000..dcbb11f Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff09.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff10.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff10.png new file mode 100644 index 0000000..c5df567 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff10.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff11.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff11.png new file mode 100644 index 0000000..7a5a146 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff11.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff12.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff12.png new file mode 100644 index 0000000..45cee17 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff12.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff13.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff13.png new file mode 100644 index 0000000..804454f Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff13.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff14.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff14.png new file mode 100644 index 0000000..2e66075 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Buff14.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Dagger02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Dagger02.png new file mode 100644 index 0000000..017dd86 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Dagger02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Dagger03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Dagger03.png new file mode 100644 index 0000000..ffad54e Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Dagger03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Dagger04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Dagger04.png new file mode 100644 index 0000000..70ca4c3 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Dagger04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Dagger05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Dagger05.png new file mode 100644 index 0000000..419ffd9 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Dagger05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Dagger06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Dagger06.png new file mode 100644 index 0000000..71465ad Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Dagger06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Earth01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Earth01.png new file mode 100644 index 0000000..189a306 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Earth01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Earth02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Earth02.png new file mode 100644 index 0000000..60ed9a0 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Earth02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Earth03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Earth03.png new file mode 100644 index 0000000..8e54818 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Earth03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Earth04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Earth04.png new file mode 100644 index 0000000..fc360a1 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Earth04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Earth05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Earth05.png new file mode 100644 index 0000000..105ba25 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Earth05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Earth06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Earth06.png new file mode 100644 index 0000000..a635951 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Earth06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Earth07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Earth07.png new file mode 100644 index 0000000..a3c74f2 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Earth07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire01.png new file mode 100644 index 0000000..620b2f8 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire02.png new file mode 100644 index 0000000..5eacb67 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire03.png new file mode 100644 index 0000000..b581229 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire04.png new file mode 100644 index 0000000..8c78e6b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire05.png new file mode 100644 index 0000000..a4197a9 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire06.png new file mode 100644 index 0000000..c7b0305 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire07.png new file mode 100644 index 0000000..076a930 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire08.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire08.png new file mode 100644 index 0000000..01246e6 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Fire08.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy01.png new file mode 100644 index 0000000..7d79e22 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy02.png new file mode 100644 index 0000000..2f17ec9 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy03.png new file mode 100644 index 0000000..16f7bc6 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy04.png new file mode 100644 index 0000000..cb7b145 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy05.png new file mode 100644 index 0000000..5be76b6 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy06.png new file mode 100644 index 0000000..65c2ee6 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy07.png new file mode 100644 index 0000000..f6562e3 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy08.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy08.png new file mode 100644 index 0000000..913f2ea Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy08.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy09.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy09.png new file mode 100644 index 0000000..83419fa Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy09.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy10.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy10.png new file mode 100644 index 0000000..3dca24d Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Holy10.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice01.png new file mode 100644 index 0000000..fa0c5b3 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice02.png new file mode 100644 index 0000000..8ad9b4d Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice03.png new file mode 100644 index 0000000..7cf3bdb Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice04.png new file mode 100644 index 0000000..d39d8d4 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice05.png new file mode 100644 index 0000000..5310923 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice06.png new file mode 100644 index 0000000..b90e60c Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice07.png new file mode 100644 index 0000000..b54fa20 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice08.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice08.png new file mode 100644 index 0000000..1ef34a8 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice08.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice09.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice09.png new file mode 100644 index 0000000..96a1290 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Ice09.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Light01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Light01.png new file mode 100644 index 0000000..1d1f592 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Light01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Light02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Light02.png new file mode 100644 index 0000000..773add5 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Light02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Light03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Light03.png new file mode 100644 index 0000000..0fa7aca Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Light03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Light04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Light04.png new file mode 100644 index 0000000..56dc636 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Light04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic01.png new file mode 100644 index 0000000..15c639c Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic02.png new file mode 100644 index 0000000..0d623bf Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic03.png new file mode 100644 index 0000000..5654a04 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic04.png new file mode 100644 index 0000000..da45b40 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic05.png new file mode 100644 index 0000000..5eff177 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic06.png new file mode 100644 index 0000000..9a110af Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic07.png new file mode 100644 index 0000000..a3dbd76 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic08.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic08.png new file mode 100644 index 0000000..e46959d Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic08.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic09.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic09.png new file mode 100644 index 0000000..7c3a6b3 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic09.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic10.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic10.png new file mode 100644 index 0000000..261ce4e Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic10.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic11.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic11.png new file mode 100644 index 0000000..2797a93 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Magic11.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Physic01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Physic01.png new file mode 100644 index 0000000..c3b46a9 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Physic01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Physic02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Physic02.png new file mode 100644 index 0000000..8192f32 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Physic02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison01.png new file mode 100644 index 0000000..ff90875 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison02.png new file mode 100644 index 0000000..a1fac2c Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison03.png new file mode 100644 index 0000000..476b12f Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison04.png new file mode 100644 index 0000000..4ac01b5 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison05.png new file mode 100644 index 0000000..8702d46 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison06.png new file mode 100644 index 0000000..8e08739 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison07.png new file mode 100644 index 0000000..b76f316 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison08.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison08.png new file mode 100644 index 0000000..ed93125 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison08.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison09.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison09.png new file mode 100644 index 0000000..901060e Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Poison09.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow01.png new file mode 100644 index 0000000..b9683d7 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow02.png new file mode 100644 index 0000000..5d88f4b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow03.png new file mode 100644 index 0000000..98dce99 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow04.png new file mode 100644 index 0000000..30677eb Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow05.png new file mode 100644 index 0000000..ade6be8 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow06.png new file mode 100644 index 0000000..7c6b9be Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow07.png new file mode 100644 index 0000000..4ac1643 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow08.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow08.png new file mode 100644 index 0000000..16316e2 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow08.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow09.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow09.png new file mode 100644 index 0000000..766d26e Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow09.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow10.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow10.png new file mode 100644 index 0000000..2561c6c Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow10.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow11.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow11.png new file mode 100644 index 0000000..c06ac9b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow11.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow12.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow12.png new file mode 100644 index 0000000..45e88f6 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow12.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow13.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow13.png new file mode 100644 index 0000000..919c804 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow13.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow14.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow14.png new file mode 100644 index 0000000..bc0fb52 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow14.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow15.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow15.png new file mode 100644 index 0000000..4c0b6b8 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow15.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow16.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow16.png new file mode 100644 index 0000000..aba69c3 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Shadow16.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword01.png new file mode 100644 index 0000000..b622967 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword02.png new file mode 100644 index 0000000..3b18e0b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword03.png new file mode 100644 index 0000000..b6a8ac6 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword04.png new file mode 100644 index 0000000..7c7eb3a Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword05.png new file mode 100644 index 0000000..c9442d9 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword06.png new file mode 100644 index 0000000..42ad806 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword07.png new file mode 100644 index 0000000..9715a63 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword08.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword08.png new file mode 100644 index 0000000..63f2b3b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword08.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword09.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword09.png new file mode 100644 index 0000000..4bdcac9 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword09.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword10.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword10.png new file mode 100644 index 0000000..84eecc2 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword10.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword15.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword15.png new file mode 100644 index 0000000..633e1f1 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword15.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword16.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword16.png new file mode 100644 index 0000000..afbd888 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword16.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword17.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword17.png new file mode 100644 index 0000000..4446660 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword17.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword18.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword18.png new file mode 100644 index 0000000..51db6e6 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword18.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword19.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword19.png new file mode 100644 index 0000000..7ab10fa Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword19.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword20.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword20.png new file mode 100644 index 0000000..24da837 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword20.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword21.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword21.png new file mode 100644 index 0000000..a7c5f85 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Sword21.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Thunder01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Thunder01.png new file mode 100644 index 0000000..fc5d4a0 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Thunder01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Thunder02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Thunder02.png new file mode 100644 index 0000000..9e6f8b1 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Thunder02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Thunder03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Thunder03.png new file mode 100644 index 0000000..8de3602 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Thunder03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Thunder04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Thunder04.png new file mode 100644 index 0000000..aabfdc5 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Thunder04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Thunder05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Thunder05.png new file mode 100644 index 0000000..c6f188b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Thunder05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Thunder06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Thunder06.png new file mode 100644 index 0000000..6f78391 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Thunder06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Thunder07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Thunder07.png new file mode 100644 index 0000000..d5f060a Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Thunder07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Water01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Water01.png new file mode 100644 index 0000000..b22552b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Water01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Water02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Water02.png new file mode 100644 index 0000000..bfb3be3 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Water02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Water03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Water03.png new file mode 100644 index 0000000..5e75fd0 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Water03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Water04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Water04.png new file mode 100644 index 0000000..3c17bc6 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Water04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Water05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Water05.png new file mode 100644 index 0000000..bde5b06 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Water05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Water06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Water06.png new file mode 100644 index 0000000..af68390 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Water06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Water07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Water07.png new file mode 100644 index 0000000..a4480fa Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Water07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Wind01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Wind01.png new file mode 100644 index 0000000..90c8da9 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Wind01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Wind02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Wind02.png new file mode 100644 index 0000000..58562fc Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Wind02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Wind03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Wind03.png new file mode 100644 index 0000000..dfd94b3 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Wind03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Wind04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Wind04.png new file mode 100644 index 0000000..6d92970 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Wind04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Wind05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Wind05.png new file mode 100644 index 0000000..1ec6795 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Wind05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Wind06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Wind06.png new file mode 100644 index 0000000..428c5f9 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Wind06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Wind07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Wind07.png new file mode 100644 index 0000000..14c98eb Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/S_Wind07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe001.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe001.png new file mode 100644 index 0000000..74736f9 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe001.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe002.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe002.png new file mode 100644 index 0000000..9175970 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe002.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe003.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe003.png new file mode 100644 index 0000000..a608c34 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe003.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe004.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe004.png new file mode 100644 index 0000000..c27096d Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe004.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe005.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe005.png new file mode 100644 index 0000000..1aff856 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe005.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe006.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe006.png new file mode 100644 index 0000000..d9f7bdf Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe006.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe007.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe007.png new file mode 100644 index 0000000..2e5258f Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe007.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe008.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe008.png new file mode 100644 index 0000000..d43b522 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe008.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe009.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe009.png new file mode 100644 index 0000000..dbf377e Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe009.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe010.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe010.png new file mode 100644 index 0000000..e06c5ee Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe010.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe011.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe011.png new file mode 100644 index 0000000..51d162d Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe011.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe012.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe012.png new file mode 100644 index 0000000..59827c2 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe012.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe013.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe013.png new file mode 100644 index 0000000..a510713 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe013.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe014.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe014.png new file mode 100644 index 0000000..80d5ff7 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Axe014.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Book01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Book01.png new file mode 100644 index 0000000..d8c3c56 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Book01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Book02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Book02.png new file mode 100644 index 0000000..bfb1fc8 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Book02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Book03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Book03.png new file mode 100644 index 0000000..51ca4f3 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Book03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Book04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Book04.png new file mode 100644 index 0000000..0c2f552 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Book04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Book05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Book05.png new file mode 100644 index 0000000..517ba90 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Book05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Book06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Book06.png new file mode 100644 index 0000000..5bd2771 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Book06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Book07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Book07.png new file mode 100644 index 0000000..e6f06d2 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Book07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow01.png new file mode 100644 index 0000000..e2297da Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow02.png new file mode 100644 index 0000000..eb09d1b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow03.png new file mode 100644 index 0000000..7c33cf6 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow04.png new file mode 100644 index 0000000..de3d425 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow05.png new file mode 100644 index 0000000..46fc8b0 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow06.png new file mode 100644 index 0000000..d8bc8f4 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow07.png new file mode 100644 index 0000000..f69f86d Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow08.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow08.png new file mode 100644 index 0000000..9297e18 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow08.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow09.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow09.png new file mode 100644 index 0000000..2ae45c6 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow09.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow10.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow10.png new file mode 100644 index 0000000..cbe2721 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow10.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow11.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow11.png new file mode 100644 index 0000000..ff23a22 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow11.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow12.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow12.png new file mode 100644 index 0000000..cbd27fd Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow12.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow13.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow13.png new file mode 100644 index 0000000..2b1c252 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow13.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow14.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow14.png new file mode 100644 index 0000000..26f9245 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow14.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow15.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow15.png new file mode 100644 index 0000000..f94b509 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow15.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow16.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow16.png new file mode 100644 index 0000000..2c30f28 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow16.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow17.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow17.png new file mode 100644 index 0000000..b481fb3 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Bow17.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger001.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger001.png new file mode 100644 index 0000000..f6e2dab Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger001.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger002.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger002.png new file mode 100644 index 0000000..7e4c8dd Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger002.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger003.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger003.png new file mode 100644 index 0000000..d21f790 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger003.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger004.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger004.png new file mode 100644 index 0000000..4454d0d Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger004.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger005.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger005.png new file mode 100644 index 0000000..a2b8c7c Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger005.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger006.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger006.png new file mode 100644 index 0000000..d3f753f Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger006.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger007.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger007.png new file mode 100644 index 0000000..0d04e59 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger007.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger008.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger008.png new file mode 100644 index 0000000..3274ef0 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger008.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger009.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger009.png new file mode 100644 index 0000000..62e38cc Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger009.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger010.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger010.png new file mode 100644 index 0000000..577ba4f Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger010.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger011.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger011.png new file mode 100644 index 0000000..b92832e Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger011.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger012.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger012.png new file mode 100644 index 0000000..94b03ff Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger012.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger013.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger013.png new file mode 100644 index 0000000..3c97ef3 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger013.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger014.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger014.png new file mode 100644 index 0000000..0ee7dd8 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger014.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger015.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger015.png new file mode 100644 index 0000000..c3fb038 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger015.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger016.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger016.png new file mode 100644 index 0000000..bc5dd24 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger016.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger017.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger017.png new file mode 100644 index 0000000..7894e62 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger017.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger018.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger018.png new file mode 100644 index 0000000..765e02b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger018.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger019.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger019.png new file mode 100644 index 0000000..aecb1bc Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger019.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger020.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger020.png new file mode 100644 index 0000000..59d6a66 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger020.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger021.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger021.png new file mode 100644 index 0000000..453af68 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Dagger021.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Fist001.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Fist001.png new file mode 100644 index 0000000..d673544 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Fist001.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Fist002.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Fist002.png new file mode 100644 index 0000000..bd5166b Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Fist002.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Fist003.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Fist003.png new file mode 100644 index 0000000..3cc044e Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Fist003.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Fist004.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Fist004.png new file mode 100644 index 0000000..df25dc3 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Fist004.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Fist005.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Fist005.png new file mode 100644 index 0000000..ad779b2 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Fist005.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gold_Axe.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gold_Axe.png new file mode 100644 index 0000000..c236ed9 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gold_Axe.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gold_Bow.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gold_Bow.png new file mode 100644 index 0000000..cc9bc6c Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gold_Bow.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gold_Dagger.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gold_Dagger.png new file mode 100644 index 0000000..8871684 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gold_Dagger.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gold_Mace.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gold_Mace.png new file mode 100644 index 0000000..5e7d63e Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gold_Mace.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gold_Spear.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gold_Spear.png new file mode 100644 index 0000000..3c20113 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gold_Spear.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gold_Sword.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gold_Sword.png new file mode 100644 index 0000000..cde8cb9 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gold_Sword.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gun001.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gun001.png new file mode 100644 index 0000000..76ede7d Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gun001.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gun002.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gun002.png new file mode 100644 index 0000000..282701d Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gun002.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gun003.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gun003.png new file mode 100644 index 0000000..11d750a Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Gun003.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace001.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace001.png new file mode 100644 index 0000000..577051e Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace001.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace002.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace002.png new file mode 100644 index 0000000..54a80e0 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace002.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace003.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace003.png new file mode 100644 index 0000000..8b961b1 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace003.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace004.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace004.png new file mode 100644 index 0000000..81c9658 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace004.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace005.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace005.png new file mode 100644 index 0000000..1061ea7 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace005.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace006.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace006.png new file mode 100644 index 0000000..47bb935 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace006.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace007.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace007.png new file mode 100644 index 0000000..e220de8 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace007.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace008.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace008.png new file mode 100644 index 0000000..01ccac4 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace008.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace009.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace009.png new file mode 100644 index 0000000..ab66259 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace009.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace010.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace010.png new file mode 100644 index 0000000..dd34c78 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace010.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace011.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace011.png new file mode 100644 index 0000000..81eb6fb Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace011.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace012.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace012.png new file mode 100644 index 0000000..76f5dea Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace012.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace013.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace013.png new file mode 100644 index 0000000..184e3c3 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace013.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace014.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace014.png new file mode 100644 index 0000000..401c554 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace014.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace15.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace15.png new file mode 100644 index 0000000..1b478fa Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace15.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace16.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace16.png new file mode 100644 index 0000000..8c08f8d Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Mace16.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear001.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear001.png new file mode 100644 index 0000000..e707e97 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear001.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear002.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear002.png new file mode 100644 index 0000000..785045e Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear002.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear003.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear003.png new file mode 100644 index 0000000..3bba345 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear003.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear004.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear004.png new file mode 100644 index 0000000..a755b9a Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear004.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear005.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear005.png new file mode 100644 index 0000000..dfe9464 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear005.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear006.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear006.png new file mode 100644 index 0000000..64bbb66 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear006.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear007.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear007.png new file mode 100644 index 0000000..a2fee6d Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear007.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear008.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear008.png new file mode 100644 index 0000000..5baf456 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear008.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear009.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear009.png new file mode 100644 index 0000000..5c364ea Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear009.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear010.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear010.png new file mode 100644 index 0000000..289ed41 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear010.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear011.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear011.png new file mode 100644 index 0000000..c45b3b0 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear011.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear012.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear012.png new file mode 100644 index 0000000..64eec76 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear012.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear013.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear013.png new file mode 100644 index 0000000..5a457d8 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear013.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear014.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear014.png new file mode 100644 index 0000000..588fac6 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Spear014.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff01.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff01.png new file mode 100644 index 0000000..37b6d88 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff01.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff02.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff02.png new file mode 100644 index 0000000..24c6dbf Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff02.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff03.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff03.png new file mode 100644 index 0000000..de68131 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff03.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff04.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff04.png new file mode 100644 index 0000000..c6f9d15 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff04.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff05.png new file mode 100644 index 0000000..7e073ad Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff05.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff06.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff06.png new file mode 100644 index 0000000..061e5cb Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff06.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff07.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff07.png new file mode 100644 index 0000000..8a9e7d8 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff07.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff08.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff08.png new file mode 100644 index 0000000..6e31d2f Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Staff08.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword001.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword001.png new file mode 100644 index 0000000..9d0bd7c Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword001.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword002.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword002.png new file mode 100644 index 0000000..757e087 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword002.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword003.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword003.png new file mode 100644 index 0000000..1eba7ad Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword003.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword004.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword004.png new file mode 100644 index 0000000..7939ed2 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword004.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword005.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword005.png new file mode 100644 index 0000000..5c81410 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword005.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword006.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword006.png new file mode 100644 index 0000000..09c059a Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword006.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword007.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword007.png new file mode 100644 index 0000000..b4bb849 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword007.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword008.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword008.png new file mode 100644 index 0000000..8dfb408 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword008.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword009.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword009.png new file mode 100644 index 0000000..ab11cb4 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword009.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword010.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword010.png new file mode 100644 index 0000000..8fe6b6f Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword010.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword011.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword011.png new file mode 100644 index 0000000..05af7f4 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword011.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword012.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword012.png new file mode 100644 index 0000000..317a8c2 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword012.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword013.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword013.png new file mode 100644 index 0000000..582d66a Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword013.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword014.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword014.png new file mode 100644 index 0000000..f649fac Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword014.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword015.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword015.png new file mode 100644 index 0000000..0225ee3 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword015.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword016.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword016.png new file mode 100644 index 0000000..e304e66 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword016.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword017.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword017.png new file mode 100644 index 0000000..63d30dc Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword017.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword018.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword018.png new file mode 100644 index 0000000..2725cd1 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword018.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword019.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword019.png new file mode 100644 index 0000000..dc33c37 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword019.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword020.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword020.png new file mode 100644 index 0000000..4e93215 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword020.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword021.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword021.png new file mode 100644 index 0000000..81f7e10 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword021.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword022.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword022.png new file mode 100644 index 0000000..98afed6 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Sword022.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Throw001.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Throw001.png new file mode 100644 index 0000000..b342b07 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Throw001.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Throw002.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Throw002.png new file mode 100644 index 0000000..edceccd Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Throw002.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Throw003.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Throw003.png new file mode 100644 index 0000000..987e344 Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Throw003.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Throw004.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Throw004.png new file mode 100644 index 0000000..6a419de Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Throw004.png differ diff --git a/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Throw05.png b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Throw05.png new file mode 100644 index 0000000..4c37fac Binary files /dev/null and b/apps/web-demo/assets-src/items/7soul-rpg-icons/W_Throw05.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/acorn.png b/apps/web-demo/assets-src/items/idylwild-inventory/acorn.png new file mode 100644 index 0000000..10f1c49 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/acorn.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/apple.png b/apps/web-demo/assets-src/items/idylwild-inventory/apple.png new file mode 100644 index 0000000..d6c7b77 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/apple.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/arrow.png b/apps/web-demo/assets-src/items/idylwild-inventory/arrow.png new file mode 100644 index 0000000..8486bce Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/arrow.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/basket.png b/apps/web-demo/assets-src/items/idylwild-inventory/basket.png new file mode 100644 index 0000000..43c1260 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/basket.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/board.png b/apps/web-demo/assets-src/items/idylwild-inventory/board.png new file mode 100644 index 0000000..2c1d1a9 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/board.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/bone.png b/apps/web-demo/assets-src/items/idylwild-inventory/bone.png new file mode 100644 index 0000000..6497aba Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/bone.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/bonemeal.png b/apps/web-demo/assets-src/items/idylwild-inventory/bonemeal.png new file mode 100644 index 0000000..0540b7d Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/bonemeal.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/book.png b/apps/web-demo/assets-src/items/idylwild-inventory/book.png new file mode 100644 index 0000000..289109c Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/book.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/bread.png b/apps/web-demo/assets-src/items/idylwild-inventory/bread.png new file mode 100644 index 0000000..8f03c02 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/bread.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/bucket.png b/apps/web-demo/assets-src/items/idylwild-inventory/bucket.png new file mode 100644 index 0000000..d12e755 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/bucket.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/chain.png b/apps/web-demo/assets-src/items/idylwild-inventory/chain.png new file mode 100644 index 0000000..ddd90d7 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/chain.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/cloth.png b/apps/web-demo/assets-src/items/idylwild-inventory/cloth.png new file mode 100644 index 0000000..7e7c0b0 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/cloth.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/copper_ingot.png b/apps/web-demo/assets-src/items/idylwild-inventory/copper_ingot.png new file mode 100644 index 0000000..c3c571a Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/copper_ingot.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/copper_ore.png b/apps/web-demo/assets-src/items/idylwild-inventory/copper_ore.png new file mode 100644 index 0000000..9719ef6 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/copper_ore.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/copper_rod.png b/apps/web-demo/assets-src/items/idylwild-inventory/copper_rod.png new file mode 100644 index 0000000..7a54cf0 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/copper_rod.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/egg.png b/apps/web-demo/assets-src/items/idylwild-inventory/egg.png new file mode 100644 index 0000000..ab35b05 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/egg.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/gold_ingot.png b/apps/web-demo/assets-src/items/idylwild-inventory/gold_ingot.png new file mode 100644 index 0000000..e9bbb8d Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/gold_ingot.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/gold_key.png b/apps/web-demo/assets-src/items/idylwild-inventory/gold_key.png new file mode 100644 index 0000000..589743c Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/gold_key.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/gold_ore.png b/apps/web-demo/assets-src/items/idylwild-inventory/gold_ore.png new file mode 100644 index 0000000..540cec5 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/gold_ore.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/grass.png b/apps/web-demo/assets-src/items/idylwild-inventory/grass.png new file mode 100644 index 0000000..5239a73 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/grass.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/herb.png b/apps/web-demo/assets-src/items/idylwild-inventory/herb.png new file mode 100644 index 0000000..6394ba0 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/herb.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/inkpot.png b/apps/web-demo/assets-src/items/idylwild-inventory/inkpot.png new file mode 100644 index 0000000..fd34233 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/inkpot.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/inventory.png b/apps/web-demo/assets-src/items/idylwild-inventory/inventory.png new file mode 100644 index 0000000..bf31d98 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/inventory.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/inventory_ase.ase b/apps/web-demo/assets-src/items/idylwild-inventory/inventory_ase.ase new file mode 100644 index 0000000..b6f0905 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/inventory_ase.ase differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/iron_ingot.png b/apps/web-demo/assets-src/items/idylwild-inventory/iron_ingot.png new file mode 100644 index 0000000..ea8eeda Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/iron_ingot.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/iron_ore.png b/apps/web-demo/assets-src/items/idylwild-inventory/iron_ore.png new file mode 100644 index 0000000..2e9875a Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/iron_ore.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/iron_pickaxe.png b/apps/web-demo/assets-src/items/idylwild-inventory/iron_pickaxe.png new file mode 100644 index 0000000..1959d5d Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/iron_pickaxe.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/leather.png b/apps/web-demo/assets-src/items/idylwild-inventory/leather.png new file mode 100644 index 0000000..9c5d814 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/leather.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/log.png b/apps/web-demo/assets-src/items/idylwild-inventory/log.png new file mode 100644 index 0000000..41aa21e Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/log.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/mug.png b/apps/web-demo/assets-src/items/idylwild-inventory/mug.png new file mode 100644 index 0000000..339e7d6 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/mug.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/mushroom.png b/apps/web-demo/assets-src/items/idylwild-inventory/mushroom.png new file mode 100644 index 0000000..beb30d1 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/mushroom.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/parchment.png b/apps/web-demo/assets-src/items/idylwild-inventory/parchment.png new file mode 100644 index 0000000..e00de27 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/parchment.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/plate.png b/apps/web-demo/assets-src/items/idylwild-inventory/plate.png new file mode 100644 index 0000000..5965906 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/plate.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/platinum_ingot.png b/apps/web-demo/assets-src/items/idylwild-inventory/platinum_ingot.png new file mode 100644 index 0000000..975c49b Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/platinum_ingot.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/platinum_ore.png b/apps/web-demo/assets-src/items/idylwild-inventory/platinum_ore.png new file mode 100644 index 0000000..f2022cd Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/platinum_ore.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/quill.png b/apps/web-demo/assets-src/items/idylwild-inventory/quill.png new file mode 100644 index 0000000..e4e2e60 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/quill.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/rawhide.png b/apps/web-demo/assets-src/items/idylwild-inventory/rawhide.png new file mode 100644 index 0000000..c72ef75 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/rawhide.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/rope.png b/apps/web-demo/assets-src/items/idylwild-inventory/rope.png new file mode 100644 index 0000000..8daf1ae Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/rope.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/sack.png b/apps/web-demo/assets-src/items/idylwild-inventory/sack.png new file mode 100644 index 0000000..e32429d Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/sack.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/scroll.png b/apps/web-demo/assets-src/items/idylwild-inventory/scroll.png new file mode 100644 index 0000000..9cd6336 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/scroll.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/silk.png b/apps/web-demo/assets-src/items/idylwild-inventory/silk.png new file mode 100644 index 0000000..79317c9 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/silk.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/silver_ingot.png b/apps/web-demo/assets-src/items/idylwild-inventory/silver_ingot.png new file mode 100644 index 0000000..9bd8d33 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/silver_ingot.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/silver_ore.png b/apps/web-demo/assets-src/items/idylwild-inventory/silver_ore.png new file mode 100644 index 0000000..a7adbc0 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/silver_ore.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/silver_shovel.png b/apps/web-demo/assets-src/items/idylwild-inventory/silver_shovel.png new file mode 100644 index 0000000..06b143b Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/silver_shovel.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/steak.png b/apps/web-demo/assets-src/items/idylwild-inventory/steak.png new file mode 100644 index 0000000..d7f2029 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/steak.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/stick.png b/apps/web-demo/assets-src/items/idylwild-inventory/stick.png new file mode 100644 index 0000000..614b8ad Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/stick.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/string.png b/apps/web-demo/assets-src/items/idylwild-inventory/string.png new file mode 100644 index 0000000..e37ed76 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/string.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/thread.png b/apps/web-demo/assets-src/items/idylwild-inventory/thread.png new file mode 100644 index 0000000..0e2ebfb Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/thread.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/torch.png b/apps/web-demo/assets-src/items/idylwild-inventory/torch.png new file mode 100644 index 0000000..fa85f28 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/torch.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/torch_lit.png b/apps/web-demo/assets-src/items/idylwild-inventory/torch_lit.png new file mode 100644 index 0000000..771c562 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/torch_lit.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/urn.png b/apps/web-demo/assets-src/items/idylwild-inventory/urn.png new file mode 100644 index 0000000..e093a06 Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/urn.png differ diff --git a/apps/web-demo/assets-src/items/idylwild-inventory/wheat.png b/apps/web-demo/assets-src/items/idylwild-inventory/wheat.png new file mode 100644 index 0000000..51f5cff Binary files /dev/null and b/apps/web-demo/assets-src/items/idylwild-inventory/wheat.png differ diff --git a/apps/web-demo/demo-content/characters/david.ts b/apps/web-demo/demo-content/characters/david.ts new file mode 100644 index 0000000..12c98b7 --- /dev/null +++ b/apps/web-demo/demo-content/characters/david.ts @@ -0,0 +1,43 @@ +// David, the demo's playable character. Pass it to the runtime: +// +// Demo content: NOT part of the engine packages. +import { + buildFrameUrls, + type CharacterDefinition, +} from "@pointclick-engine/engine-renderer-r3f"; + +const ROOT = "/assets/sprites/david"; + +export const DAVID: CharacterDefinition = { + id: "david", + clips: { + idle: { frames: [`${ROOT}/david_idle.png`], fps: 1, loop: true }, + north: { + frames: buildFrameUrls(ROOT, "david-walk-north", 9).reverse(), + fps: 16, + loop: true, + }, + south: { + frames: buildFrameUrls(ROOT, "david-walk-south", 8, 3), + fps: 16, + loop: true, + }, + west: { + frames: buildFrameUrls(ROOT, "david-walk-west", 9).reverse(), + fps: 16, + loop: true, + mirror: true, + }, + east: { + frames: buildFrameUrls(ROOT, "david-walk-west", 9).reverse(), + fps: 16, + loop: true, + }, + }, + speaking: { + frames: buildFrameUrls(ROOT, "david_speaking", 8), + fps: 8, + loop: true, + }, + size: [1.4, 2.94], +}; diff --git a/apps/web-demo/demo-content/characters/guide.ts b/apps/web-demo/demo-content/characters/guide.ts new file mode 100644 index 0000000..11ba302 --- /dev/null +++ b/apps/web-demo/demo-content/characters/guide.ts @@ -0,0 +1,14 @@ +// El guia de `town`: reutiliza el sprite de David con otro id de personaje. +// Demo content: NOT part of the engine packages. +import type { CharacterDefinition } from "@pointclick-engine/engine-renderer-r3f"; + +import { DAVID } from "./david"; +import { HELIX } from "./helix"; + +/** Personajes de los NPCs de la demo por `characterId` (prop `characters` del viewport). */ +export const GUIDE: CharacterDefinition = { ...DAVID, id: "guide" }; + +export const DEMO_NPC_CHARACTERS: Record = { + [GUIDE.id]: GUIDE, + [HELIX.id]: HELIX, +}; diff --git a/apps/web-demo/demo-content/characters/helix.ts b/apps/web-demo/demo-content/characters/helix.ts new file mode 100644 index 0000000..70979c9 --- /dev/null +++ b/apps/web-demo/demo-content/characters/helix.ts @@ -0,0 +1,23 @@ +// Helix: NPC de la escena de pruebas `sciFiLab`. +// Arte: "8 Directional 2D Point and Click Male Character", de DeMoNiCaTeD (CC-BY-SA 4.0). +// Frames recortados y escalados x4 desde la hoja original; ver `public/assets/LICENSES-art.md`. +// Demo content: NOT part of the engine packages. +import { + buildFrameUrls, + type CharacterDefinition, +} from "@pointclick-engine/engine-renderer-r3f"; + +const ROOT = "/assets/sprites/helix"; + +export const HELIX: CharacterDefinition = { + id: "helix", + clips: { + idle: { frames: [`${ROOT}/helix_idle.png`], fps: 1, loop: true }, + north: { frames: buildFrameUrls(ROOT, "helix-walk-north", 8), fps: 10, loop: true }, + south: { frames: buildFrameUrls(ROOT, "helix-walk-south", 8), fps: 10, loop: true }, + west: { frames: buildFrameUrls(ROOT, "helix-walk-east", 8), fps: 10, loop: true, mirror: true }, + east: { frames: buildFrameUrls(ROOT, "helix-walk-east", 8), fps: 10, loop: true }, + }, + // La hoja no trae clip de habla: mientras habla se queda en reposo. + size: [1.4, 2.94], +}; diff --git a/apps/web-demo/demo-content/content.test.ts b/apps/web-demo/demo-content/content.test.ts new file mode 100644 index 0000000..26c7a38 --- /dev/null +++ b/apps/web-demo/demo-content/content.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from "vitest"; +import { validateContent } from "@pointclick-engine/engine-core"; + +import { DEMO_RUNTIME_CONFIG } from "../app/lib/engine/runtime/demoViewportOptions"; + +describe("contenido de la demo", () => { + it("pasa validateContent sin errores", () => { + const issues = validateContent({ + scenes: DEMO_RUNTIME_CONFIG.scenes ?? [], + items: DEMO_RUNTIME_CONFIG.items ?? [], + ...(DEMO_RUNTIME_CONFIG.dialogues ? { dialogues: DEMO_RUNTIME_CONFIG.dialogues } : {}), + ...(DEMO_RUNTIME_CONFIG.dialogKeys ? { dialogKeys: DEMO_RUNTIME_CONFIG.dialogKeys } : {}), + }); + const errors = issues.filter((i) => i.severity === "error"); + expect(errors).toEqual([]); + }); +}); diff --git a/apps/web-demo/demo-content/dialogs/index.ts b/apps/web-demo/demo-content/dialogs/index.ts index d568dbf..48441f1 100644 --- a/apps/web-demo/demo-content/dialogs/index.ts +++ b/apps/web-demo/demo-content/dialogs/index.ts @@ -34,6 +34,10 @@ export const demoDictionaries: LocaleDictionaries = { "¡Bienvenido! Aquí puedes ser tú mismo, o alguien más.", ], }, + // Frase fija (antes un texto en codigo, siempre en castellano): se conserva igual en ambos idiomas. + personalRoomLeaveBlocked: { + phrases: ["Sería mejor recoger todo lo que pueda del cuarto antes de irme..."], + }, inventoryDropHit: { phrases: [ "¡Exacto! El Gameboy va ahí.", @@ -210,6 +214,39 @@ export const demoDictionaries: LocaleDictionaries = { "Mira eso. Todo en su sitio. No suele pasar.", ], }, + // --- Contenido de prueba (16b): guia de la plaza, ordenador y llave --- + // Textos del motor para hotspots (verbos del menu y frase generica). Se definen aqui, y no + // se dejan a `ensureEngineTexts`, porque el menu calcula sus etiquetas en el primer render. + "engine.verb.look": { phrases: ["Mirar"] }, + "engine.verb.use": { phrases: ["Usar"] }, + "engine.verb.talk": { phrases: ["Hablar"] }, + "engine.hotspot.noAction": { phrases: ["No sé qué hacer con eso."] }, + "helix.name": { phrases: ["Helix"] }, + "helix.hello": { phrases: ["Soy de otro juego. Me han dejado aquí de prueba y nadie ha venido a recogerme."] }, + "guide.name": { phrases: ["Guía"] }, + "guide.hello": { phrases: ["¡Eh, forastero! Pareces perdido. ¿Te echo una mano?"] }, + "guide.c.trophy": { phrases: ["Mira, llevo un trofeo."] }, + "guide.c.who": { phrases: ["¿Quién eres?"] }, + "guide.c.help": { phrases: ["¿Puedes ayudarme?"] }, + "guide.c.bye": { phrases: ["Hasta luego."] }, + "guide.who": { phrases: ["Soy el guía de la plaza. Conozco cada rincón, menos la mina: sigue cerrada."] }, + "guide.trophy": { phrases: ["¡Menudo trofeo! Si lo dejas en la peana de la plaza pasarán cosas."] }, + "guide.help": { phrases: ["Toma, el mango de una llave rota. El paletón debe de andar tirado por la plaza."] }, + "guide.bye": { phrases: ["Cuídate, forastero."] }, + "hotspot.computer.name": { phrases: ["Ordenador"] }, + "computer.look": { phrases: ["Mi ordenador de siempre. Aún tiene el salvapantallas de los tubos."] }, + "computer.use": { phrases: ["Pide una contraseña. Seguro que es 1234... o no."] }, + "computer.use.after": { phrases: ["Ni con la Gameboy a cuestas me deja entrar."] }, + "computer.gameboy": { phrases: ["La Gameboy no tiene ningún puerto que encaje con el ordenador."] }, + "computer.nothing": { phrases: ["Eso no tiene nada que ver con el ordenador."] }, + "item.key-handle.description": { phrases: ["El mango de una llave rota. Le falta el paletón."] }, + "item.key-bit.description": { phrases: ["El paletón de una llave rota. Le falta el mango."] }, + "item.bronze-key.description": { phrases: ["Una llave de bronce, entera de nuevo. Quizá abra la mina... o no."] }, + "item.key-part.drop.default.miss": { phrases: ["Aquí no hace nada. Lo guardo otra vez."] }, + "combine.key.done": { phrases: ["Mango y paletón encajan: ¡una llave de bronce entera!"] }, + inventoryCombineFailed: { + phrases: ["Eso no se puede combinar con eso.", "No encajan. Cada cosa vuelve a su sitio."], + }, // --- Intro --- "intro.text": { phrases: [ @@ -267,6 +304,10 @@ export const demoDictionaries: LocaleDictionaries = { "Welcome! Be yourself here, or someone else.", ], }, + // Frase fija (antes un texto en codigo, siempre en castellano): se conserva igual en ambos idiomas. + personalRoomLeaveBlocked: { + phrases: ["Sería mejor recoger todo lo que pueda del cuarto antes de irme..."], + }, inventoryDropHit: { phrases: [ "Perfect. The Gameboy goes there.", @@ -443,6 +484,38 @@ export const demoDictionaries: LocaleDictionaries = { "Look at that. Everything in its place. Doesn't happen often.", ], }, + // --- Test content (16b): town guide, computer and key --- + // Engine texts for hotspots (menu verbs and generic phrase); see the "es" block. + "engine.verb.look": { phrases: ["Look"] }, + "engine.verb.use": { phrases: ["Use"] }, + "engine.verb.talk": { phrases: ["Talk"] }, + "engine.hotspot.noAction": { phrases: ["I don't know what to do with that."] }, + "helix.name": { phrases: ["Helix"] }, + "helix.hello": { phrases: ["I am from another game. They left me here as a test and nobody came back for me."] }, + "guide.name": { phrases: ["Guide"] }, + "guide.hello": { phrases: ["Hey, stranger! You look lost. Need a hand?"] }, + "guide.c.trophy": { phrases: ["Look, I'm carrying a trophy."] }, + "guide.c.who": { phrases: ["Who are you?"] }, + "guide.c.help": { phrases: ["Can you help me?"] }, + "guide.c.bye": { phrases: ["See you later."] }, + "guide.who": { phrases: ["I'm the town guide. I know every corner except the mine: it's still closed."] }, + "guide.trophy": { phrases: ["What a trophy! Put it on the pedestal in the square and things will happen."] }, + "guide.help": { phrases: ["Here, the handle of a broken key. The bit must be lying around the square."] }, + "guide.bye": { phrases: ["Take care, stranger."] }, + "hotspot.computer.name": { phrases: ["Computer"] }, + "computer.look": { phrases: ["My trusty computer. It still has the pipes screensaver."] }, + "computer.use": { phrases: ["It asks for a password. Surely it's 1234... or not."] }, + "computer.use.after": { phrases: ["Even carrying the Gameboy it won't let me in."] }, + "computer.gameboy": { phrases: ["The Gameboy has no port that fits the computer."] }, + "computer.nothing": { phrases: ["That has nothing to do with the computer."] }, + "item.key-handle.description": { phrases: ["The handle of a broken key. The bit is missing."] }, + "item.key-bit.description": { phrases: ["The bit of a broken key. The handle is missing."] }, + "item.bronze-key.description": { phrases: ["A bronze key, whole again. Maybe it opens the mine... or not."] }, + "item.key-part.drop.default.miss": { phrases: ["It does nothing here. Putting it away."] }, + "combine.key.done": { phrases: ["Handle and bit fit: a whole bronze key!"] }, + inventoryCombineFailed: { + phrases: ["Those can't be combined.", "They don't fit together. Each thing goes back."], + }, // --- Intro --- "intro.text": { phrases: [ diff --git a/apps/web-demo/demo-content/dialogues/guide.ts b/apps/web-demo/demo-content/dialogues/guide.ts new file mode 100644 index 0000000..4a65ccf --- /dev/null +++ b/apps/web-demo/demo-content/dialogues/guide.ts @@ -0,0 +1,40 @@ +// Conversacion de prueba con el guia de `town` (contenido de la demo, no del motor). +// +// Cubre: una opcion condicionada a tener el trofeo, opciones `once` y un efecto que pone un +// flag y entrega un item (`key-handle`, que se combina con `key-bit`). +import { act, cond, dialogue, type DialogueDefinition } from "@pointclick-engine/engine-core"; + +export const GUIDE_DIALOGUE_ID = "guide-talk"; + +export const guideDialogue: DialogueDefinition = dialogue.define( + GUIDE_DIALOGUE_ID, + "root", + dialogue.node("root", { + speaker: "guide", + line: "guide.hello", + choices: [ + // 0: solo si se lleva el trofeo encima. + dialogue.choice("guide.c.trophy", { + when: cond.hasItem("trophy"), + do: [act.setFlag("guide.trophyShown")], + next: "trophy", + }), + // 1: una sola vez. + dialogue.choice("guide.c.who", { once: true, next: "who" }), + // 2: una sola vez; pone un flag y entrega el mango de la llave. + dialogue.choice("guide.c.help", { + once: true, + do: [act.setFlag("guide.helped"), act.giveItem("key-handle")], + next: "help", + }), + // 3: despedida. + dialogue.choice("guide.c.bye", { next: "bye" }), + ], + }), + dialogue.node("who", { speaker: "guide", line: "guide.who", next: "root" }), + dialogue.node("trophy", { speaker: "guide", line: "guide.trophy", next: "root" }), + dialogue.node("help", { speaker: "guide", line: "guide.help", next: "root" }), + dialogue.node("bye", { speaker: "guide", line: "guide.bye" }), +); + +export const demoDialogues: DialogueDefinition[] = [guideDialogue]; diff --git a/apps/web-demo/demo-content/items/index.ts b/apps/web-demo/demo-content/items/index.ts index 645b9fa..915474f 100644 --- a/apps/web-demo/demo-content/items/index.ts +++ b/apps/web-demo/demo-content/items/index.ts @@ -1,3 +1,5 @@ +import { act, otherwise } from "@pointclick-engine/engine-core"; + import type { ItemDefinition, ItemInteractionRule } from "./types"; export type { ItemDefinition, ItemInteractionRule }; @@ -8,6 +10,7 @@ export const ITEMS: Record = { name: "Gameboy", spriteUrl: "/assets/gameboy/gameboy.png", descriptionDialogKey: "item.gameboy.description", + pickupSoundUrl: "/assets/audio/sfx/pickup-gameboy.ogg", interactionRules: { "personal-room-gameboy-drop-target": { outcome: "place", @@ -74,6 +77,46 @@ export const ITEMS: Record = { missDialogKey: "item.trophy.drop.default.miss", }, }, + // --- Combinacion de prueba: mango + paleton dan una llave de bronce (reutilizan el sprite de la llave) --- + // Mango: lo entrega el guia de `town` al hablar con el (opcion `once` del dialogo). + "key-handle": { + id: "key-handle", + name: "Mango roto", + spriteUrl: "/assets/key/gold-key.png", + descriptionDialogKey: "item.key-handle.description", + interactionRules: {}, + defaultRule: { outcome: "return", missDialogKey: "item.key-part.drop.default.miss" }, + // Se combina con el paleton (esta regla vale en ambos sentidos). + combine: { + "key-bit": [ + otherwise( + // `say` espera a que se cierre el bocadillo: el resultado va antes que la frase. + act.removeItem("key-handle"), + act.removeItem("key-bit"), + act.giveItem("bronze-key"), + act.say("combine.key.done"), + ), + ], + }, + }, + // Paleton: esta en el suelo de `town` (initialItems). + "key-bit": { + id: "key-bit", + name: "Paletón roto", + spriteUrl: "/assets/key/gold-key.png", + descriptionDialogKey: "item.key-bit.description", + interactionRules: {}, + defaultRule: { outcome: "return", missDialogKey: "item.key-part.drop.default.miss" }, + }, + // Resultado de la combinacion. + "bronze-key": { + id: "bronze-key", + name: "Llave de bronce", + spriteUrl: "/assets/key/gold-key.png", + descriptionDialogKey: "item.bronze-key.description", + interactionRules: {}, + defaultRule: { outcome: "return", missDialogKey: "item.key-part.drop.default.miss" }, + }, }; export function getItemDefinition(itemId: string): ItemDefinition | null { diff --git a/apps/web-demo/demo-content/items/types.ts b/apps/web-demo/demo-content/items/types.ts index c93c446..c7cbb13 100644 --- a/apps/web-demo/demo-content/items/types.ts +++ b/apps/web-demo/demo-content/items/types.ts @@ -1,23 +1,5 @@ -import type { DialogKey } from "../dialogs/types"; +import type { ItemDefinition, ItemInteractionRule } from "@pointclick-engine/engine-core"; -export type ItemDropOutcome = "consume" | "place" | "return"; +export type { ItemDefinition, ItemInteractionRule }; -export type ItemInteractionRule = { - outcome: ItemDropOutcome; - hitDialogKey?: DialogKey; - missDialogKey?: DialogKey; - placeCanPickup?: boolean; - placeHasCollision?: boolean; - placeCollisionHalfSize?: [number, number, number]; - pickupSuccessDialogKey?: DialogKey; - pickupBlockedDialogKey?: DialogKey; -}; - -export type ItemDefinition = { - id: string; - name: string; - spriteUrl: string; - descriptionDialogKey?: DialogKey; - interactionRules: Record; - defaultRule: ItemInteractionRule; -}; +export type ItemDropOutcome = ItemInteractionRule["outcome"]; diff --git a/apps/web-demo/demo-content/scenes/scenes.ts b/apps/web-demo/demo-content/scenes/scenes.ts index 3f2880c..56dd6d2 100644 --- a/apps/web-demo/demo-content/scenes/scenes.ts +++ b/apps/web-demo/demo-content/scenes/scenes.ts @@ -1,86 +1,41 @@ -import type { DialogKey } from "../dialogs/types"; -import type { GameSceneTransition, SceneMusicConfig } from "@pointclick-engine/engine-core"; +import type { + GameScene, + GameSceneGround, + GameSceneInteractionDialogKeys, + GameSceneInteractionFull, + GameSceneInteractionHintDialogKeys, + GameSceneWall, + GameSceneWallOpening, +} from "@pointclick-engine/engine-core"; import { + act, + branch, + cond, + otherwise, sceneTransitionOnCollision, sceneTransitionOnItemDrop, sceneTransitionOnItemInteraction, } from "@pointclick-engine/engine-core"; -export type SceneWallOpening = { - id: string; - /** Position in wall-local space relative to wall center */ - position: [number, number, number]; - /** Half-extents of the opening: [halfWidth, halfHeight, halfDepth] */ - halfSize: [number, number, number]; -}; +import { GUIDE_DIALOGUE_ID } from "../dialogues/guide"; -export type SceneWall = { - position: [number, number, number]; - /** Rotation around Y axis in radians */ - rotationY?: number; - /** Half-extents for CuboidCollider: [halfWidth, halfHeight, halfDepth] */ - halfSize: [number, number, number]; - /** Openings (doors/windows) cut into this wall */ - openings?: SceneWallOpening[]; - /** Optional texture URL for wall billboard */ - textureUrl?: string; - /** Optional texture position offset [x, y, z] */ - texturePosition?: [number, number, number]; -}; - -export type SceneInteractionDialogKeys = { - hit: DialogKey; - miss: DialogKey; -}; - -export type SceneInteractionHintDialogKeys = { - /** Dialog cuando el personaje se acerca o inspecciona el target vacío (sin ítem colocado). */ - empty: DialogKey; - /** Dialog cuando el personaje se acerca o inspecciona el target con un ítem colocado. */ - occupied: DialogKey; -}; +// Aliases de compatibilidad: los tipos de geometria/interaccion viven en el core. +export type SceneWallOpening = GameSceneWallOpening; +export type SceneWall = GameSceneWall; +export type SceneInteractionDialogKeys = GameSceneInteractionDialogKeys; +export type SceneInteractionHintDialogKeys = GameSceneInteractionHintDialogKeys; +export type SceneGround = GameSceneGround; -export type SceneInteraction = { - id: string; - kind: "drop-target"; - /** World-space center position [x, y, z] */ - position: [number, number, number]; - /** Rotation around Y axis in radians */ - rotationY?: number; - /** Half-extents for CuboidCollider: [halfWidth, halfHeight, halfDepth] */ - halfSize: [number, number, number]; - /** If true, character collides and cannot pass through this interaction */ - hasCollision?: boolean; +/** Interaccion de la demo: el tipo del core mas campos exclusivos de la demo. */ +export type DemoSceneInteraction = GameSceneInteractionFull & { /** * Suppress the default drop-target visual (cylinder + box). Use when * another renderer (e.g. SceneDoors) already shows the interactable * surface. The pick volume + drop logic remain active. */ invisible?: boolean; - /** Item ids accepted by this interaction. If omitted, any item can be accepted. */ - acceptsItemIds?: string[]; - dialogKeys: SceneInteractionDialogKeys; - /** - * Diálogos de pista por proximidad/inspección. - * Si está presente se muestran cuando el personaje se acerca mucho - * o hace click sobre el target sin arrastrar un ítem. - */ - hintDialogKeys?: SceneInteractionHintDialogKeys; - label: string; -}; - -export type SceneGround = { - /** Límite izquierdo (X negativo) */ - minX: number; - /** Límite derecho (X positivo) */ - maxX: number; - /** Límite trasero/lejano (Z negativo) */ - minZ: number; - /** Límite frontal/cercano (Z positivo) */ - maxZ: number; - /** Y position of the ground plane */ - y: number; }; +export type SceneInteraction = DemoSceneInteraction; /** * Door — interactive opening with two visual states driven by two full-wall @@ -127,21 +82,13 @@ export type SceneDoor = { showHintWhenOpen?: boolean; }; -export type Scene = { - id: string; - label: string; - background: string; - playerSpawn: [number, number, number]; - ground: SceneGround; - walls: SceneWall[]; - interactions: SceneInteraction[]; +/** Escena de la demo: el tipo del core mas `doors` y las interacciones extendidas. */ +export type DemoScene = Omit & { + interactions: DemoSceneInteraction[]; /** Optional interactive doors. */ doors?: SceneDoor[]; - /** Declarative scene transitions (collision/item-drop/item-consume). */ - transitions?: GameSceneTransition[]; - /** Optional music configuration for this scene. */ - music?: SceneMusicConfig; }; +export type Scene = DemoScene; export const SCENES: Record = { town: { @@ -162,6 +109,34 @@ export const SCENES: Record = { fadeMs: 800, }, walls: [], + // Paleton roto: esta en el suelo de la plaza (se combina con el mango que da el guia). + initialItems: [ + { + item: { + id: "key-bit-ground", + itemId: "key-bit", + interactionId: "key-bit-pickup", + name: "Paletón roto", + spriteUrl: "/assets/key/gold-key.png", + worldPosition: [1.5, -2.4, 20.0], + canPickup: true, + hasCollision: true, + collisionHalfSize: [0.5, 0.8, 0.5], + sceneId: "town", + }, + }, + ], + // El guia: reutiliza el sprite de David (personaje "guide", ver `characters/guide.ts`). + npcs: [ + { + id: "guide", + name: "guide.name", + characterId: "guide", + position: [-4.0, -2.1, 15.5], + facing: "south", + dialogueId: GUIDE_DIALOGUE_ID, + }, + ], interactions: [ { id: "town-trophy-pedestal", @@ -363,11 +338,61 @@ export const SCENES: Record = { walls: [], interactions: [], }, + // Escena de pruebas (solo desde el selector de debug): fondo "Sci Fi Level" de Jeremy Gooch + // (CC-BY 3.0) y el NPC Helix. Ver `public/assets/LICENSES-art.md`. + sciFiLab: { + id: "sciFiLab", + label: "Sci-Fi Lab", + background: "/assets/background/sciFiLab.jpg", + playerSpawn: [0, -1.1, 13.44], + ground: { + minX: -17, + maxX: 16.8, + minZ: -7.6, + maxZ: 69.7, + y: -2.05, + }, + walls: [], + npcs: [ + { + id: "helix", + name: "helix.name", + characterId: "helix", + position: [6, -1.1, 13.44], + verbs: { talk: [{ do: [{ say: "helix.hello", speaker: "helix" }] }] }, + }, + ], + interactions: [], + }, personalRoom: { id: "personalRoom", label: "Personal Room", background: "/assets/background/personalRoom.png", playerSpawn: [0, -1.1, 13.44], + // Trofeo inicial: solo si no existe ya (colocado en cualquier escena ni en el inventario). + // La escena se marca sembrada igualmente, de modo que no vuelve a aparecer. + initialItems: [ + { + when: cond.all( + cond.not(cond.itemPlaced("trophy")), + cond.not(cond.hasItem("trophy")), + ), + item: { + id: "trophy-ground", + itemId: "trophy", + interactionId: "trophy-ground-pickup", + name: "Trophy", + spriteUrl: "/assets/trophy/trophy.png", + worldPosition: [5.5, -1.3, 22.0], + canPickup: true, + hasCollision: true, + collisionHalfSize: [0.5, 0.8, 0.5], + sceneId: "personalRoom", + }, + }, + ], + // Bienvenida: en cada entrada a la habitacion (tambien al recargar), sin flag. + onEnter: [otherwise(act.say("personalRoomWelcome"))], ground: { minX: -16.9, maxX: 16.8, @@ -499,6 +524,29 @@ export const SCENES: Record = { targetSceneId: "dungeon", spawnPosition: [1.56, -2.00, 23.80], targetPosition: [2.21, -2.00, 7.52], + // No se sale a la mazmorra mientras el trofeo siga colocado en la habitacion. + when: cond.not(cond.itemPlaced("trophy", { inScene: "personalRoom" })), + blocked: [act.say("personalRoomLeaveBlocked")], + }, + ], + // Hotspot de prueba: el ordenador del escritorio (mirar, usar y soltar el gameboy encima). + hotspots: [ + { + id: "personal-room-computer", + label: "hotspot.computer.name", + position: [-10.6, 3.0, 10], + halfSize: [1.2, 1.0, 0.8], + verbs: { + look: [otherwise(act.setFlag("computer.seen"), act.say("computer.look"))], + use: [ + branch(cond.flag("computer.gameboyTried"), act.say("computer.use.after")), + otherwise(act.say("computer.use")), + ], + }, + useItem: { + gameboy: [otherwise(act.setFlag("computer.gameboyTried"), act.say("computer.gameboy"))], + }, + useItemDefault: [otherwise(act.say("computer.nothing"))], }, ], interactions: [ diff --git a/apps/web-demo/public/assets/LICENSES-art.md b/apps/web-demo/public/assets/LICENSES-art.md new file mode 100644 index 0000000..928bc6e --- /dev/null +++ b/apps/web-demo/public/assets/LICENSES-art.md @@ -0,0 +1,12 @@ +# Licencias del arte de terceros + +Arte de terceros que se sirve con la demo. Las fuentes sin modificar están en `apps/web-demo/assets-src/` (ver su `README.md`). El audio tiene su propio `audio/LICENSES.md`. + +| Archivos | Obra | Autor | Licencia | Origen | Cambios | +|---|---|---|---|---|---| +| `background/sciFiLab.jpg` | Sci Fi Level | Jeremy Gooch (jeremygooch.blogspot.com) | [CC-BY 3.0](https://creativecommons.org/licenses/by/3.0/) | https://opengameart.org/content/sci-fi-level | Capas de fondo y primer plano fundidas; recorte de 1495×841 px desde x=1880; convertido a JPEG | +| `sprites/helix/*.png` | 8 Directional 2D Point and Click Male Character | DeMoNiCaTeD | [CC-BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/) | https://opengameart.org/content/8-directional-2d-point-and-click-male-character | Frames recortados de la hoja (40×62 px por celda) y escalados ×4 sin suavizado | + +Los frames de `sprites/helix/` son una obra derivada y se distribuyen también bajo CC-BY-SA 4.0. + +Pendiente de documentar: el origen y la licencia de los demás fondos, del sprite de David y de los ítems (ver `docs/phases/phase-18-story-demo/assets.md`). diff --git a/apps/web-demo/public/assets/background/sciFiLab.jpg b/apps/web-demo/public/assets/background/sciFiLab.jpg new file mode 100644 index 0000000..c7c5312 Binary files /dev/null and b/apps/web-demo/public/assets/background/sciFiLab.jpg differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0001.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0001.png new file mode 100644 index 0000000..3a42403 Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0001.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0002.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0002.png new file mode 100644 index 0000000..57ea150 Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0002.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0003.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0003.png new file mode 100644 index 0000000..33f76c9 Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0003.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0004.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0004.png new file mode 100644 index 0000000..c48649a Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0004.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0005.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0005.png new file mode 100644 index 0000000..f3ab658 Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0005.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0006.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0006.png new file mode 100644 index 0000000..fb88929 Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0006.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0007.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0007.png new file mode 100644 index 0000000..ebc7916 Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0007.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0008.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0008.png new file mode 100644 index 0000000..eb336ff Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-east_0008.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0001.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0001.png new file mode 100644 index 0000000..358fdbd Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0001.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0002.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0002.png new file mode 100644 index 0000000..692c81d Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0002.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0003.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0003.png new file mode 100644 index 0000000..b21d959 Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0003.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0004.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0004.png new file mode 100644 index 0000000..6cf1d00 Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0004.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0005.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0005.png new file mode 100644 index 0000000..9f36ed7 Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0005.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0006.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0006.png new file mode 100644 index 0000000..10de4ab Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0006.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0007.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0007.png new file mode 100644 index 0000000..6c32af6 Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0007.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0008.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0008.png new file mode 100644 index 0000000..8002e3e Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-north_0008.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0001.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0001.png new file mode 100644 index 0000000..fe22c9c Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0001.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0002.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0002.png new file mode 100644 index 0000000..6ec3aa3 Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0002.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0003.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0003.png new file mode 100644 index 0000000..de98ddc Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0003.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0004.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0004.png new file mode 100644 index 0000000..d31f2d7 Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0004.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0005.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0005.png new file mode 100644 index 0000000..0944600 Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0005.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0006.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0006.png new file mode 100644 index 0000000..24d2c3e Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0006.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0007.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0007.png new file mode 100644 index 0000000..bc9379c Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0007.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0008.png b/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0008.png new file mode 100644 index 0000000..84bb581 Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix-walk-south_0008.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix_idle.png b/apps/web-demo/public/assets/sprites/helix/helix_idle.png new file mode 100644 index 0000000..434b68a Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix_idle.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix_idle_east.png b/apps/web-demo/public/assets/sprites/helix/helix_idle_east.png new file mode 100644 index 0000000..56508e1 Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix_idle_east.png differ diff --git a/apps/web-demo/public/assets/sprites/helix/helix_idle_north.png b/apps/web-demo/public/assets/sprites/helix/helix_idle_north.png new file mode 100644 index 0000000..73ce145 Binary files /dev/null and b/apps/web-demo/public/assets/sprites/helix/helix_idle_north.png differ diff --git a/dev.log b/dev.log deleted file mode 100644 index 3b6bec1..0000000 --- a/dev.log +++ /dev/null @@ -1,29 +0,0 @@ - -> dev -> npm run dev -w apps/web-demo - - -> @pointclick-engine/web-demo@0.1.0 dev -> next dev - -⚠ Port 3000 is in use by process 11816, using available port 3001 instead. -▲ Next.js 16.2.6 (Turbopack) -- Local: http://localhost:3001 -- Network: http://100.105.191.78:3001 -✓ Ready in 415ms -⨯ Another next dev server is already running. - -- Local: http://localhost:3000 -- PID: 11816 -- Dir: C:\COMPARTIDO\2d-game-test\2d-game-test\apps\web-demo -- Log: .next\dev\logs\next-development.log - -Run taskkill /PID 11816 /F to stop it. -[?25h -npm error Lifecycle script `dev` failed with error: -npm error code 1 -npm error path C:\COMPARTIDO\2d-game-test\2d-game-test\apps\web-demo -npm error workspace @pointclick-engine/web-demo@0.1.0 -npm error location C:\COMPARTIDO\2d-game-test\2d-game-test\apps\web-demo -npm error command failed -npm error command C:\WINDOWS\system32\cmd.exe /d /s /c next dev diff --git a/docs/LIBRARY_API_CONTRACT_V1.md b/docs/LIBRARY_API_CONTRACT_V1.md index 79fd406..c7d3e76 100644 --- a/docs/LIBRARY_API_CONTRACT_V1.md +++ b/docs/LIBRARY_API_CONTRACT_V1.md @@ -12,46 +12,48 @@ Este documento define qué superficie está soportada oficialmente para consumid ### 2.1 Engine public API -Archivo fuente: +Archivos fuente: -- `app/lib/engine/publicApi.ts` +- `packages/engine-core/src/game/runtime/` (runtime agnóstico; se re-exporta desde `packages/engine-core/src/index.ts`) +- `packages/engine-renderer-r3f/src/index.ts` (viewport, hooks y componentes R3F) +- `apps/web-demo/app/lib/engine/publicApi.ts`: barrel de compatibilidad. Re-exporta ambos paquetes con los nombres del contrato v1; ningún nombre se ha renombrado ni eliminado. -Exports soportados: +Exports soportados de `@pointclick-engine/engine-core`: - Tipos de contenido: - - `GameVec3` - - `GameSceneGround` - - `GameSceneWall` + - `GameVec3`, `GameSceneGround`, `GameSceneWall` - `GameSceneInteractionDialogKeys` - - `GameSceneInteraction` - - `GameSceneConfig` - - `GameItemDropOutcome` - - `GameItemRule` - - `GameItemConfig` - - `GameRuleConfig` - - `GameRuntimeConfig` - - `GameRuntime` - - `GameState` - - `GameActions` - - `GameRuntimeEvent` - - `GameRuntimeEventHandler` - - `GameViewportProps` -- Funciones/componentes: - - `registerScene` - - `registerItem` - - `registerRule` - - `createGameRuntime` - - `getGameState` - - `getGameActions` - - `useGameState` - - `useGameActions` - - `GameViewport` + - `GameSceneConfig` (incluye `transitions?` y `music?`) + - `GameItemDropOutcome`, `GameItemRule`, `GameItemConfig`, `GameRuleConfig` + - `GameRuntimeConfig`, `GameRuntime`, `GameState`, `GameActions` + - `GameRuntimeEvent`, `GameRuntimeEventHandler` + - `InventoryUIAdapter`, `DialogUIAdapter` +- Funciones: + - `registerScene`, `registerItem`, `registerRule` + - `createGameRuntime`, `getGameRuntime` + - `getGameState`, `getGameActions` + - `toRuntimeScene`, `createInventoryRuleContext` +- Comandos y eventos: `GameCommand`, `GameCommandType`, `GameEvent`, `GameEventType`, `GameEventHandler`. + +Exports soportados de `@pointclick-engine/engine-renderer-r3f`: + +- Tipos: `GameViewportProps`, `GameViewportViewProps`, `GameViewportController`, `GameViewportControllerOptions`, `GameViewportAudioOptions`, `CharacterDefinition`, `CharacterClip`, `CharacterDirection`. +- Componentes: `GameViewport`, `GameViewportView`, `CharacterSprite`. +- Hooks: `useGameState`, `useGameActions`, `useGameViewportController`, `useSceneRuntime`, `useTransitionSystem`, `useInventoryRuntime`, `useAudioSystem`. +- Funciones: `attachAudioSystem`. + +Notas de la superficie: + +- `GameSceneInteraction` en el barrel de la demo es un alias de `GameSceneInteractionFull` del core. En `engine-core` el nombre `GameSceneInteraction` designa la interfaz base. +- `GameActions.setScene` es `(sceneId: string) => void` (`packages/engine-core/src/game/runtime/types.ts`). +- `GameViewportProps` = opciones de `useGameViewportController` + props de `GameViewportView` + `debug` + `onRuntimeEvent`. Todas opcionales; ver [`LIBRARY_CONSUMPTION_GUIDE.md`](LIBRARY_CONSUMPTION_GUIDE.md). +- Superficie i18n (Fase 13): ver [`architecture/02-public-api.md`](architecture/02-public-api.md). ### 2.2 Platform adapters Archivo fuente: -- `app/lib/platform-web.ts` +- `apps/web-demo/app/lib/platform-web.ts` Puertos soportados: @@ -72,21 +74,49 @@ Adapters y barrel soportados: - `browserEnvironmentAdapter` - `webPlatform` +### 2.3 Novedades 0.5.0 + +Solo adiciones, salvo la nota breaking. + +- `engine-core`: runtime agnóstico (`createGameRuntime` y registros), `scene:set` con `spawnPosition?`, `player:stop` implementado, stores `useDialogStore`, `useInventoryUiStore`, `useInventoryStateStore`, `usePlacedItemsStateStore` y persistencia por puerto (`gameStatePersistence.ts`). +- `engine-renderer-r3f`: `GameViewport` jugable con valores por defecto, `useGameViewportController` + `GameViewportView`, `CharacterSprite` / `CharacterDefinition`, `attachAudioSystem`, y las props nuevas de `GameViewport` (`storage`, `canLeaveScene`, `getInitialPlacedItems`, `onSceneEnter`, `audio`, `character`, `children`, `overlay`, entre otras). +- `GameSceneConfig.transitions` y `music` se conservan al registrar la escena y al ejecutar `scene:set` (`toRuntimeScene`). +- Obsoletos (siguen exportados): `DavidSprite` y los exports de `sprite/clips.ts`. + +**Cambio breaking de comportamiento**: recoger un ítem viaja por el bus como `item:pickedUp`; antes llegaba como `item:dropped` con `outcome: "pickup-success"`. Quien detectaba recogidas por `item:dropped` debe pasar a `item:pickedUp`. El callback legacy `onRuntimeEvent` no cambia. Las reglas de audio solo reproducen el sonido de soltar con `outcome: "place"`. + +Limitaciones conocidas en 0.5.0: algunos outcomes legacy viajaban como `item:dropped` fuera del tipo; `inventory:pickup` e `inventory:drop` no tenían executor; `player:stop` no detiene el movimiento manual (sigue igual). Los dos primeros se resuelven en 0.6.0 (ver 2.4). + +### 2.4 Novedades 0.6.0 (sin publicar; los paquetes siguen en 0.5.0) + +Solo adiciones. Guía de uso: [`authoring/README.md`](authoring/README.md); modelo: [`architecture/10-narrative-model.md`](architecture/10-narrative-model.md). + +- `engine-core` (raíz): `cond`, `evaluateCondition`, `getConditionContext`, `act`, `branch`, `otherwise`, `pickBranch`, `dialogue`, `createSequencer`, `validateContent`, `resolveCombine`, `npcToHotspot`, `getAvailableVerbs`, `getDefaultVerb`, `isHotspotVisible`, `resolveInitialItems`, `resolveEnterScript`, `evaluateTransitionGate`, `getSceneRuleContext`, `getDeclaredScene`; tipos `Condition`, `Action`, `Script`, `Branch`, `ScriptRun`, `DialogueDefinition`, `DialogueNode`, `DialogueChoice`, `ContentIssue`, `GameContent`. +- Tipos de contenido: `Verb`, `GameSceneHotspot`, `GameSceneNpc`, `NpcFacing`, `SceneInitialItem`; campos nuevos opcionales `hotspots`, `npcs`, `initialItems`, `onEnter` (escena), `when` y `blocked` (transición), `combine` (ítem). +- Estado y guardado: `useWorldStateStore`, `getWorldState`, `useDialogueStore`, `useInputLockStore`, `captureSnapshot`, `applySnapshot`, `saveGame`, `loadGame`, `clearSave`, `resetGameState`, `migrateLegacySave`, `SAVE_FORMAT_VERSION`, `SAVE_STORAGE_KEY`, `GameSnapshot`. +- Puertos: `ClockPort`, `systemClock`, `HeadlessClock`. +- Subpath `@pointclick-engine/engine-core/testing`: `createPlaythrough`, `Playthrough`. +- `GameRuntime`: `runScript`, `registerHandler`, `getDialogues`. `GameRuntimeConfig`: `dialogues`, `storage`, `saveKey`, `clock`, `instantWalk`, `validate`, `dialogKeys`, `handlerNames`. `DialogUIAdapter.show` recibe `speaker?`. +- Comandos nuevos: `state:setFlag`, `state:clearFlag`, `game:save`, `game:load`, `game:reset`, `script:run`, `script:cancelAll`, `hotspot:interact`, `inventory:combine`, `dialogue:start`, `dialogue:choose`, `dialogue:advance`, `dialogue:end`. Campos opcionales nuevos: `inventory:pickup.placedItemId`, `inventory:drop.interactionId` / `hotspotId`, `dialog:trigger.speaker`. +- Eventos nuevos: `state:flagChanged`, `game:saved`, `game:loaded`, `game:reset`, `script:started`, `script:finished`, `input:lockChanged`, `custom`, `hotspot:interacted`, `hotspot:noAction`, `dialogue:started`, `dialogue:nodeEntered`, `dialogue:choiceMade`, `dialogue:ended`, `inventory:pickupFailed`, `inventory:full`, `item:removed`, `item:combined`, `item:combineFailed`. `dialog:triggered` gana `speaker?`. `item:dropped.outcome` declara ahora todos sus valores (`rule-miss`, `unknown-item`, `on-player`, y los obsoletos `pickup-blocked`, `item-interact`). +- `engine-renderer-r3f`: props nuevas de `GameViewport` / `GameViewportView`: `characters`, `verbMenu`, `noActionDialogKey`, `dialogueChoices`. Componentes y hooks: `VerbMenu`, `DialogueChoices`, `SceneHotspots`, `SceneNpcs`, `NpcSprite`, `useDialogue`, `useHotspotInteractions`, `useVisibleHotspots`, `useVisibleNpcs`, `ensureEngineTexts`, `ENGINE_VERB_LABEL_KEYS`, `ENGINE_NO_ACTION_KEY`. +- Vía avanzada (siguen soportados, se evalúan después de las reglas declarativas): `canLeaveScene`, `onSceneEnter`, `getInitialPlacedItems`. + ## 3. No soportado para consumidores externos No se garantiza estabilidad en: -- `app/lib/engine/runtime/*` -- `app/lib/engine/render/*` -- `app/lib/engine/movement/*` -- `app/components/*` -- `app/store/*` +- `apps/web-demo/app/lib/engine/runtime/*` (incluye `useDoorSystem.ts`: las puertas son de la demo) +- `apps/web-demo/app/components/*` +- `apps/web-demo/app/store/*` +- `packages/engine-core/src/game/runtime/executors.ts` y `registry.ts` (internos; los registros son globales de módulo) +- Cualquier símbolo de los paquetes no listado en 2.1 o 2.3. Estos módulos pueden cambiar internamente sin política de compatibilidad para integradores. ## 4. Reglas de consumo -1. Consumir runtime desde `publicApi`. +1. Consumir el runtime desde `@pointclick-engine/engine-core` y el viewport desde `@pointclick-engine/engine-renderer-r3f` (o desde el barrel `publicApi`). 2. Consumir interoperabilidad desde `platform-web`. 3. No depender de comportamiento implícito de stores internos. 4. Tratar tipos/eventos públicos como contrato de integración. @@ -117,9 +147,10 @@ Cambios breaking (requieren plan de migración): ## 7. Validación mínima para PRs que toquen contrato 1. Actualizar este documento si cambia la superficie pública. -2. Mantener tests de contrato de `publicApi` en verde. +2. Mantener tests de contrato de `publicApi` en verde (`apps/web-demo/app/lib/engine/publicApi.test.ts`). 3. Mantener tests de `platform-web` en verde. 4. Ejecutar y validar: - `npm run lint` - `npm run test` - `npm run build` +5. Con la demo en marcha: `npm run smoke` (`e2e/smoke.mjs` y `e2e/smoke-minimal.mjs`). diff --git a/docs/LIBRARY_CONSUMPTION_GUIDE.md b/docs/LIBRARY_CONSUMPTION_GUIDE.md index 012e730..bdf30c5 100644 --- a/docs/LIBRARY_CONSUMPTION_GUIDE.md +++ b/docs/LIBRARY_CONSUMPTION_GUIDE.md @@ -1,173 +1,200 @@ # Library Consumption Guide -Guía para integrar el Point & Click Game Engine en una aplicación host. +Guía para integrar el Point & Click Game Engine en una aplicación host (paquetes 0.5.0; las novedades 0.6.0, sin publicar, se marcan como tales). Ejemplo verificable: `apps/web-demo/app/example-minimal/page.tsx`. Para escribir escenas, puzzles y diálogos: [`authoring/README.md`](authoring/README.md). -**Estado**: v2 (post Phase 4 + Phase 5) | **Última revisión**: 2026-05-27 - ---- - -## 1. Packages disponibles +## 1. Paquetes ```bash -npm install @pointclick-engine/engine-core -npm install @pointclick-engine/engine-renderer-r3f # + peer deps (ver README del package) +npm install @pointclick-engine/engine-core @pointclick-engine/engine-renderer-r3f +# + peer deps del renderer (ver packages/engine-renderer-r3f/README.md) ``` -| Package | Responsabilidad | +| Paquete | Responsabilidad | |---------|----------------| -| `@pointclick-engine/engine-core` | Estado, reglas, pathfinding, ports. Cero React, cero browser globals. | -| `@pointclick-engine/engine-renderer-r3f` | Renderer React Three Fiber. `GameViewport`, `createGameRuntime`, sprites, scene primitives. | +| `@pointclick-engine/engine-core` | Runtime agnóstico (`createGameRuntime`, registros, comandos/eventos), stores, reglas, pathfinding, puertos. Cero React. | +| `@pointclick-engine/engine-renderer-r3f` | `GameViewport` jugable, hooks de estado, sprites y escena R3F. Depende del core. | ---- +El runtime vive en `packages/engine-core/src/game/runtime/`. Contrato exacto de exports: [`LIBRARY_API_CONTRACT_V1.md`](LIBRARY_API_CONTRACT_V1.md). ## 2. Flujo canónico -### Paso 1: Crear el runtime +Resumen de `apps/web-demo/app/example-minimal/page.tsx` (importa solo de los paquetes): crear el runtime una vez, y montar `GameViewport` cuando exista. ```tsx "use client"; -import { useEffect } from "react"; -import { createGameRuntime, GameViewport } from "@pointclick-engine/engine-renderer-r3f"; - -const myScenes = [ - { - id: "town", - label: "Town", - background: "/assets/bg/town.jpg", - playerSpawn: [0, 0, 10], - ground: { minX: -15, maxX: 15, minZ: -10, maxZ: 30, y: -3 }, - walls: [], - interactions: [], - }, -]; - -export default function GamePage() { + +import { useEffect, useState } from "react"; +import { + createGameRuntime, + sceneTransitionOnCollision, + type GameItemConfig, + type GameRuntime, + type GameSceneConfig, +} from "@pointclick-engine/engine-core"; +import { GameViewport } from "@pointclick-engine/engine-renderer-r3f"; + +const SCENE_A: GameSceneConfig = { + id: "minimal-a", + label: "Minimal Scene A", + background: "/assets/background/town.jpg", + playerSpawn: [3.08, 1.05, 13.44], + ground: { minX: -12, maxX: 17, minZ: -15, maxZ: 30, y: -3.25 }, + walls: [], interactions: [], + // Ítem inicial declarado en la propia escena (sin callback del host). + initialItems: [ + { + item: { + id: "trophy-in-scene-a", itemId: "trophy", interactionId: "trophy-pickup-zone", + name: "Trophy", spriteUrl: "/assets/trophy/trophy.png", + worldPosition: [6.5, -2.4, 13.4], canPickup: true, + }, + }, + ], + transitions: [ + sceneTransitionOnCollision({ + id: "transition-a-to-b", + targetSceneId: "minimal-b", + position: [2, -1, -12], halfSize: [6, 4, 2], + spawnPosition: [0, -1.1, 20], targetPosition: [0, -1.1, 10], + }), + ], +}; + +// Resumida: el ejemplo real añade la transición de vuelta B -> A. +const SCENE_B: GameSceneConfig = { + id: "minimal-b", label: "Minimal Scene B", background: "/assets/background/mazmorra.jpg", + playerSpawn: [0, -1.1, 13.44], + ground: { minX: -14.4, maxX: 15.8, minZ: -20.6, maxZ: 60.6, y: -3.15 }, + walls: [], interactions: [], +}; + +const TROPHY_ITEM: GameItemConfig = { + id: "trophy", name: "Trophy", spriteUrl: "/assets/trophy/trophy.png", + interactionRules: {}, defaultRule: { outcome: "return" }, +}; + +export default function MinimalGame() { + const [runtime, setRuntime] = useState(null); useEffect(() => { - const runtime = createGameRuntime({ - scenes: myScenes, - }); - return () => runtime.dispose(); + const created = createGameRuntime({ scenes: [SCENE_A, SCENE_B], items: [TROPHY_ITEM] }); + setRuntime(created); + return () => { + created.dispose(); + setRuntime(null); + }; }, []); - return ; + if (!runtime) return null; + return ; } ``` -### Paso 2: Comunicación bidireccional (host → juego) +Con estos valores por defecto el juego es jugable: personaje incluido, inventario, recogida/colocación de ítems y transiciones. Sin `storage` no persiste la escena; sin `audio` no suena. -Desde cualquier componente HTML (fuera del Canvas), envía comandos al runtime: +## 3. Opciones de `GameViewport` -```ts -import { getGameRuntime } from "@pointclick-engine/engine-renderer-r3f"; +`GameViewportProps` = opciones de `useGameViewportController` + props de `GameViewportView` + `debug` y `onRuntimeEvent`. Todas son opcionales. -const runtime = getGameRuntime(); +| Para... | Opciones | +|---------|----------| +| **Escena inicial y persistencia** | `initialSceneId` (escena si no hay guardada), `storage` (`SceneProgressStorage`: `loadSceneId`/`saveSceneId`), `startPersistence` (arranca el guardado de inventario e ítems; devuelve su limpieza), `resolveScene` (por defecto, el registro del runtime) | +| **Reglas del juego** | `getPhrase(key)`, `itemContext`, `filterPlacedItems`, `canPickupItems`. Vía avanzada (0.6.0 prefiere los datos de escena, ver sección 5b): `canLeaveScene` (`true` deja salir; `{ text, dialogKey? }` bloquea), `getInitialPlacedItems(sceneId, allItems)` (array = siembra; `null` = no marca la escena como sembrada), `onSceneEnter(sceneId, { showDialog })` | +| **Narrativa (0.6.0)** | `characters` (`Record` para los `characterId` de los NPC), `verbMenu` (sustituye `VerbMenu`), `dialogueChoices` (sustituye `DialogueChoices`), `noActionDialogKey` (frase de `hotspot:noAction`) | +| **Audio** | `audio`: `{ port, defaults, items, transitions, settingsStore, scenes? }`. Sin `audio` no hay sonido. Los sonidos se declaran en datos (`pickupSoundUrl`/`dropSoundUrl` del ítem, `music` de la escena). Solo `outcome: "place"` reproduce el sonido de soltar | +| **Personaje** | `character: CharacterDefinition` (por defecto, el incluido), `spriteRuntimeProps` | +| **Extensión** | `children` (dentro de ``, p. ej. puertas), `canvasChildren` (en el Canvas, fuera de ``), `overlay` (HTML sobre el canvas), `cameraMode` (`"fixed"` por defecto), `onSceneReady` | +| **Observación** | `runtime` (por defecto, `getGameRuntime()`), `onRuntimeEvent` (callback legacy), `debug` | -// Cambiar escena -runtime?.executeCommand({ type: "scene:set", sceneId: "dungeon" }); +## 4. `useGameViewportController` + `GameViewportView` -// Mostrar diálogo -runtime?.executeCommand({ type: "dialog:trigger", dialogKey: "welcomeMessage" }); +`GameViewport` es la composición de ambos. Úsalos por separado cuando tu UI necesita datos del controlador (escena actual, estado del diálogo, inventario) fuera del Canvas: -// Abrir/cerrar inventario -runtime?.executeCommand({ type: "inventory:toggle" }); +```tsx +import { + GameViewportView, + useGameViewportController, +} from "@pointclick-engine/engine-renderer-r3f"; + +function Game() { + const controller = useGameViewportController({ initialSceneId: "minimal-a" }); + return {controller.sceneId}

} />; +} ``` -### Paso 3: Escuchar eventos del juego (juego → host) +## 5. Comandos y eventos ```ts -const unsub = runtime?.on("scene:changed", (ev) => { - console.log("Entered scene:", ev.sceneId); -}); +import { getGameRuntime } from "@pointclick-engine/engine-core"; -// También: "player:moved", "dialog:triggered", "dialog:dismissed" +const runtime = getGameRuntime(); // null antes de createGameRuntime o tras dispose() -// Limpiar al desmontar: +runtime?.executeCommand({ type: "scene:set", sceneId: "minimal-b", spawnPosition: [0, -1.1, 20] }); +runtime?.executeCommand({ type: "dialog:trigger", dialogKey: "welcomeMessage" }); +runtime?.executeCommand({ type: "inventory:toggle" }); + +const unsub = runtime?.on("item:pickedUp", (ev) => console.log(ev.itemId)); unsub?.(); ``` -### Paso 4: Leer estado React desde la UI +- `scene:set` acepta `spawnPosition?`; `transition:activate` respeta el `spawnPosition` de la transición. +- `player:stop` aborta una caminata por ruta (emite `player:walkAborted`); **no** detiene el movimiento manual por teclado/joystick. +- Texto de diálogos: `registerRule({ key, phrases })` (o `rules` en `createGameRuntime`) o un `dialogAdapter` propio que traduzca la clave. Sin ninguno, `dialog:trigger` muestra la propia clave. +- Catálogo completo de comandos y eventos: [`architecture/05-bidirectional-communication.md`](architecture/05-bidirectional-communication.md). + +## 5b. Narrativa declarativa (0.6.0, sin publicar) + +Escenas con `hotspots`, `npcs`, `initialItems` y `onEnter`, transiciones con `when`/`blocked`, ítems con `combine` y árboles de diálogo (`dialogues` en la config) son datos: ver [`authoring/`](authoring/README.md) y [`architecture/10-narrative-model.md`](architecture/10-narrative-model.md). + +- Comandos nuevos: `hotspot:interact`, `inventory:combine`, `dialogue:start|choose|advance|end`, `script:run`, `script:cancelAll`, `state:setFlag|clearFlag`, `game:save|load|reset`. Eventos: `hotspot:interacted|noAction`, `dialogue:*`, `item:combined|combineFailed`, `script:started|finished`, `state:flagChanged`, `game:saved|loaded|reset`. Lista en [`LIBRARY_API_CONTRACT_V1.md`](LIBRARY_API_CONTRACT_V1.md) (2.4). +- Guardado: `storage` (y `saveKey`) en `createGameRuntime` activan `game:save` / `game:load`. Una partida de 0.5.0 se migra con `migrateLegacySave`. +- `call` en un guion invoca lo que registres con `runtime.registerHandler(name, fn)`. `validate` en la config valida el contenido (solo en desarrollo por defecto); `dialogKeys` y `handlerNames` amplían la comprobación. +- Si sobrescribes `resolveScene` con tus propias escenas, proyecta tú los NPC con `npcToHotspot` (`toRuntimeScene` lo hace solo para el registro). +- Tests sin renderer: `createPlaythrough` de `@pointclick-engine/engine-core/testing`. Los outcomes `pickup-blocked` e `item-interact` de `item:dropped` son obsoletos. + +## 6. Leer estado desde la UI ```tsx -import { useGameState, useGameActions } from "@pointclick-engine/engine-renderer-r3f"; +import { useGameActions, useGameState } from "@pointclick-engine/engine-renderer-r3f"; export function SceneSwitcher() { const sceneId = useGameState((s) => s.sceneId); - const { setScene, requestRespawn } = useGameActions(); - + const { setScene } = useGameActions(); return ( -
-

Escena: {sceneId}

- - -
+ ); } ``` ---- - -## 3. Subpath exports de `engine-core` - -Para trees-haking granular, importa solo el módulo que necesitas: - -```ts -import type { GameCommand } from "@pointclick-engine/engine-core/commands"; -import type { GameEvent } from "@pointclick-engine/engine-core/events"; -import type { IGameLoopPort } from "@pointclick-engine/engine-core/ports"; -import type { GameVec3 } from "@pointclick-engine/engine-core/types"; -import { useSceneStore } from "@pointclick-engine/engine-core/state"; -``` - ---- - -## 4. Registrar diálogos personalizados - -```ts -import { registerRule } from "@pointclick-engine/engine-renderer-r3f"; - -registerRule({ key: "welcomeMessage", phrases: ["¡Bienvenido al pueblo!", "¿Primera vez por aquí?"] }); -registerRule({ key: "boundaryHit", phrases: ["¡Hay una pared ahí!"] }); -``` - ---- - -## 5. Consideraciones SSR - -- `GameViewport` lleva `"use client"` — no renderiza en servidor. -- `createGameRuntime` inicializa el store; hacerlo en `useEffect` para evitar hidratación conflictiva. -- `getGameRuntime()` devuelve `null` antes de que el runtime se cree (útil para verificar antes de llamar). - ---- +`GameState` = `sceneId`, `scene`, `playerPosition`, `respawnSignal`. `GameActions` también trae `setPlayerPosition` y `requestRespawn`. `GameActions.setScene` es `(sceneId: string) => void`. -## 6. Errores comunes +Stores reactivos del core (selector de zustand): `useSceneStore`, `useInventoryStateStore` (`slots`), `usePlacedItemsStateStore` (`items`), `useDialogStore`, `useInventoryUiStore` y, en 0.6.0, `useWorldStateStore` (`flags`, `visitedSceneIds`) y `useDialogueStore`. La persistencia va por puerto (`KeyValueStoragePort`). -| ❌ Hacer | ✅ En su lugar | -|----------|--------------| -| Importar módulos internos de `app/lib/engine/runtime/` directamente | Importar desde `@pointclick-engine/engine-renderer-r3f` | -| Usar `window.document` en lógica de juego | Pasar por ports / platform adapters | -| Mutar `useSceneStore` directamente desde la UI | Usar `useGameActions()` o `executeCommand()` | -| Crear el runtime varias veces | Un solo `createGameRuntime()` por instancia de juego | +## 7. SSR ---- +- `GameViewport` y los hooks del renderer llevan `"use client"`: no renderizan en servidor. +- Crea el runtime en `useEffect` y monta el viewport cuando exista (como en el flujo canónico). -## 7. Criterio de breaking change +## 8. Limitaciones conocidas -**Compatible** (no requiere migración): -- Nuevas funciones en la API pública sin cambiar firmas existentes. -- Nuevos campos opcionales en tipos públicos. -- Nuevos subpath exports. +- `inventory:pickup` e `inventory:drop` tienen executor en 0.6.0 (solo cambian estado y emiten eventos; los textos los muestra el viewport). +- El renderer no trae UI para combinar ítems: el host lanza `inventory:combine` (la demo lo hace en `GameTouchCanvas.tsx`). +- Las puertas son de la demo (`apps/web-demo/app/lib/engine/runtime/useDoorSystem.ts`), no del motor. +- Los registros de escenas, ítems y reglas son globales de módulo: un solo juego por página. -**Breaking** (requiere issue + guía de migración): -- Renombrar o eliminar exports públicos. -- Cambiar la semántica de commands/events. -- Cambiar la forma de `GameViewport` props. +## 9. Errores comunes ---- +| No hacer | En su lugar | +|----------|-------------| +| Importar `createGameRuntime` o `registerRule` de `engine-renderer-r3f` | Importar del core: `@pointclick-engine/engine-core` | +| Escuchar `item:dropped` para detectar recogidas | Escuchar `item:pickedUp` | +| Montar `GameViewport` antes de crear el runtime | Esperar al runtime (estado + `useEffect`) | +| Crear el runtime varias veces | Un `createGameRuntime()` por juego; `dispose()` al desmontar | +| Esperar que `player:stop` frene el teclado | Solo detiene caminatas por ruta | -## 8. Ver también +## 10. Ver también -- [`architecture/05-bidirectional-communication.md`](architecture/05-bidirectional-communication.md) — Protocolo completo de commands & events -- [`architecture/06-renderer-implementation-guide.md`](architecture/06-renderer-implementation-guide.md) — Escribir un renderer alternativo -- [`architecture/02-public-api.md`](architecture/02-public-api.md) — Contrato estable de `publicApi` -- `packages/engine-core/README.md` — Quickstart engine-core aislado -- `packages/engine-renderer-r3f/README.md` — Quickstart renderer R3F +- [`LIBRARY_API_CONTRACT_V1.md`](LIBRARY_API_CONTRACT_V1.md) — Superficie soportada y novedades 0.5.0 y 0.6.0 +- [`architecture/02-public-api.md`](architecture/02-public-api.md) — Resumen de la API pública +- [`architecture/05-bidirectional-communication.md`](architecture/05-bidirectional-communication.md) — Commands & Events diff --git a/docs/README.md b/docs/README.md index 4751838..d9bdcf5 100644 --- a/docs/README.md +++ b/docs/README.md @@ -9,12 +9,28 @@ Diseño del sistema. Lee antes de tocar arquitectura. - [`architecture/01-layers.md`](architecture/01-layers.md) — Las 4 capas y su responsabilidad -- [`architecture/02-public-api.md`](architecture/02-public-api.md) — Contrato de `publicApi.ts` (estable v1) +- [`architecture/02-public-api.md`](architecture/02-public-api.md) — API pública (contrato v1; `publicApi.ts` es barrel de los paquetes) - [`architecture/03-rules-core-vs-render.md`](architecture/03-rules-core-vs-render.md) — Decisión: ¿este código va en core o renderer? - [`architecture/04-platform-ports.md`](architecture/04-platform-ports.md) — Adapters web (storage, clipboard, timer) - [`architecture/05-bidirectional-communication.md`](architecture/05-bidirectional-communication.md) — Commands & Events API (web ↔ juego) - [`architecture/06-renderer-implementation-guide.md`](architecture/06-renderer-implementation-guide.md) — Cómo escribir un renderer alternativo +- [`architecture/07-walls-with-openings.md`](architecture/07-walls-with-openings.md) — Walls with openings: pathfinding & rendering +- [`architecture/08-scene-transitions.md`](architecture/08-scene-transitions.md) — Scene transitions as first-class primitives - [`architecture/09-multiplayer.md`](architecture/09-multiplayer.md) — Multijugador agnóstico (port + partición world/presence/private) +- [`architecture/10-narrative-model.md`](architecture/10-narrative-model.md) — Modelo narrativo: estado de mundo → condiciones → ramas → secuenciador → comandos y eventos (0.6.0) + +--- + +## ✍️ Authoring (guía para escribir una aventura) + +Escenas, puzzles y diálogos como datos. Empieza por el índice y sigue el orden. + +- [`authoring/README.md`](authoring/README.md) — Índice, ejemplos ejecutables y textos (`say`) +- [`authoring/01-scenes-and-hotspots.md`](authoring/01-scenes-and-hotspots.md) — Escenas, transiciones, hotspots y verbos +- [`authoring/02-conditions-and-actions.md`](authoring/02-conditions-and-actions.md) — Flags, condiciones, acciones, ramas y `call` +- [`authoring/03-dialogues-and-npcs.md`](authoring/03-dialogues-and-npcs.md) — Diálogos con opciones y NPCs +- [`authoring/04-items-and-combining.md`](authoring/04-items-and-combining.md) — Ítems, reglas de drop y combinaciones +- [`authoring/05-saving-and-testing.md`](authoring/05-saving-and-testing.md) — Guardado, validación y `createPlaythrough` --- @@ -27,6 +43,7 @@ Cómo trabajar en este repo. - [`workflow/how-to-spawn-subagent.md`](workflow/how-to-spawn-subagent.md) — Delegar tareas autocontenidas - [`workflow/pre-commit-checklist.md`](workflow/pre-commit-checklist.md) — Validación antes de commit - [`workflow/commit-convention.md`](workflow/commit-convention.md) — Formato de commits +- Smoke headless: `npm run smoke` (`e2e/smoke.mjs` + `e2e/smoke-minimal.mjs`; requiere la demo en marcha) --- @@ -39,10 +56,18 @@ Trabajo actual y futuro. Una fase = un directorio con tareas modulares. - [`phases/phase-4-bidirectional-web-game/`](phases/phase-4-bidirectional-web-game/) — ✅ Completed: Comunicación web ↔ juego - [`phases/phase-5-publish/`](phases/phase-5-publish/) — ✅ Completed: Publicación en npm (v0.1.0 publishable) - [`phases/phase-6-walls-with-openings/`](phases/phase-6-walls-with-openings/) — ✅ Completed: Walls with openings & pathfinding -- [`phases/phase-7-walls-first-class/`](phases/phase-7-walls-first-class/) — ✅ Completed: Walls as first-class scene elements +- [`phases/phase-7-walls-first-class/`](phases/phase-7-walls-first-class/) — 📋 Planned (not started) - [`phases/phase-8-scene-transitions/`](phases/phase-8-scene-transitions/) — ✅ Completed: Scene transitions (collision + item-drop) - [`phases/phase-9-placed-items-agnóstic/`](phases/phase-9-placed-items-agnóstic/) — ✅ Phases A-C: Placed items refactoring to core (types, dialog keys, stores) +- [`phases/phase-10-scene-entry-positions-and-pathwalking/`](phases/phase-10-scene-entry-positions-and-pathwalking/) — ✅ Completed: Player spawn positions and pathwalking +- [`phases/phase-11-audio/`](phases/phase-11-audio/) — ✅ Completed: Audio system (música + SFX + mute) +- [`phases/phase-12-architecture-cleanup/`](phases/phase-12-architecture-cleanup/) — ✅ Completed: Core agnosticism & library boundaries +- [`phases/phase-13-i18n/`](phases/phase-13-i18n/) — ✅ Completed: Localization system (i18n) - [`phases/phase-14-multiplayer/`](phases/phase-14-multiplayer/) — 📋 Planning: Multijugador en tiempo real, agnóstico de transporte +- [`phases/phase-15-green-baseline/`](phases/phase-15-green-baseline/) — ✅ Completed: Base verde (tests, tipos, lint, CI) y docs resincronizadas +- [`phases/phase-16-runtime-in-library/`](phases/phase-16-runtime-in-library/) — ✅ Completed: Runtime en los paquetes (core + renderer); la demo es consumidora (0.5.0) +- [`phases/phase-17-narrative-primitives/`](phases/phase-17-narrative-primitives/) — ✅ Completed: Flags, condiciones, acciones, hotspots con verbos, NPCs, diálogos con opciones, guardado único (0.6.0) +- [`phases/phase-18-story-demo/`](phases/phase-18-story-demo/) — 📋 Next: Aventura corta con historia, de principio a fin --- @@ -72,6 +97,12 @@ Decisiones arquitectónicas registradas. - [`decisions/0002-useframe-for-loop.md`](decisions/0002-useframe-for-loop.md) - [`decisions/0003-monorepo-with-demo.md`](decisions/0003-monorepo-with-demo.md) - [`decisions/0004-modular-docs-strategy.md`](decisions/0004-modular-docs-strategy.md) +- [`decisions/0005-renderer-ports-design.md`](decisions/0005-renderer-ports-design.md) +- [`decisions/0006-command-event-architecture.md`](decisions/0006-command-event-architecture.md) +- [`decisions/0007-release-strategy.md`](decisions/0007-release-strategy.md) +- [`decisions/0008-multiplayer-architecture.md`](decisions/0008-multiplayer-architecture.md) +- [`decisions/0009-runtime-lives-in-packages.md`](decisions/0009-runtime-lives-in-packages.md) +- [`decisions/0010-declarative-narrative-model.md`](decisions/0010-declarative-narrative-model.md) --- @@ -80,6 +111,7 @@ Decisiones arquitectónicas registradas. - [`ROADMAP_FRAMEWORK_AGNOSTIC_REFACTORING.md`](ROADMAP_FRAMEWORK_AGNOSTIC_REFACTORING.md) — Plan high-level de 5 fases - [`LIBRARY_API_CONTRACT_V1.md`](LIBRARY_API_CONTRACT_V1.md) — Contrato v1 de API pública - [`LIBRARY_CONSUMPTION_GUIDE.md`](LIBRARY_CONSUMPTION_GUIDE.md) — Cómo consumir la librería +- [`authoring/README.md`](authoring/README.md) — Cómo escribir escenas, puzzles y diálogos - [`_archive/`](_archive/) — Documentos reemplazados (referencia histórica) --- diff --git a/docs/DEBUG_MODE_REVIEW.md b/docs/_archive/DEBUG_MODE_REVIEW.md similarity index 100% rename from docs/DEBUG_MODE_REVIEW.md rename to docs/_archive/DEBUG_MODE_REVIEW.md diff --git a/FEATURE_WALLS_OPENINGS_VISUAL_GUIDE.md b/docs/_archive/FEATURE_WALLS_OPENINGS_VISUAL_GUIDE.md similarity index 100% rename from FEATURE_WALLS_OPENINGS_VISUAL_GUIDE.md rename to docs/_archive/FEATURE_WALLS_OPENINGS_VISUAL_GUIDE.md diff --git a/PHASE_6_EXECUTIVE_SUMMARY.md b/docs/_archive/PHASE_6_EXECUTIVE_SUMMARY.md similarity index 100% rename from PHASE_6_EXECUTIVE_SUMMARY.md rename to docs/_archive/PHASE_6_EXECUTIVE_SUMMARY.md diff --git a/TODAY_DELIVERABLES.md b/docs/_archive/TODAY_DELIVERABLES.md similarity index 100% rename from TODAY_DELIVERABLES.md rename to docs/_archive/TODAY_DELIVERABLES.md diff --git a/docs/architecture/01-layers.md b/docs/architecture/01-layers.md index 08d475a..9e66305 100644 --- a/docs/architecture/01-layers.md +++ b/docs/architecture/01-layers.md @@ -12,16 +12,19 @@ ↕ props / callbacks ┌────────────────────┴────────────────────────────────────┐ │ 2. Renderer R3F │ -│ apps/web-demo/app/lib/engine/runtime/, render/ │ -│ - GameTouchCanvas, useFrame loops │ +│ packages/engine-renderer-r3f/src/ │ +│ - GameViewport (composición jugable), hooks de │ +│ escena/transiciones/inventario/audio, sprites │ │ - Renderizado 3D (Three.js, Rapier) │ │ - Sería diferente con otro renderer │ └────────────────────┬────────────────────────────────────┘ ↕ events / state subscriptions ┌────────────────────┴────────────────────────────────────┐ │ 3. Core (AGNÓSTICO) │ -│ packages/engine-core/ (Fase 2+) │ -│ - Zustand stores, rules, pathfinding │ +│ packages/engine-core/src/ │ +│ - Runtime (game/runtime/): createGameRuntime, │ +│ registros, executors de comandos │ +│ - Zustand stores, rules, pathfinding, puertos │ │ - Sin React, sin R3F, sin Next.js │ │ - Testeable sin mocks de framework │ └────────────────────┬────────────────────────────────────┘ @@ -44,6 +47,17 @@ | Core | Solo types y puertos | React, R3F, navegador | | Platform | API del navegador + puertos | Lógica de juego | +## Qué queda en la demo (`apps/web-demo`) + +Tras la Fase 16 el runtime ya no vive en la demo. La demo es **consumidora y punto de composición**: + +- `app/lib/engine/publicApi.ts`: barrel de re-export del contrato v1 (ver [`02-public-api.md`](02-public-api.md)). +- `demo-content/`: escenas, ítems, diálogos y personaje de la demo. +- `app/components/` y `app/store/`: UI propia (inventario, joystick, paneles de depuración, editores) y puertas (`SceneDoors.tsx`, `useDoorSystem.ts`). +- `app/lib/engine/runtime/`: opciones de la demo para `useGameViewportController` (`demoViewportOptions.ts`, `demoSceneRules.ts`) y hooks de depuración/editores. +- `app/lib/platform-web.ts`, `platform-web-audio.ts`, `platform-web-i18n.ts`, `gamePersistence.ts`: adapters web. +- `app/example-minimal/page.tsx`: juego que importa solo de los paquetes. + ## Flujo de datos **Entrada usuario** → Presentación → Renderer → Core (state update) @@ -51,7 +65,7 @@ ## Verificación -Test rápido: si borras `react` de `package.json` de `engine-core/`, debe seguir compilando. +Test rápido: si borras `react` de `package.json` de `engine-core/`, debe seguir compilando. Además, `packages/engine-core/src/__tests__/` incluye un test de agnosticismo del core. ## Ver también diff --git a/docs/architecture/02-public-api.md b/docs/architecture/02-public-api.md index a8107f8..add3c26 100644 --- a/docs/architecture/02-public-api.md +++ b/docs/architecture/02-public-api.md @@ -1,82 +1,27 @@ -# API Pública (`publicApi.ts`) +# API Pública -**Ubicación actual**: `app/lib/engine/publicApi.ts` -**Ubicación post-Fase 2**: `packages/engine-core/src/index.ts` (parte agnóstica) + `apps/web-demo/.../publicApi.ts` (parte R3F) +**Ubicación**: el runtime agnóstico vive en `packages/engine-core/src/game/runtime/` y el viewport/hooks R3F en `packages/engine-renderer-r3f/src/index.ts`. `apps/web-demo/app/lib/engine/publicApi.ts` es un **barrel de compatibilidad** que re-exporta ambos con los nombres del contrato v1. ## Contrato Estable (v1) -Estos exports **NO se rompen sin issue + migración + bump semver**. +Estos exports **NO se rompen sin issue + migración + bump semver**. La lista completa y separada por paquete está en [`../LIBRARY_API_CONTRACT_V1.md`](../LIBRARY_API_CONTRACT_V1.md) (fuente única; no se duplica aquí). -### Tipos +Resumen: -```ts -GameVec3 -GameSceneGround, GameSceneWall, GameSceneConfig -GameSceneInteraction, GameSceneInteractionDialogKeys -GameItemDropOutcome, GameItemRule, GameItemConfig -GameRuleConfig -GameRuntimeConfig, GameRuntime -GameState, GameActions -GameRuntimeEvent, GameRuntimeEventHandler -GameViewportProps -``` - -### Funciones / Componentes - -```ts -createGameRuntime(config?: GameRuntimeConfig): GameRuntime -registerScene(config: GameSceneConfig): void -registerItem(config: GameItemConfig): void -registerRule(config: GameRuleConfig): void -getGameState(): GameState -getGameActions(): GameActions -useGameState(selector: (s: GameState) => T): T -useGameActions(): GameActions -GameViewport(props: GameViewportProps): ReactNode -``` - -### i18n (v0.4.0+, Phase 13) +| Paquete | Contenido | +|---------|-----------| +| `@pointclick-engine/engine-core` | `createGameRuntime`, `getGameRuntime`, `registerScene/Item/Rule`, `getGameState`, `getGameActions`, tipos `Game*Config`, `GameRuntime`, `GameState`, `GameActions`, `GameCommand`, `GameEvent` | +| `@pointclick-engine/engine-renderer-r3f` | `GameViewport`, `GameViewportView`, `useGameViewportController`, `useGameState`, `useGameActions`, `CharacterSprite`, `attachAudioSystem` | -Tipos: +Cómo se usa, paso a paso: [`../LIBRARY_CONSUMPTION_GUIDE.md`](../LIBRARY_CONSUMPTION_GUIDE.md). -```ts -Locale, DialogEntry, DialogDictionary, LocaleDictionaries -I18nConfig, I18nState, I18nPort, I18nStore -UseI18nResult, UseLocaleDetectionOptions -LocaleSwitcherProps, LocaleSwitcherRenderOption, I18nProviderProps -``` +## i18n (v0.4.0+, Phase 13) -Funciones / componentes: +Core (`@pointclick-engine/engine-core`): `registerDictionary`, `registerDictionaries`, `getDictionary`, `translate`, `getRandomPhrase`, `matchLocale`, `createI18nStore`, `getI18nStore`, `resetI18nStore`, `subscribeI18n`, `setI18nStoreEmitter`, `HeadlessI18nAdapter`, `registerI18nExecutors`; tipos `Locale`, `DialogEntry`, `DialogDictionary`, `LocaleDictionaries`, `I18nConfig`, `I18nState`, `I18nPort`, `I18nStore`. -```ts -// Core -registerDictionary(locale, dict): void -registerDictionaries(all): void -getDictionary(locale): DialogDictionary | undefined -translate(key, opts?): string -getRandomPhrase(key, opts?): string -matchLocale(candidate, available): Locale | null -createI18nStore(config): I18nStore -getI18nStore(): I18nStore -resetI18nStore(config?): void -subscribeI18n(listener): () => void -setI18nStoreEmitter(emitter): void -HeadlessI18nAdapter // class implements I18nPort -registerI18nExecutors(handler, emit?): () => void - -// R3F -useI18n(): UseI18nResult -useLocaleDetection({ port, config? }): void -... - -``` +Renderer (`@pointclick-engine/engine-renderer-r3f`): `useI18n`, `useLocaleDetection`, `I18nProvider`, `LocaleSwitcher`; tipos `UseI18nResult`, `UseLocaleDetectionOptions`, `LocaleSwitcherProps`, `LocaleSwitcherRenderOption`, `I18nProviderProps`. -Adapter web (no es parte del package; vive en `apps/web-demo/app/lib/`): - -```ts -createWebI18nAdapter({ availableLocales, storageKey? }): WebI18nAdapter -bindI18nPersistence(store, port): () => void -``` +Adapter web (no es parte de los paquetes; vive en `apps/web-demo/app/lib/platform-web-i18n.ts`): `createWebI18nAdapter`, `bindI18nPersistence`. Recetas Next.js: ver [`../integrations/nextjs-i18n.md`](../integrations/nextjs-i18n.md). @@ -90,7 +35,7 @@ Recetas Next.js: ver [`../integrations/nextjs-i18n.md`](../integrations/nextjs-i - ❌ Renombrar / remover exports - ❌ Cambiar firmas (parámetros, return) -- ❌ Cambiar semántica de eventos / acciones +- ❌ Cambiar semántica de eventos / acciones (p. ej. 0.5.0: recoger un ítem pasó de `item:dropped` con `outcome: "pickup-success"` a `item:pickedUp`) ## Si necesitas cambiar la API pública @@ -101,13 +46,13 @@ Recetas Next.js: ver [`../integrations/nextjs-i18n.md`](../integrations/nextjs-i ## Commands & Events (Phase 4) -`createGameRuntime()` ahora devuelve también `executeCommand`, `on`, `emit`, `dispose`: +`createGameRuntime()` devuelve un handle con `executeCommand`, `on`, `emit`, `dispose`, además de `getScenes`, `getItems`, `getRules`: ```ts const runtime = createGameRuntime({ scenes }); runtime.on("scene:changed", handler); // suscribirse a eventos runtime.executeCommand({ type: "scene:set", sceneId: "town" }); // enviar comandos -const rt = getGameRuntime(); // acceso al singleton desde cualquier sitio +const rt = getGameRuntime(); // handle activo (null antes de crearlo o tras dispose) ``` Ver catálogo completo en [`05-bidirectional-communication.md`](05-bidirectional-communication.md). diff --git a/docs/architecture/05-bidirectional-communication.md b/docs/architecture/05-bidirectional-communication.md index 69a3616..2874610 100644 --- a/docs/architecture/05-bidirectional-communication.md +++ b/docs/architecture/05-bidirectional-communication.md @@ -1,6 +1,6 @@ # Bidirectional Communication -**Estado**: estable v0.4 | **Última revisión**: 2026-05-27 +**Estado**: estable v0.4; catálogo ampliado en 0.6.0 (sin publicar) | **Última revisión**: 2026-10-11 ## TL;DR @@ -14,7 +14,7 @@ Ambos son sincrónicos, fire-and-forget, y **no requieren React**. ## Quickstart ```ts -import { createGameRuntime } from "@pointclick-engine/engine-renderer-r3f"; // facade re-export +import { createGameRuntime } from "@pointclick-engine/engine-core"; const runtime = createGameRuntime({ scenes, items, rules }); @@ -35,17 +35,36 @@ runtime.dispose(); | Type | Payload | Efecto | |------|---------|--------| -| `scene:set` | `{ sceneId: string }` | Cambia la escena activa | +| `scene:set` | `{ sceneId: string, spawnPosition? }` | Cambia la escena activa | | `scene:respawn` | — | Reinicia player en spawn de la escena actual | | `player:move` | `{ position: [x,y,z] }` | Teleporta player (sin pathfinding) | -| `player:stop` | — | Cancela movimiento en curso *(not yet wired — Phase 5)* | -| `inventory:toggle` | — | Abre/cierra UI inventario *(not yet wired — Phase 5)* | -| `inventory:pickup` | `{ itemId: string }` | Mete ítem al inventario *(not yet wired — Phase 5)* | -| `inventory:drop` | `{ itemId: string, slotIndex: number }` | Suelta ítem *(not yet wired — Phase 5)* | -| `dialog:trigger` | `{ dialogKey: string }` | Muestra diálogo por clave *(not yet wired — Phase 5)* | -| `dialog:dismiss` | — | Cierra diálogo activo *(not yet wired — Phase 5)* | +| `player:stop` | — | Aborta una caminata por ruta (emite `player:walkAborted`) | +| `inventory:toggle` | — | Abre/cierra UI inventario | +| `inventory:pickup` | `{ itemId, placedItemId? }` | Recoge un ítem colocado de la escena activa | +| `inventory:drop` | `{ itemId, slotIndex, interactionId? \| hotspotId? }` | Suelta ítem sobre una interacción o un hotspot | +| `dialog:trigger` | `{ dialogKey, speaker? }` | Muestra el bocadillo de una clave | +| `dialog:dismiss` | — | Cierra diálogo activo | -Comandos sin executor real loguean un `console.warn` y no hacen nada. Se cablearán en Phase 5. +Comandos sin executor registrado loguean un `console.warn` y no hacen nada. + +### Comandos nuevos en 0.6.0 + +Fuente: `packages/engine-core/src/game/commands/types.ts`. + +| Type | Payload | Efecto | +|------|---------|--------| +| `state:setFlag` | `{ name, value }` | Pone un flag (`boolean \| number \| string`) | +| `state:clearFlag` | `{ name }` | Borra un flag | +| `game:save` | `{ extra? }` | Guarda la partida (requiere `storage`) | +| `game:load` | — | Carga la partida guardada | +| `game:reset` | — | Vacía la partida y borra el guardado | +| `script:run` | `{ script, interrupt? }` | Ejecuta un guion | +| `script:cancelAll` | — | Cancela el guion en curso y la cola | +| `hotspot:interact` | `{ hotspotId, verb, itemId? }` | Verbo (`look`, `use`, `talk`) o `useItem` sobre un hotspot o NPC | +| `inventory:combine` | `{ itemId, withItemId }` | Combina dos ítems del inventario | +| `dialogue:start` | `{ dialogueId }` | Abre una conversación | +| `dialogue:choose` | `{ index }` | Elige una opción | +| `dialogue:advance` / `dialogue:end` | — | Cierra la línea / termina la conversación | ## Catálogo de eventos @@ -57,9 +76,28 @@ Comandos sin executor real loguean un `console.warn` y no hacen nada. Se cablear | `player:collided` | `{ reason, position }` | Boundary / stuck | | `item:pickedUp` | `{ itemId, quantity }` | Tras pickup exitoso | | `item:dropped` | `{ itemId, outcome, interactionId? }` | Tras drop | -| `dialog:triggered` | `{ text, dialogKey?, source }` | Diálogo mostrado | +| `dialog:triggered` | `{ text, dialogKey?, source, speaker? }` | Diálogo mostrado | | `dialog:dismissed` | `{ dialogKey? }` | Diálogo cerrado | +### Eventos nuevos en 0.6.0 + +Fuente: `packages/engine-core/src/game/events/types.ts`. + +| Type | Payload | Cuándo | +|------|---------|--------| +| `state:flagChanged` | `{ name, value?, previous? }` | Cambia o se borra un flag | +| `game:saved` / `game:reset` | — | Tras guardar / reiniciar | +| `game:loaded` | `{ found, applied?, extra? }` | Tras `game:load` | +| `script:started` / `script:finished` | `{ id }` / `{ id, result }` | Un guion empieza / termina (`"finished"` o `"cancelled"`) | +| `input:lockChanged` | `{ locked }` | Cambia el bloqueo de entrada | +| `custom` | `{ name, payload? }` | Acción `emit` de un guion | +| `hotspot:interacted` | `{ hotspotId, verb, itemId? }` | Se aplicó una rama | +| `hotspot:noAction` | `{ hotspotId, verb, itemId?, reason }` | Sin rama (`not-found`, `hidden`, `missing-item`, `no-rule`) | +| `dialogue:started` / `nodeEntered` / `choiceMade` / `ended` | ver tipos | Ciclo de una conversación (`ended.reason`: `finished`, `ended`, `cancelled`) | +| `inventory:pickupFailed` | `{ itemId, reason }` | `not-found`, `blocked`, `full`, `unknown-item` | +| `inventory:full` / `item:removed` | `{ itemId }` | `giveItem` sin sitio / `removeItem` | +| `item:combined` / `item:combineFailed` | `{ itemId, withItemId }` | Resultado de `inventory:combine` | + > **Nota sobre `player:moved`**: se emite a ~60Hz. Si el consumer hace operaciones costosas > en este handler, añadir throttle/debounce en el callback — nunca en el motor. @@ -110,7 +148,7 @@ window.addEventListener("message", (msg) => { Si no tienes referencia directa al handle (ej. dentro de un componente que no lo creó): ```ts -import { getGameRuntime } from "@pointclick-engine/engine-renderer-r3f"; +import { getGameRuntime } from "@pointclick-engine/engine-core"; const rt = getGameRuntime(); // null si no se ha llamado createGameRuntime todavía rt?.executeCommand({ type: "scene:respawn" }); ``` diff --git a/docs/architecture/10-narrative-model.md b/docs/architecture/10-narrative-model.md new file mode 100644 index 0000000..02ac489 --- /dev/null +++ b/docs/architecture/10-narrative-model.md @@ -0,0 +1,73 @@ +# Modelo narrativo (0.6.0) + +**Estado**: implementado (Fase 17, sin publicar) | **Decisión**: [ADR-0010](../decisions/0010-declarative-narrative-model.md) | **Cómo se usa**: [`../authoring/README.md`](../authoring/README.md) + +## TL;DR + +El contenido narrativo es **dato serializable**, no código. Un intérprete pequeño en `engine-core` lo ejecuta despachando los comandos que ya existían y esperando eventos del bus. Nada de esto importa React ni el renderer. + +## Cómo encajan las piezas + +``` + contenido (datos) core (packages/engine-core/src/game/narrative/) + ───────────────── ────────────────────────────────────────────── + scene.hotspots / npcs ──┐ + scene.onEnter │ evento del jugador / de escena + transition.when/blocked ├──► hotspot:interact · dialogue:start · inventory:combine · + item.combine │ entrada a escena · transición + dialogue nodes/choices ─┘ │ + ▼ + estado de mundo ──► condiciones ──► ramas (pickBranch: gana la primera) + (flags, visitadas, evaluateCondition │ guion = Action[] + inventario, ítems ▼ + colocados, escena) secuenciador (createSequencer) + ▲ cola FIFO · cancelable · ClockPort + │ │ una acción cada vez + │ ▼ + │ comandos (dialog:trigger, state:setFlag, + │ player:walkTo, scene:set, ...) + │ │ + └──────── stores (sceneStore, ▼ + worldStateStore, ...) eventos (dialog:dismissed, + player:walkCompleted, state:flagChanged, + script:finished, ...) ──► host / UI / sequencer +``` + +1. **Estado de mundo** (`state/worldStateStore.ts`): flags `boolean | number | string` y escenas visitadas. Junto al inventario, los ítems colocados y la escena activa forma el `ConditionContext` (`getConditionContext`). +2. **Condiciones** (`narrative/conditions.ts`): `Condition` evaluable sin efectos con `evaluateCondition`. Una forma desconocida es `false`. +3. **Ramas** (`narrative/branches.ts`): `pickBranch(branches, ctx)` devuelve el guion de la primera rama cuyo `when` se cumple. Hotspots, NPC, `useItem`, `combine` y `onEnter` son listas de ramas. +4. **Secuenciador** (`narrative/sequencer.ts`, `actionExecutors.ts`): ejecuta un guion acción a acción. Cada acción **despacha comandos existentes** y espera el evento que la completa (`say` espera `dialog:dismissed`; `walkTo`, `player:walkCompleted` o `player:walkAborted`; `wait`, el `ClockPort`). Cola FIFO; `interrupt` y `script:cancelAll` cancelan. `lockInput` bloquea la entrada del jugador. +5. **Comandos y eventos**: lo único que cruza hacia fuera. El host observa con `runtime.on(...)` y actúa con `executeCommand(...)`; los catálogos nuevos están en [05](05-bidirectional-communication.md). + +## Un mismo motor para todo + +`registerHotspotCommands`, `registerDialogueCommands` y `registerCombineCommands` reciben `runScript` del secuenciador: hablar con un NPC, usar un ítem y combinar son el mismo mecanismo con distinto disparador. Un diálogo es un ejecutor de la acción `startDialogue` que recorre nodos y espera el cierre del bocadillo o la elección. + +`say` y las líneas de diálogo emiten `dialog:trigger` con una **clave** que se resuelve en las reglas del runtime o en un `dialogAdapter` del host (ver [`../authoring/README.md`](../authoring/README.md)). + +## Quién aplica qué + +| Regla | Funciones puras (core) | Las aplica | +|-------|------------------------|------------| +| `initialItems` | `resolveInitialItems` | el renderer al entrar a la escena; `createPlaythrough` en headless | +| `onEnter` | `resolveEnterScript` | ídem | +| `transition.when` / `blocked` | `evaluateTransitionGate` | ídem, antes de cambiar de escena | +| Verbos, `useItem`, `combine`, diálogos | comandos del runtime (`hotspot:interact`, `inventory:combine`, `dialogue:*`) | el core, sin renderer | + +Los callbacks de 0.5.0 (`canLeaveScene`, `onSceneEnter`, `getInitialPlacedItems`) siguen disponibles como **vía avanzada** y se evalúan después de las reglas declarativas. + +## Guardado + +La instantánea `GameSnapshot` (`state/saveGame.ts`) serializa exactamente ese estado: escena, posición, inventario, ítems colocados, escenas sembradas, flags y escenas visitadas, más `extra` para el host. Por eso el contenido declarativo se puede guardar, validar (`validateContent`) y repetir en headless (`createPlaythrough`). Ver [`../authoring/05-saving-and-testing.md`](../authoring/05-saving-and-testing.md). + +## Dónde vive cada cosa + +| Capa | Qué | Ruta | +|------|-----|------| +| Core | tipos, evaluador, secuenciador, comandos narrativos, stores, guardado, validador | `packages/engine-core/src/game/{narrative,state}/` | +| Core | `ClockPort`, `HeadlessClock` | `packages/engine-core/src/ports/` | +| Core (subpath `/testing`) | `createPlaythrough` | `packages/engine-core/src/testing/` | +| Renderer | `SceneHotspots`, `SceneNpcs`, `NpcSprite`, `VerbMenu`, `DialogueChoices`, `useDialogue`, `useHotspotInteractions` | `packages/engine-renderer-r3f/src/` | +| Host | textos (`rules` o `dialogAdapter`), `characters`, UI de inventario/combinar | `apps/web-demo/` | + +Cumple la [regla de oro](03-rules-core-vs-render.md): el core no importa React, R3F, `window` ni `document`. diff --git a/docs/authoring/01-scenes-and-hotspots.md b/docs/authoring/01-scenes-and-hotspots.md new file mode 100644 index 0000000..dd17572 --- /dev/null +++ b/docs/authoring/01-scenes-and-hotspots.md @@ -0,0 +1,129 @@ +# 1. Escenas, transiciones, hotspots y verbos + +Una escena es un objeto `GameSceneConfig` (`packages/engine-core/src/game/runtime/types.ts`). Esta guía cubre lo que añade la 0.6.0: `hotspots`, `npcs` (ver [03](03-dialogues-and-npcs.md)), `initialItems` y `onEnter` (ver [02](02-conditions-and-actions.md) y [04](04-items-and-combining.md)) y las condiciones de las transiciones. + +## Hotspots + +Un hotspot es una caja clicable con reglas por **verbo**. Tipos reales (`packages/engine-core/src/game/types/index.ts`): + +```ts +export type Verb = "look" | "use" | "talk"; + +export interface GameSceneHotspot { + id: string; + /** Clave de i18n. */ + label: string; + position: GameVec3; + halfSize: GameVec3; + rotationY?: number; + visibleWhen?: Condition; + hasCollision?: boolean; + /** Punto al que camina el jugador antes de actuar. Sin el, actua desde donde esta. */ + approach?: GameVec3; + verbs?: Partial>; + /** Ramas por itemId al usar un item del inventario sobre el hotspot. */ + useItem?: Record; + /** Ramas para un item sin regla propia en `useItem`. */ + useItemDefault?: Branch[]; +} +``` + +- Cada verbo (y cada `useItem[itemId]`) es una lista de **ramas** `{ when?, do }`: gana la primera cuyo `when` se cumple (sin `when` se cumple siempre). Ver [02](02-conditions-and-actions.md). +- Un verbo sin rama aplicable no aparece en el menú. Orden de preferencia del verbo por defecto: `talk`, `use`, `look` (`getDefaultVerb`, `packages/engine-core/src/game/narrative/hotspots.ts`). +- Si solo hay un verbo aplicable, el click lo ejecuta; si hay varios, el renderer muestra `VerbMenu`. +- `approach`: el jugador camina ahí antes del guion (se antepone un `walkTo`). +- `visibleWhen`: oculta el hotspot mientras no se cumpla. +- Soltar un ítem del inventario sobre el hotspot equivale al verbo `useItem` (`hotspot:interact` con `verb: "useItem"`). + +Si no hay regla aplicable, el comando emite `hotspot:noAction` (`reason`: `"not-found" | "hidden" | "missing-item" | "no-rule"`) y el renderer dice la frase `engine.hotspot.noAction`. + +## Ejemplo: el cofre y el mapa de "El faro" + +Copiado de `packages/engine-core/src/__tests__/fixtures/miniAdventure.ts` (escena `beach`): + +```ts +import { act, branch, cond, otherwise, type GameSceneConfig } from "@pointclick-engine/engine-core"; + +const zone = [0.5, 1, 0.5] as [number, number, number]; + +const hotspots: GameSceneConfig["hotspots"] = [ + { + id: "chest", + label: "chest.label", + position: [-3, 0, 2], + halfSize: zone, + approach: [-2, 0, 2], + verbs: { + look: [otherwise(act.say("chest.look"))], + use: [ + branch(cond.flag("chest.open"), act.say("chest.empty")), + otherwise(act.say("chest.locked")), + ], + }, + useItem: { + "rusty-key": [ + branch(cond.flag("chest.open"), act.say("chest.alreadyOpen")), + otherwise( + act.say("chest.unlock"), + act.removeItem("rusty-key"), + act.setFlag("chest.open"), + act.giveItem("lens"), + ), + ], + }, + useItemDefault: [otherwise(act.say("chest.nothing"))], + }, + { + id: "map", + label: "map.label", + position: [0, 0, -3], + halfSize: zone, + verbs: { look: [otherwise(act.say("map.look"), act.setFlag("map.seen"))] }, + }, +]; +``` + +Lee: mirar el cofre siempre da la misma frase; usarlo dice "cerrado" hasta que `chest.open`; la llave lo abre una vez; cualquier otro ítem cae en `useItemDefault`. + +## Transiciones con condición + +Todas las transiciones (`collision`, `item-drop`...) aceptan dos campos nuevos (`BaseSceneTransition`, mismo archivo de tipos): + +```ts + /** + * Condicion para que la transicion ocurra (todos los tipos). Sin ella, siempre ocurre. + * Si no se cumple no hay cambio de escena y, si existe, corre `blocked`. + */ + when?: Condition; + /** Guion que corre al intentar la transicion sin cumplir `when`. */ + blocked?: Script; +``` + +Del fixture (escena `cove`): + +```ts +transitions: [ + { + id: "to-lighthouse", + kind: "collision", + targetSceneId: "lighthouse", + position: [0, 0, 7], + halfSize: [2, 1, 0.5], + when: cond.flag("keeper.lit"), + blocked: [act.say("lighthouse.locked")], + }, +], +``` + +El renderer aplica `when`/`blocked` con `evaluateTransitionGate` antes de cambiar de escena. El callback `canLeaveScene` de 0.5.0 sigue existiendo como vía avanzada y se evalúa **después**: solo si `when` deja pasar puede además vetar. + +## Elementos de escena declarativos + +| Campo | Qué es | Guía | +|-------|--------|------| +| `hotspots` | cajas con verbos | esta | +| `npcs` | personajes con los que hablar | [03](03-dialogues-and-npcs.md) | +| `initialItems` | ítems sembrados una vez por escena, con `when` opcional | [04](04-items-and-combining.md) | +| `onEnter` | ramas que corren en cada entrada | [02](02-conditions-and-actions.md) | + +Los hotspots y NPC se conservan al registrar la escena (`registerScene` / `scenes` de `createGameRuntime`). diff --git a/docs/authoring/02-conditions-and-actions.md b/docs/authoring/02-conditions-and-actions.md new file mode 100644 index 0000000..983d910 --- /dev/null +++ b/docs/authoring/02-conditions-and-actions.md @@ -0,0 +1,111 @@ +# 2. Flags, condiciones y acciones + +El estado de mundo son **flags** con nombre (`boolean | number | string`, `FlagValue` en `packages/engine-core/src/game/state/worldStateStore.ts`) y la lista de escenas visitadas. Las condiciones lo leen sin efectos; las acciones lo cambian y mueven el juego. + +## Condiciones + +Tipo real (`packages/engine-core/src/game/narrative/conditions.ts`): + +```ts +export type Condition = + | { flag: string; equals?: FlagValue; gte?: number; lte?: number } // sin operador: "es verdadero" + | { hasItem: string; atLeast?: number } + | { itemPlaced: string; inScene?: string; at?: string } // at = interactionId + | { inScene: string } + | { visited: string } + | { all: Condition[] } + | { any: Condition[] } + | { not: Condition }; +``` + +- `flag` sin operador es verdadero para `true`, un número distinto de 0 o un texto no vacío. Un flag nunca puesto es falso. +- Una condición `undefined` cuenta como verdadera. Una forma desconocida se evalúa a `false` (con un `console.warn`). +- Constructores `cond`: `cond.flag("x")`, `cond.flag("n", { gte: 3 })`, `cond.hasItem`, `cond.itemPlaced`, `cond.inScene`, `cond.visited`, `cond.all(...)`, `cond.any(...)`, `cond.not(c)`. Devuelven objetos planos. + +## Acciones y guiones + +Tipo real (`packages/engine-core/src/game/narrative/actions.ts`): + +```ts +export type Action = + | { say: string; speaker?: string } // clave de dialogo; espera al cierre + | { setFlag: string; value?: FlagValue } // por defecto true + | { giveItem: string } + | { removeItem: string } + | { placeItem: PlacedSceneItem } + | { removePlacedItem: string } + | { changeScene: string; spawnPosition?: GameVec3 } + | { walkTo: GameVec3 } // espera al fin o al aborto de la caminata + | { wait: number } // ms, via ClockPort + | { playSfx: string } + | { startDialogue: string } // tarea 07; espera al final + | { lockInput: boolean } + | { emit: string; payload?: unknown } // evento { type: "custom", name, payload } + | { call: string; args?: unknown }; // manejador registrado por el host + +export type Script = Action[]; +export type Branch = { when?: Condition; do: Script }; +``` + +Un **guion** es una lista de acciones que se ejecutan **en orden**, una a la vez. Constructores `act.*` (uno por acción) y, para ramas, `branch(when, ...acciones)` y `otherwise(...acciones)` (rama sin condición, siempre la última). + +Un guion lo ejecuta el secuenciador: cola FIFO, cancelable, con `ClockPort` inyectado. Desde fuera: `runtime.runScript(script, { interrupt? })` o el comando `script:run` (`interrupt` cancela el actual y vacía la cola); `script:cancelAll` los cancela todos. Eventos: `script:started`, `script:finished` (`result: "finished" | "cancelled"`). + +### Ramas: gana la primera + +`pickBranch` recorre las ramas en orden y corre la primera cuyo `when` se cumple. Por eso `otherwise(...)` va al final: + +```ts +use: [ + branch(cond.flag("chest.open"), act.say("chest.empty")), + otherwise(act.say("chest.locked")), +], +``` + +## Dos reglas de orden que muerden + +**`say` espera a que se cierre el bocadillo** (unos segundos): el guion no sigue hasta el evento `dialog:dismissed`. Los cambios de estado que deban quedar hechos cuanto antes (`giveItem`, `removeItem`, `setFlag`...) van **antes** del `say`. Así lo hace la demo en `demo-content/items/index.ts`: + +```ts +combine: { + "key-bit": [ + otherwise( + // `say` espera a que se cierre el bocadillo: el resultado va antes que la frase. + act.removeItem("key-handle"), + act.removeItem("key-bit"), + act.giveItem("bronze-key"), + act.say("combine.key.done"), + ), + ], +}, +``` + +**`onEnter` "solo la primera vez" se hace con un flag, no con `visited`.** Cuando se evalúa `onEnter`, la escena ya cuenta como visitada: `not(visited(...))` nunca se cumpliría. Del fixture (escena `beach`): + +```ts +// Solo la primera vez: el flag, no `visited` (al evaluarse la escena ya cuenta como visitada). +onEnter: [branch(cond.not(cond.flag("intro.done")), act.say("beach.intro"), act.setFlag("intro.done"))], +``` + +`onEnter` corre en **cada** entrada a la escena; sin flag, repite (la demo lo usa así para su bienvenida: `onEnter: [otherwise(act.say("personalRoomWelcome"))]`). + +## Cuándo usar `call` + +`call` invoca un manejador con nombre que registra el host: es la vía de escape para lo que el vocabulario no cubre (créditos, analíticas, abrir una pantalla). Si el mismo `call` se repite en varios juegos, es candidato a acción nueva. Del fixture, escena `lighthouse`: + +```ts +onEnter: [ + branch( + cond.flag("keeper.lit"), + act.say("lighthouse.ending"), + act.call("credits", { ending: "good" }), + act.setFlag("game.finished"), + ), +], +``` + +El host lo registra con `runtime.registerHandler("credits", (args) => ...)` (devuelve la función que lo quita). Para que `validateContent` avise de un `call` sin manejador, pasa sus nombres en `handlerNames` de la config del runtime (en `GameContent` el campo se llama `handlers`). Un `call` sin manejador avisa por consola y el guion continúa; si el manejador devuelve una promesa, el guion la espera. + +## Quién aplica las reglas declarativas + +`initialItems`, `onEnter` y `transition.when`/`blocked` los aplica el **renderer** con funciones puras del core (`resolveInitialItems`, `resolveEnterScript`, `evaluateTransitionGate`). En headless los aplica `createPlaythrough` ([05](05-saving-and-testing.md)). Los callbacks de 0.5.0 (`canLeaveScene`, `onSceneEnter`, `getInitialPlacedItems`) siguen funcionando, se evalúan **después** de los declarativos y son vía avanzada. diff --git a/docs/authoring/03-dialogues-and-npcs.md b/docs/authoring/03-dialogues-and-npcs.md new file mode 100644 index 0000000..f186668 --- /dev/null +++ b/docs/authoring/03-dialogues-and-npcs.md @@ -0,0 +1,159 @@ +# 3. Diálogos con opciones y NPCs + +No confundir: `dialog:*` (singular) es el **bocadillo de una frase**; `dialogue:*` es una **conversación** con varios turnos y opciones. + +## Árbol de diálogo + +Tipos reales (`packages/engine-core/src/game/narrative/dialogueTypes.ts`): + +```ts +export interface DialogueChoice { + /** Clave de i18n del texto de la opcion. */ + text: string; + /** Opcion oculta si no se cumple. */ + when?: Condition; + /** Desaparece tras elegirla (se recuerda con el flag `dlg...`). */ + once?: boolean; + do?: Script; + next?: string; +} + +export interface DialogueNode { + id: string; + /** Id de NPC o "player". */ + speaker?: string; + /** Clave de i18n; sin linea, el nodo solo ejecuta `do`. */ + line?: string; + /** Efectos al entrar en el nodo (se esperan antes de seguir). */ + do?: Script; + /** Sin opciones visibles, avanza a `next`. */ + choices?: DialogueChoice[]; + /** Sin next ni opciones visibles, el dialogo termina. */ + next?: string; +} + +export interface DialogueDefinition { id: string; start: string; nodes: DialogueNode[] } +``` + +Constructores: `dialogue.define(id, start, ...nodos)`, `dialogue.node(id, props)`, `dialogue.choice(text, props)`. Se registran en `dialogues` de `createGameRuntime`. La conversación termina con `dialogue:ended` (`reason`: `"finished" | "ended" | "cancelled"`). + +Ejemplo del fixture (`miniAdventure.ts`, pescador de la playa): + +```ts +import { act, cond, dialogue } from "@pointclick-engine/engine-core"; + +dialogue.define( + "fisher-talk", + "root", + dialogue.node("root", { + speaker: "fisherman", + line: "fisher.hello", + choices: [ + // 0: la pista solo si ya se miro el mapa; una sola vez. + dialogue.choice("ask.frame", { + when: cond.flag("map.seen"), + once: true, + do: [act.say("fisher.frame", "fisherman"), act.giveItem("lamp-frame")], + next: "root", + }), + // 1: saludo, solo la primera vez. + dialogue.choice("ask.weather", { once: true, do: [act.say("fisher.weather", "fisherman")], next: "root" }), + // 2: despedida (sin next: termina la conversacion). + dialogue.choice("bye"), + ], + }), +); +``` + +Reglas que se ven ahí: + +- El **índice** de una opción es su posición original en `node.choices` (0, 1, 2), aunque otras estén ocultas. Es lo que usan `dialogue:choose` y `choose()` del playthrough. +- `when` oculta la opción; `once` la oculta tras elegirla (queda el flag `dlg.fisher-talk.root.0`). +- Una opción sin `next` termina la conversación. +- Al elegir, se cierra la línea, corre el `do` de la opción (espera cada acción, `say` incluido, ver [02](02-conditions-and-actions.md)) y luego se pasa a `next`. + +Un caso real de la demo (`apps/web-demo/demo-content/dialogues/guide.ts`) usa `cond.hasItem("trophy")` en una opción y `act.giveItem("key-handle")` en otra con `once`. + +## NPCs + +Un NPC es un hotspot con sprite. Tipo real (`packages/engine-core/src/game/types/index.ts`): + +```ts +export interface GameSceneNpc { + id: string; + /** Clave de i18n. */ + name: string; + /** Id de un personaje registrado en el viewport (prop `characters`). */ + characterId: string; + position: GameVec3; + facing?: NpcFacing; // "north" | "south" | "west" | "east" + visibleWhen?: Condition; + hasCollision?: boolean; + approach?: GameVec3; + clickBox?: { halfSize: GameVec3; offset?: GameVec3 }; + /** Atajo: hablar inicia este diálogo. Equivale a `verbs.talk = [{ do: [{ startDialogue }] }]`. */ + dialogueId?: string; + verbs?: Partial>; + useItem?: Record; +} +``` + +Del fixture (escena `cove`): un guardián con diálogo, que además acepta la lámpara y se deja mirar: + +```ts +npcs: [ + { + id: "keeper", + name: "keeper.name", + characterId: "keeper", + position: [2, 0, 2], + dialogueId: "keeper-talk", + useItem: { + lamp: [ + otherwise( + act.say("keeper.thanks", "keeper"), + act.removeItem("lamp"), + act.setFlag("keeper.lit"), + ), + ], + }, + verbs: { look: [otherwise(act.say("keeper.look"))] }, + }, +], +``` + +- `dialogueId` es un atajo de `verbs.talk`; un `verbs.talk` explícito gana. +- `clickBox` ajusta la caja clicable (por defecto cubre un sprite de tamaño estándar, de los pies a la cabeza). +- `characterId` apunta a un `CharacterDefinition` que pasas en la prop `characters` de `GameViewport` (`Record`). La demo lo hace en `apps/web-demo/demo-content/characters/guide.ts` (`DEMO_NPC_CHARACTERS`). + +### El `speaker` debe ser el `id` del NPC + +Para que el bocadillo salga sobre el NPC, el `speaker` de la línea (`node.speaker`) o de `say` debe ser **exactamente el `id`** del NPC (`"fisherman"`, `"keeper"`). Si no coincide con un NPC visible, el bocadillo sale sobre el jugador (`resolveSpeakingNpcId`). + +### Proyección a hotspot y `resolveScene` + +`toRuntimeScene` añade cada NPC a `scene.hotspots` con `npcToHotspot`, para que `hotspot:interact` los encuentre. Un host que **sobrescriba `resolveScene`** con sus propias escenas debe proyectar él los NPC. Así lo hace la demo (`apps/web-demo/app/lib/engine/runtime/demoViewportOptions.ts`): + +```ts +import { npcToHotspot, type GameScene } from "@pointclick-engine/engine-core"; + +function resolveDemoScene(id: string): GameScene | null { + const scene = SCENES[id]; + if (!scene) return null; + if (!scene.npcs?.length) return scene; + return { ...scene, hotspots: [...(scene.hotspots ?? []), ...scene.npcs.map(npcToHotspot)] }; +} +``` + +## Comandos, eventos y UI + +| Comando | Efecto | +|---------|--------| +| `dialogue:start` `{ dialogueId }` | Abre la conversación (también la acción `startDialogue`) | +| `dialogue:choose` `{ index }` | Elige la opción con ese índice original | +| `dialogue:advance` | Cierra la línea abierta (sin opciones) y sigue al `next` | +| `dialogue:end` | Cierra la conversación | + +Eventos: `dialogue:started`, `dialogue:nodeEntered`, `dialogue:choiceMade`, `dialogue:ended`. + +El renderer pinta las opciones con `DialogueChoices` (flechas, Enter/Espacio y teclas 1-9) y la línea en el bocadillo del `speaker`. Sustitúyelo con la prop `dialogueChoices` de `GameViewport`; `useDialogue()` da `{ active, speaker, choices, choose, advance, end }` para una UI propia. Mientras hay conversación la entrada del jugador queda bloqueada. diff --git a/docs/authoring/04-items-and-combining.md b/docs/authoring/04-items-and-combining.md new file mode 100644 index 0000000..47f35e5 --- /dev/null +++ b/docs/authoring/04-items-and-combining.md @@ -0,0 +1,105 @@ +# 4. Ítems, reglas de drop y combinaciones + +## Ítems + +`GameItemConfig` (`packages/engine-core/src/game/runtime/types.ts`): + +```ts +export type GameItemConfig = { + id: string; + name: string; + spriteUrl: string; + descriptionDialogKey?: string; + pickupSoundUrl?: string; + dropSoundUrl?: string; + interactionRules: Record; + defaultRule: GameItemRule; + /** Ramas condicionales para combinar este ítem con otro por id. */ + combine?: Record; +}; +``` + +`interactionRules` (por id de interacción) y `defaultRule` son las **reglas de drop** de 0.5.0: qué pasa al soltar el ítem sobre una diana de arrastre (`GameItemRule.outcome`: `"place"` lo deja en la escena, `"consume"` lo gasta, `"return"` vuelve al inventario; más `hitDialogKey`, `missDialogKey`...). No cambian en 0.6.0. Los ítems que no se sueltan en dianas usan `interactionRules: {}` y `defaultRule: { outcome: "return" }`, como el fixture: + +```ts +const item = (id: string, extra: Partial = {}): GameItemConfig => ({ + id, + name: `item.${id}`, + spriteUrl: `/${id}.png`, + interactionRules: {}, + defaultRule: { outcome: "return" }, + ...extra, +}); +``` + +## Combinar dos ítems + +La regla se declara en **uno** de los ítems: `combine[idDelOtro]` es una lista de ramas ([02](02-conditions-and-actions.md)). Vale en **ambos sentidos**: `resolveCombine(a, b)` busca primero `a.combine[b.id]` y, si no existe, `b.combine[a.id]`. Del fixture: + +```ts +import { act, otherwise, type GameItemConfig } from "@pointclick-engine/engine-core"; + +const lens: GameItemConfig = item("lens", { + combine: { + "lamp-frame": [ + otherwise( + act.say("combine.lamp"), + act.removeItem("lens"), + act.removeItem("lamp-frame"), + act.giveItem("lamp"), + ), + ], + }, +}); +``` + +El guion **decide** el resultado: el comando `inventory:combine` no quita ni da nada por su cuenta, solo corre la rama. Recuerda el orden de [02](02-conditions-and-actions.md): `say` espera al cierre del bocadillo, así que la demo (`demo-content/items/index.ts`) pone `removeItem`/`giveItem` **antes** del `say`. + +Comando y eventos: + +| | | +|--|--| +| Comando | `inventory:combine` `{ itemId, withItemId }` | +| Éxito | `item:combined` `{ itemId, withItemId }` y se corre el guion | +| Fallo | `item:combineFailed` si son el mismo ítem, falta alguno en el inventario, no está registrado o no hay rama aplicable | + +El renderer **no** trae UI de combinar: la UI del inventario es del host. La demo lanza el comando al soltar un ítem sobre otro slot ocupado (`apps/web-demo/app/components/GameTouchCanvas.tsx`) y explica `item:combineFailed` con una frase. + +## Usar un ítem sobre un hotspot o NPC + +`useItem[itemId]` del hotspot/NPC (ver [01](01-scenes-and-hotspots.md)) y `useItemDefault` para el resto. Solo se ejecuta si el jugador tiene el ítem: si no, `hotspot:noAction` con `reason: "missing-item"`. En el fixture, la llave abre el cofre y cualquier otra cosa cae en `useItemDefault`. + +## Ítems iniciales en la escena (`initialItems`) + +Se siembran **una vez por escena** al entrar por primera vez; cada uno con un `when` opcional evaluado en ese momento (`SceneInitialItem`, `packages/engine-core/src/game/types/index.ts`): + +```ts +export interface SceneInitialItem { + item: PlacedSceneItem; + when?: Condition; +} +``` + +Del fixture (escena `cove`), el pescado solo aparece si ya se pasó por la playa: + +```ts +initialItems: [ + { item: placed("fish-on-rocks", "fish", "rocks", "cove"), when: cond.visited("beach") }, +], +``` + +Notas: + +- `PlacedSceneItem` (mismo archivo): `id`, `itemId`, `interactionId`, `name`, `spriteUrl`, `worldPosition`, `canPickup`, y opcionales `hasCollision`, `collisionHalfSize`, `pickupSuccessDialogKey`, `pickupBlockedDialogKey`, `sceneId`. Un ítem sin `sceneId` recibe el de la escena que lo siembra. +- El `interactionId` de un ítem colocado es una **etiqueta libre**, no una referencia validada: no tiene que existir en `interactions` (el validador no lo comprueba). +- Una escena sembrada no vuelve a sembrarse al reentrar (se recuerda en `seededSceneIds` del guardado). La demo (`scenes.ts`, `personalRoom`) usa un `when` con `cond.not(cond.itemPlaced("trophy"))` para no duplicar el trofeo. +- Los ítems también se pueden dar y quitar en un guion: `act.giveItem`, `act.removeItem`, `act.placeItem`, `act.removePlacedItem`. + +## Recoger y soltar por comando + +| Comando | Campos nuevos en 0.6.0 | +|---------|------------------------| +| `inventory:pickup` | `placedItemId?` (el `id` del ítem colocado) | +| `inventory:drop` | `interactionId?` o `hotspotId?` (como mucho uno; `hotspotId` equivale a `hotspot:interact` con `verb: "useItem"`) | + +Eventos: recoger emite `item:pickedUp` (desde 0.5.0; no `item:dropped`) o `inventory:pickupFailed` (`reason`: `"not-found" | "blocked" | "full" | "unknown-item"`); un guion emite además `item:removed` e `inventory:full` (inventario lleno al hacer `giveItem`). Estos comandos solo cambian estado: los textos (`hitDialogKey`, `pickup*DialogKey`) los muestra el renderer, y un guion los declara con `say`. diff --git a/docs/authoring/05-saving-and-testing.md b/docs/authoring/05-saving-and-testing.md new file mode 100644 index 0000000..d086c72 --- /dev/null +++ b/docs/authoring/05-saving-and-testing.md @@ -0,0 +1,112 @@ +# 5. Guardado, validación y test de recorrido + +## Guardado único + +Toda la partida vive en **una instantánea** JSON bajo una sola clave (`pointclick-save` por defecto). Tipo real (`packages/engine-core/src/game/state/saveGame.ts`): + +```ts +export interface GameSnapshot { + version: number; + sceneId: string; + playerPosition?: GameVec3; + inventory: InventorySlotsState; + placedItems: PlacedSceneItem[]; + seededSceneIds: string[]; + flags: Record; + visitedSceneIds: string[]; + /** Estado propio del host (p. ej. puertas de la demo). Opaco para el core. */ + extra?: Record; +} +``` + +Se activa pasando un almacenamiento a `createGameRuntime` (`storage: KeyValueStoragePort`, y opcionalmente `saveKey`). Sin `storage`, los comandos solo avisan por consola. + +| Comando | Evento | Qué hace | +|---------|--------|----------| +| `game:save` `{ extra? }` | `game:saved` | Escribe la instantánea (`extra` = estado propio del host) | +| `game:load` | `game:loaded` `{ found, applied?, extra? }` | Lee y restaura; `applied` es `false` si la escena guardada no está registrada | +| `game:reset` | `game:reset` | Vacía inventario, ítems, flags y borra la clave de guardado (no cambia de escena) | + +Detalles que importan: + +- Orden al restaurar: inventario, ítems colocados, flags, y **al final** la escena, para que lo que se evalúe al entrar vea el estado ya restaurado (`applySnapshot`). +- `loadGame` nunca lanza: devuelve `null` si no hay partida, el JSON es inválido, la forma no cuadra o la versión es superior a `SAVE_FORMAT_VERSION` (hoy 1). +- Para cambiar el formato: sube `SAVE_FORMAT_VERSION` y añade la entrada a `SAVE_MIGRATIONS` (`{ [versionOrigen]: migración }`). +- `playerPosition` es opcional: sin ella, la escena usa su `playerSpawn`. +- Una partida de 0.5.0 (cuatro claves sueltas: `inventory-slots`, `current-scene-id`, `placed-items-state`...) se convierte con `migrateLegacySave(storage, { defaultSceneId, legacySeededSceneId?, extraKeys? })`, que **no** borra las claves antiguas ni escribe la nueva: eso lo decides tú. La demo lo hace en `apps/web-demo/app/lib/gamePersistence.ts`, que además guarda sus puertas en `extra`. + +## Validación del contenido + +`validateContent(content)` recorre escenas, ítems y diálogos y devuelve una lista de incidencias (`ContentIssue`: `severity`, `code`, `where`, `message`). Con `createGameRuntime` corre sola, según la opción `validate`: + +| `validate` | Efecto | +|------------|--------| +| (sin valor) | Como `true` solo cuando `NODE_ENV === "development"`; nada en test o producción | +| `true` | Un único `console.warn` agrupado | +| `"throw"` | Lanza si hay errores (los avisos van a consola) | +| `false` | No valida | + +Para que compruebe las claves de texto y los `call`, pasa `dialogKeys` (conjunto de claves conocidas) y `handlerNames` (nombres de manejadores) en la config del runtime. En `GameContent`, que recibe `validateContent` directamente, se llaman `dialogKeys` y `handlers`. + +Códigos (`packages/engine-core/src/game/narrative/validate*.ts`): + +| Severidad | Códigos | +|-----------|---------| +| error | `duplicate-id`, `unknown-item`, `unknown-scene`, `unknown-interaction`, `unknown-dialogue`, `unknown-dialogue-start`, `unknown-dialogue-node`, `dialogue-dead-end`, `unknown-verb`, `unknown-action`, `unknown-branch`, `unknown-condition` | +| warning | `unknown-dialog-key`, `unknown-handler`, `unreachable-scene`, `unreachable-dialogue-node`, `unused-item`, `flag-never-set`, `flag-never-read` | + +El `interactionId` de un ítem colocado no se valida (es una etiqueta libre). + +## Test de recorrido headless + +`createPlaythrough` monta el runtime real con reloj virtual (`HeadlessClock`), almacenamiento en memoria y caminata instantánea, **sin renderer**. Se importa del subpath `@pointclick-engine/engine-core/testing`. Valida el contenido y lanza si hay errores. Hay **una sola partida viva por proceso** (los registros son globales): llama a `dispose()` al terminar cada test. + +Sin renderer, `createPlaythrough` aplica por su cuenta las reglas declarativas que en el juego aplica el renderer (`initialItems`, `onEnter`, `when`/`blocked`). Del test `miniAdventure.playthrough.test.ts`: + +```ts +import { createPlaythrough, type Playthrough } from "@pointclick-engine/engine-core/testing"; +import { miniAdventure } from "./fixtures/miniAdventure"; + +const p = createPlaythrough(miniAdventure, { + handlers: { credits: (args) => void credits.push(args) }, + onRuntime: (rt) => + void rt.on("dialog:triggered", (e) => { + if (e.dialogKey) said.push(e.dialogKey); + }), +}); +await p.settle(); + +// Puzzle 1: recoger y usar. +await p.pickUp("key-on-sand"); +await p.useItemOn("rusty-key", "chest"); +expect(p.state().inventory).toEqual(["lens"]); +expect(p.state().flags["chest.open"]).toBe(true); + +// Puzzle 2: conversacion condicionada por haber mirado el mapa. +await p.look("map"); +await p.talk("fisherman"); +await p.choose(0); +await p.choose(2); + +// Puzzle 3: combinar; luego cambio de escena. +await p.combine("lens", "lamp-frame"); +await p.goThrough("to-cove"); +``` + +API de `Playthrough` (`packages/engine-core/src/testing/playthrough.ts`): + +| Método | Qué hace | +|--------|----------| +| `look(id)`, `use(id)`, `talk(id)` | Verbo sobre el hotspot o NPC `id`; `talk` se detiene en la primera elección pendiente | +| `useItemOn(itemId, id)` | Usa un ítem del inventario sobre el hotspot o NPC | +| `combine(a, b)` | Combina dos ítems del inventario | +| `pickUp(placedItemId)` | Recoge un ítem colocado de la escena activa | +| `choose(index)` | Elige por **índice original** de `node.choices`; lanza si no está disponible ("no disponible") | +| `goThrough(transitionId)` | Cruza una transición respetando `when`/`blocked` | +| `settle()` | Avanza el reloj y cierra bocadillos hasta que no queden guiones | +| `state()` | `{ sceneId, inventory, flags, dialogueActive }` | +| `save()` | `GameSnapshot`; pásalo como `opts.snapshot` para reanudar | + +Opciones de `createPlaythrough`: `initialSceneId`, `handlers` (se registran antes de entrar en la escena inicial), `onRuntime` (antes de entrar, para suscribirse a eventos del arranque) y `snapshot`. + +Escribe también los recorridos "equivocados" (usar la llave sin tenerla, hablar antes de mirar el mapa, cruzar una transición bloqueada): el fixture los cubre en el mismo archivo. diff --git a/docs/authoring/README.md b/docs/authoring/README.md new file mode 100644 index 0000000..984f5eb --- /dev/null +++ b/docs/authoring/README.md @@ -0,0 +1,79 @@ +# Guía de autoría + +Cómo escribir una aventura con el motor (0.6.0): escenas, puzzles y diálogos como **datos** TypeScript, sin callbacks. Modelo y motivación: [`../architecture/10-narrative-model.md`](../architecture/10-narrative-model.md) y [ADR-0010](../decisions/0010-declarative-narrative-model.md). + +> La versión de los paquetes todavía es 0.5.0: lo de esta guía es la 0.6.0 sin publicar (ver los `CHANGELOG.md`). + +## Orden de lectura + +1. [`01-scenes-and-hotspots.md`](01-scenes-and-hotspots.md) — escenas, transiciones, hotspots y verbos. +2. [`02-conditions-and-actions.md`](02-conditions-and-actions.md) — flags, condiciones, acciones, ramas y `call`. +3. [`03-dialogues-and-npcs.md`](03-dialogues-and-npcs.md) — árboles de diálogo con opciones y NPCs. +4. [`04-items-and-combining.md`](04-items-and-combining.md) — ítems, reglas de drop y combinaciones. +5. [`05-saving-and-testing.md`](05-saving-and-testing.md) — guardado, validación y test de recorrido. + +## Ejemplos que se ejecutan + +Los fragmentos de la guía están copiados de código que corre: + +- `packages/engine-core/src/__tests__/fixtures/miniAdventure.ts`: "El faro", una mini-aventura completa (3 escenas, 2 NPC, 5 ítems, 4 puzzles encadenados). Su test `miniAdventure.playthrough.test.ts` la resuelve sin renderer. +- `apps/web-demo/demo-content/`: escenas, ítems y el diálogo `dialogues/guide.ts` de la demo. +- `apps/web-demo/app/example-minimal/page.tsx`: un hotspot y un ítem inicial en una escena, montados con `GameViewport`. + +## Lo mínimo: un hotspot que habla + +Tomado de `example-minimal/page.tsx`. Una escena con un hotspot `notice` cuyo verbo `look` pone un flag y dice una frase: + +```ts +import { act, otherwise, type GameSceneConfig } from "@pointclick-engine/engine-core"; + +const SCENE_A: GameSceneConfig = { + id: "minimal-a", + label: "Minimal Scene A", + background: "/assets/background/town.jpg", + playerSpawn: [3.08, 1.05, 13.44], + ground: { minX: -12, maxX: 17, minZ: -15, maxZ: 30, y: -3.25 }, + walls: [], + interactions: [], + hotspots: [ + { + id: "notice", + label: "notice.label", + position: [6.0, 2.6, 13.4], + halfSize: [0.7, 1.2, 0.5], + verbs: { + look: [otherwise(act.setFlag("notice.seen"), act.say("notice.look"))], + }, + }, + ], +}; +``` + +Con un solo verbo, un click lo ejecuta directamente; con varios sale un menú de verbos. + +## Textos: `say` y las líneas resuelven una clave + +`say`, `line`, `text` y `label` son **claves**, no texto. Se resuelven así (`dialog:trigger`, `packages/engine-core/src/game/runtime/executors.ts`): + +- Con reglas registradas: `rules: [{ key, phrases }]` en `createGameRuntime` (o `registerRule`). Se elige una frase al azar. +- O con un `dialogAdapter` propio que traduzca la clave, como hace la demo (`apps/web-demo/app/lib/engine/runtime/demoViewportOptions.ts`). +- Sin ninguno de los dos se muestra la clave literal. + +```ts +const created = createGameRuntime({ + scenes: [SCENE_A, SCENE_B], + items: [TROPHY_ITEM], + rules: [{ key: "notice.look", phrases: ["Un cartel de la plaza: 'SE BUSCA... un buen guía.'"] }], +}); +``` + +## Dónde mirar cuando algo no funciona + +| Síntoma | Causa habitual | Guía | +|---------|----------------|------| +| El bocadillo sale sobre el jugador y no sobre el NPC | `speaker` no es exactamente el `id` del NPC | [03](03-dialogues-and-npcs.md) | +| El `onEnter` de "solo la primera vez" no se dispara nunca | Se usó `not(visited(...))` | [02](02-conditions-and-actions.md) | +| El cambio de estado tarda en aplicarse | Va después de un `say`, que espera al cierre del bocadillo | [02](02-conditions-and-actions.md) | +| Aparece la clave en lugar del texto | Faltan `rules` o `dialogAdapter` | esta página | +| El NPC no se puede clicar | El host usa su propio `resolveScene` y no proyecta NPC | [03](03-dialogues-and-npcs.md) | +| Avisos en consola al arrancar | `validateContent` encontró referencias rotas | [05](05-saving-and-testing.md) | diff --git a/docs/decisions/0009-runtime-lives-in-packages.md b/docs/decisions/0009-runtime-lives-in-packages.md new file mode 100644 index 0000000..7434e44 --- /dev/null +++ b/docs/decisions/0009-runtime-lives-in-packages.md @@ -0,0 +1,51 @@ +# ADR-0009: El runtime vive en los paquetes, no en la demo + +**Status**: accepted (aprobado por el owner el 2026-10-10) +**Issue**: [#21](https://github.com/DanielMartinezSebastian/pointclick-engine/issues/21) +**Date**: 2026-10-10 + +## Context + +`createGameRuntime`, los registros de escenas/ítems/reglas, los executors de comandos, `useGameState`, `useGameActions` y `GameViewport` viven en `apps/web-demo/app/lib/engine/publicApi.ts`. Consecuencias medidas en la auditoría del 2026-10-10: + +- `docs/LIBRARY_CONSUMPTION_GUIDE.md` documenta esos símbolos como exports de `@pointclick-engine/engine-renderer-r3f`, que no los exporta. Quien instale los paquetes publicados (0.4.0) no tiene runtime. +- `GameViewport` renderiza un `` vacío. El juego real lo monta `GameTouchCanvas.tsx` (526 líneas) con 9 hooks en `app/lib/engine/runtime/`, 15 archivos que importan `demo-content` directamente. +- `scene:set` copia la escena campo a campo en 4 sitios y descarta `transitions` y `music`. +- La demo mantiene copias de 7 archivos del renderer y de `inventoryRules.ts`. + +## Decision + +1. **`engine-core` aloja el runtime agnóstico**: `createGameRuntime`, registros, `CommandHandler` con sus executors, `EventBus`, `getGameRuntime`, `getGameState`, `getGameActions`. No depende de React. Los registros pertenecen a la instancia de runtime; `registerScene/Item/Rule` a nivel de módulo se conservan como fachada sobre un registro por defecto para no romper el contrato. +2. **`engine-renderer-r3f` aloja lo que depende de React**: `useGameState`, `useGameActions`, `GameViewport` (funcional, no un canvas vacío) y los hooks de orquestación hoy en la demo, que reciben el contenido por inyección en vez de importar `demo-content`. +3. **`apps/web-demo/.../publicApi.ts` se queda como barrel de re-export**. Todos los nombres del contrato v1 siguen importándose desde la misma ruta. Sin cambios breaking. +4. **La escena se registra entera**. Un único helper convierte la config pública en `GameScene`; desaparece la copia campo a campo. +5. **Los tipos de escena de la demo se derivan de los del core**. Lo que solo existe en la demo (`doors`) se modela como extensión explícita hasta que la Fase 7 lo promueva. + +## Alternatives considered + +- **Paquete nuevo `engine-runtime`**: separa mejor, pero añade un tercer paquete en lockstep (ADR-0007) sin beneficio hoy; el runtime no tiene dependencias que el core no tenga ya. +- **Todo en el renderer**: obligaría a un renderer alternativo a reimplementar comandos y registros, contra ADR-0005. +- **Dejarlo en la demo y arreglar solo la doc**: mantiene la librería inutilizable fuera del monorepo. + +## Consequences + +- Versión objetivo: **0.5.0** en ambos paquetes (lockstep). Solo adiciones; el contrato v1 se mantiene. +- Corrección de tipo ya aplicada en la Fase 15: `GameActions.setScene` pasa a `(sceneId: string) => void`, que es lo que la implementación y la guía hacían desde siempre. +- La demo adelgaza: pasa a ser consumidora, que es lo que `CLAUDE.md` exige. +- Riesgo: es un refactor transversal. Se mitiga con la base verde de la Fase 15, tests headless del runtime en core y smoke en navegador en cada ola. + +## Resultado (2026-10-10) + +Implementado en la Fase 16. Dos puntos de la decisión no se aplicaron tal cual: los registros siguen siendo globales de módulo (punto 1) y la demo conserva en el store su escena completa mediante `resolveScene` (punto 4). Ver la retrospectiva de la fase. + +## Requisito de proceso + +`CLAUDE.md` exige issue + migración para tocar `publicApi.ts`. Borrador del issue: + +> **Título**: Mover el runtime (`createGameRuntime`, hooks, `GameViewport`) de la demo a los paquetes +> **Cuerpo**: enlace a este ADR + plan `docs/phases/phase-16-runtime-in-library/`. Migración: ninguna para quien importe desde `publicApi.ts`; quien quiera consumir desde npm podrá importar desde `@pointclick-engine/engine-core` y `@pointclick-engine/engine-renderer-r3f` a partir de 0.5.0. + +## References + +- `docs/phases/phase-16-runtime-in-library/` +- ADR-0005 (renderer ports), ADR-0006 (commands/events), ADR-0007 (release) diff --git a/docs/decisions/0010-declarative-narrative-model.md b/docs/decisions/0010-declarative-narrative-model.md new file mode 100644 index 0000000..e783a52 --- /dev/null +++ b/docs/decisions/0010-declarative-narrative-model.md @@ -0,0 +1,50 @@ +# ADR-0010: Modelo narrativo declarativo (flags, condiciones, acciones) + +**Status**: accepted (aprobado por el owner el 2026-10-10) +**Date**: 2026-10-10 + +## Context + +Tras la Fase 16 el motor mueve un personaje, gestiona inventario, ítems colocados, transiciones, audio e i18n, y es consumible desde los paquetes. Pero no puede expresar una aventura: + +- La única interacción de escena es `kind: "drop-target"`. No hay "mirar", "usar" ni "hablar". +- No hay estado de mundo: nada recuerda que algo ya ocurrió, salvo el inventario y los ítems colocados. +- Los diálogos son frases sueltas elegidas al azar por clave. No hay conversación con opciones ni personajes con los que hablar. +- No hay forma de encadenar "di esto, camina allí, entrega esto, cambia de escena". +- Las reglas propias de un juego se escriben como callbacks de TypeScript (`canLeaveScene`, `onSceneEnter`, `getInitialPlacedItems` en la demo). Funcionan, pero no se pueden guardar, inspeccionar, validar ni replicar por red. +- El guardado son cuatro claves sueltas sin versión. + +## Decision + +1. **El contenido narrativo es dato, no código.** Escenas, hotspots, NPCs, diálogos y reglas se describen con objetos serializables. Un intérprete pequeño en `engine-core` los ejecuta. Ningún `eval`, ninguna función dentro del contenido. +2. **Tres piezas base en el core**: + - **Estado de mundo**: flags con nombre (`boolean | number | string`) en un store reactivo. + - **Condiciones**: un tipo `Condition` evaluable sin efectos (`flag`, `hasItem`, `itemPlaced`, `inScene`, `visited`, `all`, `any`, `not`). + - **Acciones**: un tipo `Action` (`say`, `setFlag`, `giveItem`, `removeItem`, `placeItem`, `removePlacedItem`, `changeScene`, `walkTo`, `wait`, `playSfx`, `startDialogue`, `lockInput`, `emit`, `call`). Un **guion** es `Action[]`; una **rama** es `{ when?: Condition; do: Action[] }` y gana la primera que cumple. +3. **Un secuenciador** ejecuta guiones paso a paso: espera al cierre de un diálogo o al final de una caminata antes de seguir, es cancelable y usa un `ClockPort` inyectado, para que los tests sean deterministas y sin temporizadores reales. +4. **Hotspots con verbos** como elemento nuevo de escena (`scene.hotspots`), separado de `interactions` para no romper las dianas de arrastre existentes. Verbos: `look`, `use`, `talk` y `useItem[itemId]`, cada uno con ramas. +5. **NPCs** como elemento de escena (`scene.npcs`): personaje, posición, condición de visibilidad y diálogo. Se pintan con `CharacterSprite`. +6. **Árboles de diálogo** con nodos, opciones condicionadas y efectos, sobre las claves de i18n existentes. +7. **Combinación de ítems** declarada en el ítem. +8. **Guardado único y versionado**: una instantánea (`escena`, posición, inventario, ítems colocados, flags, escenas visitadas y sembradas) bajo una sola clave, con migración desde las cuatro claves actuales. +9. **Vía de escape explícita**: la acción `call` invoca por nombre un manejador que el host registra. Los callbacks de la Fase 16 se conservan como opciones avanzadas, pero la demo deja de usarlos. +10. **Todo es aditivo** sobre 0.5.0. Versión objetivo 0.6.0. + +## Alternatives considered + +- **Seguir con callbacks de TypeScript**: máxima flexibilidad, pero el estado del juego queda repartido en cierres que no se guardan ni se replican (bloquea el guardado fiable y la Fase 14 de multijugador), y cada juego reimplementa lo mismo. +- **Integrar un lenguaje narrativo externo (Ink, Yarn Spinner)**: resuelve muy bien los diálogos, pero no los hotspots, el inventario ni las transiciones, añade una dependencia y un formato que no es TypeScript. Se puede añadir más adelante como adaptador que genere estos mismos datos. +- **Un lenguaje de scripting propio en texto**: más cómodo de escribir, pero exige parser, mensajes de error y herramientas. Los objetos tipados dan autocompletado y validación gratis. + +## Consequences + +- El contenido se puede validar al arrancar (referencias a ítems, escenas, flags y claves de diálogo inexistentes) y probar en headless: un test puede resolver una aventura entera con comandos. +- El guardado y, más adelante, el multijugador operan sobre un estado explícito. +- Escribir contenido es más verboso que un callback. Se mitiga con funciones constructoras (`say("clave")`, `when(flag("x"), …)`), igual que ya existe `sceneTransitionOnCollision`. +- Los casos que el vocabulario no cubra caen en `call`. Si un `call` se repite en varios juegos, es candidato a acción nueva. +- Fuera de alcance: puertas como primitiva (Fase 7, aunque los flags la simplifican), cinemáticas con cámara, y editor visual. + +## References + +- `docs/phases/phase-17-narrative-primitives/` +- ADR-0006 (commands/events), ADR-0008 (multiplayer), ADR-0009 (runtime en los paquetes) diff --git a/docs/decisions/README.md b/docs/decisions/README.md index afc6258..ac5d48c 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -42,6 +42,8 @@ Cada ADR es **~30 líneas**. Estructura: - [0006 — Command/Event architecture (bidirectional web ↔ game)](0006-command-event-architecture.md) - [0007 — Release strategy (npm scope, versioning, publish process)](0007-release-strategy.md) - [0008 — Multiplayer architecture (agnostic transport + state partition)](0008-multiplayer-architecture.md) +- [0009 — El runtime vive en los paquetes, no en la demo](0009-runtime-lives-in-packages.md) +- [0010 — Modelo narrativo declarativo (flags, condiciones, acciones)](0010-declarative-narrative-model.md) ## Cómo añadir un ADR diff --git a/docs/phases/phase-10-scene-entry-positions-and-pathwalking/README.md b/docs/phases/phase-10-scene-entry-positions-and-pathwalking/README.md index 476725f..3e89bb6 100644 --- a/docs/phases/phase-10-scene-entry-positions-and-pathwalking/README.md +++ b/docs/phases/phase-10-scene-entry-positions-and-pathwalking/README.md @@ -1,6 +1,6 @@ # Phase 10 — Scene Entry Positions & Player Pathwalking -**Status**: In Progress | **Owner**: Daniel Martínez Sebastián | **Version target**: v0.2.0 +**Status**: completed | **Owner**: Daniel Martínez Sebastián | **Version target**: v0.2.0 **Started**: 2026-05-30 diff --git a/docs/phases/phase-11/PLAN_AUDIO_FIXES.md b/docs/phases/phase-11-audio/PLAN_AUDIO_FIXES.md similarity index 100% rename from docs/phases/phase-11/PLAN_AUDIO_FIXES.md rename to docs/phases/phase-11-audio/PLAN_AUDIO_FIXES.md diff --git a/docs/phases/phase-11-audio/README.md b/docs/phases/phase-11-audio/README.md index 6819a0c..8821cc8 100644 --- a/docs/phases/phase-11-audio/README.md +++ b/docs/phases/phase-11-audio/README.md @@ -1,6 +1,6 @@ # Phase 11 — Audio System (música + SFX + mute en inventario) -**Status**: Planned | **Owner**: Daniel Martínez Sebastián | **Version target**: v0.3.0 +**Status**: Completed — gate de validación pendiente (ver Phase 15) | **Owner**: Daniel Martínez Sebastián | **Version target**: v0.3.0 **Planned**: 2026-05-30 diff --git a/docs/phases/phase-11-audio/tracking.md b/docs/phases/phase-11-audio/tracking.md index 89fc1a9..dbb1def 100644 --- a/docs/phases/phase-11-audio/tracking.md +++ b/docs/phases/phase-11-audio/tracking.md @@ -1,81 +1,81 @@ -# Phase 11 — Progress Tracking - -**Phase**: 11 — Audio System -**Status**: Planned -**Started**: — -**Completed**: — - ---- - -## Sprint 1 — Core agnóstico - -- [x] [11.1 — Core types: SoundDefinition + audio fields](tasks/01-core-types.md) -- [x] [11.2 — Core port: AudioPort + HeadlessAudioAdapter](tasks/02-audio-port.md) -- [x] [11.3 — Core state: audioSettingsStore + persistencia](tasks/03-audio-settings-store.md) -- [x] [11.4 — Core commands + events de audio](tasks/04-commands-and-events.md) -- [x] [11.5 — Core: audioRules processor + defaults](tasks/05-audio-rules-processor.md) -- [x] [11.6 — Core tests: store + rules + headless](tasks/06-core-tests.md) - -## Sprint 2 — Platform + renderer - -- [x] [11.7 — Platform: webAudioAdapter](tasks/07-web-audio-adapter.md) -- [x] [11.8 — R3F: useAudioSystem hook](tasks/08-r3f-audio-hook.md) - -## Sprint 3 — UI + demo - -- [x] [11.9 — UI: mute controls en InventoryUI](tasks/09-inventory-mute-controls.md) -- [x] [11.10 — Demo: assets free + wiring](tasks/10-demo-assets-and-wiring.md) - ---- - -## Post-Phase Checklist - -- [ ] All tests passing (`npm run test`) -- [ ] Type-check passing -- [ ] Build passing -- [ ] `grep -r "new Audio\|AudioContext\|window\.\|document\." packages/engine-core/src/` → vacío -- [ ] Backward compatibility: escenas/items sin audio funcionan -- [ ] Persistencia de mute/volumen verificada (recarga manual) -- [ ] Demo: 2+ escenas con música, 1+ ítem con SFX custom, 1+ transición con SFX -- [ ] `LICENSES.md` de audio creado con atribuciones -- [ ] Arquitectura respetada (Core agnóstico, R3F renderer-specific, UI presentación) - ---- - -## Deliverables esperados - -### Core (engine-core) — ~840 LOC -- Types: `SoundDefinition`, `SceneMusicConfig`, `AudioSettings`, `SoundCategory` -- Port: `AudioPort` + `HeadlessAudioAdapter` -- State: `audioSettingsStore` + storage adapter integration -- Commands: `audio:playSfx`, `audio:setMuted`, `audio:setVolume` -- Events: `audio:sfxRequested`, `audio:musicRequested`, `audio:musicStopped`, `audio:settingsChanged` -- Rules processor: `audioRules.ts` + `AudioDefaultsConfig` -- Tests: ≥30 tests nuevos - -### Renderer R3F (engine-renderer-r3f) — ~150 LOC -- Hook: `useAudioSystem(runtime, adapter, defaults)` -- Suscripción a eventos del runtime → reproducción vía port -- Integración en `GameTouchSpriteRuntime` - -### Platform (web-demo) — ~220 LOC -- `webAudioAdapter` en `platform-web.ts` -- Manejo de fade in/out, pooling de instancias, autoplay-policy - -### UI (web-demo) — ~120 LOC -- Tres toggles en `InventoryUI` (master / música / SFX) -- Estado leído del store, despachan commands - -### Demo content — ~80 LOC + assets -- Música configurada en `town`, `dungeon`, `personalRoom` -- SFX custom para al menos un ítem (ej. `gameboy` pickup) -- SFX de transición en al menos una puerta -- `apps/web-demo/public/assets/audio/LICENSES.md` - ---- - -## Timeline (a rellenar al ejecutar) - -| Fecha | Task | Status | -|------|------|--------| -| 2026-05-30 | Plan creado | ⏳ | +# Phase 11 — Progress Tracking + +**Phase**: 11 — Audio System +**Status**: Completed — gate de validación pendiente (ver Phase 15) +**Started**: — +**Completed**: — + +--- + +## Sprint 1 — Core agnóstico + +- [x] [11.1 — Core types: SoundDefinition + audio fields](tasks/01-core-types.md) +- [x] [11.2 — Core port: AudioPort + HeadlessAudioAdapter](tasks/02-audio-port.md) +- [x] [11.3 — Core state: audioSettingsStore + persistencia](tasks/03-audio-settings-store.md) +- [x] [11.4 — Core commands + events de audio](tasks/04-commands-and-events.md) +- [x] [11.5 — Core: audioRules processor + defaults](tasks/05-audio-rules-processor.md) +- [x] [11.6 — Core tests: store + rules + headless](tasks/06-core-tests.md) + +## Sprint 2 — Platform + renderer + +- [x] [11.7 — Platform: webAudioAdapter](tasks/07-web-audio-adapter.md) +- [x] [11.8 — R3F: useAudioSystem hook](tasks/08-r3f-audio-hook.md) + +## Sprint 3 — UI + demo + +- [x] [11.9 — UI: mute controls en InventoryUI](tasks/09-inventory-mute-controls.md) +- [x] [11.10 — Demo: assets free + wiring](tasks/10-demo-assets-and-wiring.md) + +--- + +## Post-Phase Checklist + +- [x] All tests passing (`npm run test`) +- [x] Type-check passing +- [x] Build passing +- [x] `grep -r "new Audio\|AudioContext\|window\.\|document\." packages/engine-core/src/` → vacío +- [ ] Backward compatibility: escenas/items sin audio funcionan — _sin verificar en navegador_ +- [ ] Persistencia de mute/volumen verificada (recarga manual) — _sin verificar en navegador_ +- [x] Demo: 2+ escenas con música, 1+ ítem con SFX custom, 1+ transición con SFX — _validado 2026-10-10 por `npm run smoke` tras la tarea 16.07b: música por escena, `pickup-gameboy.ogg` declarado en el ítem, sonido de transición_ +- [x] `LICENSES.md` de audio creado con atribuciones +- [x] Arquitectura respetada (Core agnóstico, R3F renderer-specific, UI presentación) — _la demo usa `useAudioSystem` desde la tarea 16.07b_ + +--- + +## Deliverables esperados + +### Core (engine-core) — ~840 LOC +- Types: `SoundDefinition`, `SceneMusicConfig`, `AudioSettings`, `SoundCategory` +- Port: `AudioPort` + `HeadlessAudioAdapter` +- State: `audioSettingsStore` + storage adapter integration +- Commands: `audio:playSfx`, `audio:setMuted`, `audio:setVolume` +- Events: `audio:sfxRequested`, `audio:musicRequested`, `audio:musicStopped`, `audio:settingsChanged` +- Rules processor: `audioRules.ts` + `AudioDefaultsConfig` +- Tests: ≥30 tests nuevos + +### Renderer R3F (engine-renderer-r3f) — ~150 LOC +- Hook: `useAudioSystem(runtime, adapter, defaults)` +- Suscripción a eventos del runtime → reproducción vía port +- Integración en `GameTouchSpriteRuntime` + +### Platform (web-demo) — ~220 LOC +- `webAudioAdapter` en `platform-web.ts` +- Manejo de fade in/out, pooling de instancias, autoplay-policy + +### UI (web-demo) — ~120 LOC +- Tres toggles en `InventoryUI` (master / música / SFX) +- Estado leído del store, despachan commands + +### Demo content — ~80 LOC + assets +- Música configurada en `town`, `dungeon`, `personalRoom` +- SFX custom para al menos un ítem (ej. `gameboy` pickup) +- SFX de transición en al menos una puerta +- `apps/web-demo/public/assets/audio/LICENSES.md` + +--- + +## Timeline (a rellenar al ejecutar) + +| Fecha | Task | Status | +|------|------|--------| +| 2026-05-30 | Plan creado | ⏳ | diff --git a/docs/phases/phase-12-architecture-cleanup/README.md b/docs/phases/phase-12-architecture-cleanup/README.md index adec310..5e9047e 100644 --- a/docs/phases/phase-12-architecture-cleanup/README.md +++ b/docs/phases/phase-12-architecture-cleanup/README.md @@ -1,6 +1,6 @@ # Phase 12 — Architecture Cleanup: Core Agnosticism & Library Boundaries -**Status**: Planned | **Owner**: Daniel Martínez Sebastián | **Version target**: v0.2.0 +**Status**: Completed — gate de validación pendiente (ver Phase 15) | **Owner**: Daniel Martínez Sebastián | **Version target**: v0.2.0 **Planned**: 2026-05-31 --- diff --git a/docs/phases/phase-12-architecture-cleanup/tracking.md b/docs/phases/phase-12-architecture-cleanup/tracking.md index 65399fa..bf1f306 100644 --- a/docs/phases/phase-12-architecture-cleanup/tracking.md +++ b/docs/phases/phase-12-architecture-cleanup/tracking.md @@ -1,75 +1,75 @@ -# Phase 12 — Progress Tracking - -**Phase**: 12 — Architecture Cleanup: Core Agnosticism & Library Boundaries -**Status**: Planned -**Started**: — -**Completed**: — - ---- - -## Sprint 1 — Core agnosticism (sin riesgo de romper demo) - -- [x] [12.1 — Core: eliminar window.__gameTrace, LogPort opcional](tasks/01-remove-window-trace-scenestore.md) -- [x] [12.2 — publicApi: completar tipos audio (GameItemRule, GameItemConfig, GameItemDropOutcome)](tasks/02-fix-publicapi-type-gaps.md) - -## Sprint 2 — Desacoplar demo de hooks del engine - -- [x] [12.3 — useTransitionSystem: eliminar import SCENES, aceptar resolveScene callback](tasks/03-decouple-transition-system-from-scenes.md) -- [x] [12.4 — publicApi: eliminar imports de demo stores, DI para inventory + dialog](tasks/04-remove-demo-store-imports-from-publicapi.md) - -## Sprint 3 — Extraer hooks genéricos al renderer - -- [x] [12.5 — engine-renderer-r3f: mover useClickToMoveController](tasks/05-extract-click-to-move-to-renderer.md) -- [x] [12.6 — engine-renderer-r3f: mover useKeyboardMovementInput](tasks/06-extract-keyboard-input-to-renderer.md) - -## Sprint 4 — Separar GameViewport de GameTouchCanvas - -- [x] [12.7 — engine-renderer-r3f: extraer GameCanvasCore; publicApi no importa demo](tasks/07-split-gameviewport-gamecanvascore.md) - -## Sprint 5 — Tests de consolidación - -- [x] [12.8 — Tests: LogPort, transitionSystem, hooks renderer, publicApi DI contract](tasks/08-tests-consolidation.md) - ---- - -## Post-Phase Checklist - -- [ ] Todos los tests pasan (`npm run test` en root) -- [ ] Type-check limpio en `packages/engine-core` y `packages/engine-renderer-r3f` -- [ ] `grep -rn "window\.\|document\." packages/engine-core/src/` → vacío -- [ ] `publicApi.ts` sin imports de `../../store/` ni `../../components/` -- [ ] `useTransitionSystem` sin import de `demo-content` -- [ ] `engine-renderer-r3f` exporta `useClickToMoveController` y `WebKeyboardInput` -- [ ] Demo funciona end-to-end (manual smoke test) -- [ ] ≥ 20 tests nuevos añadidos - ---- - -## Deliverables esperados - -### Core (engine-core) — ~75 LOC neto -- `logSceneStore` depende de `console.info` únicamente; sin `window` -- Tipos `GameItemRule`, `GameItemConfig`, `GameItemDropOutcome` completos en publicApi - -### Runtime hooks (web-demo/lib/engine) — ~95 LOC neto -- `useTransitionSystem` sin import de SCENES -- `publicApi.ts` acepta `{ inventoryAdapter, dialogAdapter }` en lugar de importar stores - -### Renderer (engine-renderer-r3f) — ~260 LOC (moves + new exports) -- `useClickToMoveController` exportado desde el package -- `WebKeyboardInput` / `useKeyboardMovementInput` exportado desde el package -- `GameCanvasCore` como componente R3F genérico (sin demo content) - -### Tests — ~200 LOC -- `packages/engine-core/__tests__/sceneStoreAgnosticism.test.ts` -- `packages/engine-renderer-r3f/src/__tests__/useClickToMoveController.test.ts` -- `packages/engine-renderer-r3f/src/__tests__/useKeyboardMovementInput.test.ts` -- `apps/web-demo/app/lib/engine/publicApi.di.test.ts` - ---- - -## Timeline - -| Fecha | Task | Status | -|-------|------|--------| -| 2026-05-31 | Plan creado | ⏳ | +# Phase 12 — Progress Tracking + +**Phase**: 12 — Architecture Cleanup: Core Agnosticism & Library Boundaries +**Status**: Completed — gate de validación pendiente (ver Phase 15) +**Started**: — +**Completed**: — + +--- + +## Sprint 1 — Core agnosticism (sin riesgo de romper demo) + +- [x] [12.1 — Core: eliminar window.__gameTrace, LogPort opcional](tasks/01-remove-window-trace-scenestore.md) +- [x] [12.2 — publicApi: completar tipos audio (GameItemRule, GameItemConfig, GameItemDropOutcome)](tasks/02-fix-publicapi-type-gaps.md) + +## Sprint 2 — Desacoplar demo de hooks del engine + +- [x] [12.3 — useTransitionSystem: eliminar import SCENES, aceptar resolveScene callback](tasks/03-decouple-transition-system-from-scenes.md) +- [x] [12.4 — publicApi: eliminar imports de demo stores, DI para inventory + dialog](tasks/04-remove-demo-store-imports-from-publicapi.md) + +## Sprint 3 — Extraer hooks genéricos al renderer + +- [x] [12.5 — engine-renderer-r3f: mover useClickToMoveController](tasks/05-extract-click-to-move-to-renderer.md) +- [x] [12.6 — engine-renderer-r3f: mover useKeyboardMovementInput](tasks/06-extract-keyboard-input-to-renderer.md) + +## Sprint 4 — Separar GameViewport de GameTouchCanvas + +- [x] [12.7 — engine-renderer-r3f: extraer GameCanvasCore; publicApi no importa demo](tasks/07-split-gameviewport-gamecanvascore.md) + +## Sprint 5 — Tests de consolidación + +- [x] [12.8 — Tests: LogPort, transitionSystem, hooks renderer, publicApi DI contract](tasks/08-tests-consolidation.md) + +--- + +## Post-Phase Checklist + +- [x] Todos los tests pasan (`npm run test` en root) +- [x] Type-check limpio en `packages/engine-core` y `packages/engine-renderer-r3f` +- [x] `grep -rn "window\.\|document\." packages/engine-core/src/` → vacío +- [x] `publicApi.ts` sin imports de `../../store/` ni `../../components/` +- [x] `useTransitionSystem` sin import de `demo-content` +- [x] `engine-renderer-r3f` exporta `useClickToMoveController` y `WebKeyboardInput` +- [x] Demo funciona end-to-end (manual smoke test) — _verificado a mano por el owner, 2026-10-10 (intro, movimiento, ítems, transición, puerta, audio, idioma)_ +- [x] ≥ 20 tests nuevos añadidos + +--- + +## Deliverables esperados + +### Core (engine-core) — ~75 LOC neto +- `logSceneStore` depende de `console.info` únicamente; sin `window` +- Tipos `GameItemRule`, `GameItemConfig`, `GameItemDropOutcome` completos en publicApi + +### Runtime hooks (web-demo/lib/engine) — ~95 LOC neto +- `useTransitionSystem` sin import de SCENES +- `publicApi.ts` acepta `{ inventoryAdapter, dialogAdapter }` en lugar de importar stores + +### Renderer (engine-renderer-r3f) — ~260 LOC (moves + new exports) +- `useClickToMoveController` exportado desde el package +- `WebKeyboardInput` / `useKeyboardMovementInput` exportado desde el package +- `GameCanvasCore` como componente R3F genérico (sin demo content) + +### Tests — ~200 LOC +- `packages/engine-core/__tests__/sceneStoreAgnosticism.test.ts` +- `packages/engine-renderer-r3f/src/__tests__/useClickToMoveController.test.ts` +- `packages/engine-renderer-r3f/src/__tests__/useKeyboardMovementInput.test.ts` +- `apps/web-demo/app/lib/engine/publicApi.di.test.ts` + +--- + +## Timeline + +| Fecha | Task | Status | +|-------|------|--------| +| 2026-05-31 | Plan creado | ⏳ | diff --git a/docs/phases/phase-13-i18n/README.md b/docs/phases/phase-13-i18n/README.md index 22dec8b..242cceb 100644 --- a/docs/phases/phase-13-i18n/README.md +++ b/docs/phases/phase-13-i18n/README.md @@ -1,6 +1,6 @@ # Phase 13 — i18n / Localization System (core + R3F + demo) -**Status**: Planned | **Owner**: Daniel Martínez Sebastián | **Version target**: v0.4.0 +**Status**: Completed — gate de validación pendiente (ver Phase 15) | **Owner**: Daniel Martínez Sebastián | **Version target**: v0.4.0 **Planned**: 2026-05-31 diff --git a/docs/phases/phase-13-i18n/tracking.md b/docs/phases/phase-13-i18n/tracking.md index e897163..b34fc11 100644 --- a/docs/phases/phase-13-i18n/tracking.md +++ b/docs/phases/phase-13-i18n/tracking.md @@ -1,7 +1,7 @@ # Phase 13 — Progress Tracking **Phase**: 13 — i18n / Localization System -**Status**: Completed +**Status**: Completed — gate de validación pendiente (ver Phase 15) **Started**: 2026-05-31 **Completed**: 2026-05-31 @@ -32,17 +32,17 @@ ## Post-Phase Checklist -- [ ] All tests passing (`npm run test`) -- [ ] Type-check passing -- [ ] Build passing (incluido `apps/web-demo` en modo Next.js build) -- [ ] `grep -rE "navigator\.|localStorage|document\.|cookies|next/|next-intl" packages/engine-core/src/` → vacío -- [ ] `grep -rE "navigator\.|localStorage|document\.|cookies|next/|next-intl" packages/engine-renderer-r3f/src/` → vacío (los hooks NO consumen browser globals directamente) -- [ ] Backward compatibility: `apps/web-demo/demo-content/dialogs/getRandomPhrase.ts` legacy wrapper sigue funcionando -- [ ] Persistencia del locale verificada (recarga manual mantiene elección) -- [ ] Detección automática verificada (browser en `en-*` arranca en `en`; resto arranca en `es`) -- [ ] `` montado en `InventoryUI` cambia el idioma del speech bubble en vivo -- [ ] 3 recetas Next.js documentadas y enlazadas desde el README de la fase -- [ ] Arquitectura respetada (Core agnóstico, R3F renderer-specific, Platform en demo) +- [x] All tests passing (`npm run test`) +- [x] Type-check passing +- [x] Build passing (incluido `apps/web-demo` en modo Next.js build) +- [x] `grep -rE "navigator\.|localStorage|document\.|cookies|next/|next-intl" packages/engine-core/src/` → vacío +- [x] `grep -rE "navigator\.|localStorage|document\.|cookies|next/|next-intl" packages/engine-renderer-r3f/src/` → vacío (los hooks NO consumen browser globals directamente) +- [x] Backward compatibility: `apps/web-demo/demo-content/dialogs/getRandomPhrase.ts` legacy wrapper sigue funcionando +- [x] Persistencia del locale verificada (recarga manual mantiene elección) — _verificado a mano por el owner, 2026-10-10_ +- [ ] Detección automática verificada (browser en `en-*` arranca en `en`; resto arranca en `es`) — _sin verificar en navegador_ +- [x] `` montado en `InventoryUI` cambia el idioma del speech bubble en vivo — _verificado a mano por el owner, 2026-10-10_ +- [ ] 3 recetas Next.js documentadas y enlazadas desde el README de la fase — _documentadas en docs/integrations/nextjs-i18n.md; falta el enlace desde el README de la fase_ +- [x] Arquitectura respetada (Core agnóstico, R3F renderer-specific, Platform en demo) --- diff --git a/docs/phases/phase-15-green-baseline/README.md b/docs/phases/phase-15-green-baseline/README.md new file mode 100644 index 0000000..3a21734 --- /dev/null +++ b/docs/phases/phase-15-green-baseline/README.md @@ -0,0 +1,70 @@ +# Phase 15 — Green Baseline + +**Objetivo**: dejar el repo en verde verificable (tests, type-check, lint, build, CI) y la doc alineada con el código, antes de tocar arquitectura. +**Duración estimada**: 2–3 días +**Estado**: completed (2026-10-10) +**Owner**: Daniel Martínez Sebastián +**Version target**: v0.4.1 (sin cambios de API salvo un fix de tipo, ver tarea 01) + +--- + +## Por qué + +Auditoría del 2026-10-10 (medido, no estimado): + +| Comprobación | Resultado | +|---|---| +| `engine-core` tests | 244/244 ✅ | +| `engine-renderer-r3f` tests | 61/66 — 5 fallan en `useAudioSystem.test.tsx` | +| `web-demo` tests | 46/50 — 4 fallan en `publicApi.test.ts` | +| `tsc --noEmit` demo | 10 errores (solo en tests) | +| `eslint` demo | 11 errores, 9 warnings | +| `next build` | ✅ | +| CI | no existe | +| `dist/` | versionado (260 archivos) y desfasado respecto a `src` en 9 | +| Docs | fases 6, 8, 10–13 con estado erróneo; 28 checks de gate sin validar | + +Sin una base verde no se puede validar la Fase 16 (mover el runtime a la librería). + +## Resultado esperado + +Desde la raíz, todo esto termina con código 0: + +```bash +npm run build -w packages/engine-core -w packages/engine-renderer-r3f +npm test +npx tsc --noEmit -p packages/engine-core +npx tsc --noEmit -p packages/engine-renderer-r3f +npx tsc --noEmit -p apps/web-demo +npm run lint +npm run build +``` + +Y además: CI en GitHub Actions ejecutándolo, `dist/` fuera de git, docs sincronizadas. + +## Tareas y reparto + +Los archivos de cada tarea son **disjuntos**: las tareas 01–06 y 08 corren en paralelo. + +| # | Tarea | Modelo | Capa | +|---|---|---|---| +| 01 | [Arreglar tests de contrato de publicApi](tasks/01-fix-publicapi-contract-tests.md) | sonnet | demo | +| 02 | [Arreglar tests de useAudioSystem](tasks/02-fix-audio-system-tests.md) | sonnet | renderer | +| 03 | [Lint: errores de reglas React](tasks/03-lint-react-rules.md) | sonnet | demo | +| 04 | [Lint: `any` e imports sin usar](tasks/04-lint-trivial.md) | haiku | demo | +| 05 | [Core: guarda de `process.env`](tasks/05-core-node-env-guard.md) | haiku | core | +| 06 | [Workflow de CI](tasks/06-ci-workflow.md) | haiku | tooling | +| 07 | [Sacar `dist/` de git](tasks/07-untrack-dist.md) | opus (orquestador) | tooling | +| 08 | [Resincronizar docs](tasks/08-docs-resync.md) | haiku | docs | +| 09 | [Gate de validación](tasks/09-validation-gate.md) | opus (orquestador) | todas | + +## Reglas para todas las tareas + +- **No hacer commit ni tocar el índice de git** (salvo `git mv`/`git rm` que la tarea pida). El orquestador integra y commitea. +- Tocar **solo** los archivos listados en la tarea. Si hace falta otro, parar y reportarlo. +- No arreglar un test debilitando la aserción: si el test describe un comportamiento que ya no existe, se reescribe para el comportamiento actual y se explica en el reporte. +- Regla de Oro: `packages/engine-core` nunca importa React/R3F/Next/`window`/`document`. + +## Fuera de alcance + +Mover `createGameRuntime` a un paquete, borrar duplicados, primitivas narrativas → Fase 16 en adelante. diff --git a/docs/phases/phase-15-green-baseline/tasks/01-fix-publicapi-contract-tests.md b/docs/phases/phase-15-green-baseline/tasks/01-fix-publicapi-contract-tests.md new file mode 100644 index 0000000..337dc5f --- /dev/null +++ b/docs/phases/phase-15-green-baseline/tasks/01-fix-publicapi-contract-tests.md @@ -0,0 +1,50 @@ +# Task 15.01 — Arreglar tests de contrato de publicApi + +**Effort**: 1.5h | **Modelo**: sonnet | **Blocks**: 09 | **Blocked by**: — + +**Archivos permitidos** (ningún otro): +- `apps/web-demo/app/lib/engine/publicApi.test.ts` +- `apps/web-demo/app/lib/engine/publicApi.ts` (solo el tipo `GameActions`) +- `apps/web-demo/app/lib/core/rules/inventoryRules.test.ts` + +--- + +## 🎯 Objetivo + +4 tests fallan y hay 10 errores de `tsc`, todos en tests que quedaron desfasados cuando la tarea 12.4 sustituyó los imports de stores de la demo por adapters inyectados. + +## Diagnóstico + +1. **4 tests rojos** en `describe("publicApi — wired commands (Phase 5)")`: llaman a `createGameRuntime()` sin `inventoryAdapter` ni `dialogAdapter` y luego esperan cambios en `useInventoryStore` / `useDialogStore`. Sin adapter el comando es no-op por diseño. +2. **TS2554 "Expected 2-3 arguments, but got 1"** (líneas 98, 109): `GameActions` es `Pick`, así que el tipo exige `setScene(id, scene)`, pero la implementación y `docs/LIBRARY_CONSUMPTION_GUIDE.md` usan `setScene(id)`. El tipo está mal, no el test. +3. **TS2345** (líneas 87, 105, 118): `Object.values(SCENES).forEach(registerScene)` — el tipo `Scene` de la demo tiene `rotationY?` opcional y `GameSceneWall` lo exige. La deduplicación de tipos es de la Fase 16; aquí se usa el mismo cast que ya hace `app/page.tsx`. +4. **TS2339 "on type 'never'"** (líneas 131–136): `actionsFromHook` se asigna dentro de un closure y TS lo estrecha a `null`. +5. **TS2322** en `inventoryRules.test.ts:66`: `kind: "drop-target"` se ensancha a `string`. + +## 📝 Instructions + +1. En `publicApi.ts`, reemplazar el tipo `GameActions` por uno explícito que coincida con la implementación: + ```ts + export type GameActions = { + setScene: (sceneId: string) => void; + setPlayerPosition: SceneStoreSnapshot["setPlayerPosition"]; + requestRespawn: SceneStoreSnapshot["requestRespawn"]; + }; + ``` + No cambiar nada más de ese archivo. +2. En los 4 tests rojos, crear el runtime con adapters que escriban en los stores de la demo (mismo cableado que `app/page.tsx`). Mantener las aserciones tal cual. +3. Añadir 2 tests nuevos del contrato DI: sin adapters, `inventory:toggle` y `dialog:trigger` no lanzan y `dialog:trigger` sigue emitiendo `dialog:triggered`. +4. Resolver los TS2345 con `Object.values(SCENES) as GameSceneConfig[]`. +5. Resolver los "never" tipando el holder como objeto (`const holder: { actions: GameActions | null } = { actions: null }`). +6. En `inventoryRules.test.ts`, `kind: "drop-target" as const` (o tipar el literal). + +## ✅ Success Criteria + +- [ ] `cd apps/web-demo && npx vitest run` → 0 fallos, y al menos 52 tests. +- [ ] `npx tsc --noEmit -p apps/web-demo` → 0 errores. +- [ ] Ninguna aserción existente eliminada ni relajada. +- [ ] `git diff --stat` solo muestra los 3 archivos permitidos. + +## Reporte + +Lista de cambios, salida final de los dos comandos, y cualquier cosa sospechosa vista de paso (sin arreglarla). diff --git a/docs/phases/phase-15-green-baseline/tasks/02-fix-audio-system-tests.md b/docs/phases/phase-15-green-baseline/tasks/02-fix-audio-system-tests.md new file mode 100644 index 0000000..9d78e00 --- /dev/null +++ b/docs/phases/phase-15-green-baseline/tasks/02-fix-audio-system-tests.md @@ -0,0 +1,49 @@ +# Task 15.02 — Arreglar tests de useAudioSystem + +**Effort**: 2h | **Modelo**: sonnet | **Blocks**: 09, 16.07 | **Blocked by**: — + +**Archivos permitidos** (ningún otro): +- `packages/engine-renderer-r3f/src/hooks/useAudioSystem.ts` +- `packages/engine-renderer-r3f/src/hooks/attachAudioSystem.ts` (nuevo) +- `packages/engine-renderer-r3f/src/__tests__/useAudioSystem.test.tsx` (puede renombrarse a `attachAudioSystem.test.ts`) +- `packages/engine-renderer-r3f/src/index.ts` (solo añadir el export nuevo) + +--- + +## 🎯 Objetivo + +Los 5 tests de `useAudioSystem.test.tsx` fallan con `Cannot read properties of null (reading 'useRef')`: el test invoca el hook como función normal, fuera de un render de React. No hay `@testing-library/react` ni `jsdom` en el paquete, y no se van a añadir. + +## Decisión de diseño (ya tomada) + +Separar la lógica del hook. Todo lo que hoy ocurre dentro del `useEffect` pasa a una función pura sin React: + +```ts +// hooks/attachAudioSystem.ts — sin imports de "react" +export interface AttachAudioSystemOpts { /* los mismos campos que UseAudioSystemOpts */ } +/** Suscribe el puerto de audio a los eventos del runtime. Devuelve la función de limpieza. */ +export function attachAudioSystem(opts: AttachAudioSystemOpts): () => void +``` + +`useAudioSystem` queda como envoltorio fino: `useEffect(() => attachAudioSystem(opts), [...])`. El estado que hoy vive en `previousMusicRef` pasa a ser una variable del closure de `attachAudioSystem`. + +## 📝 Instructions + +1. Leer `useAudioSystem.ts` completo y `packages/engine-core/src/game/logic/rules/audioRules.ts` (solo lectura) para entender `resolveAudioEvents`. +2. Crear `attachAudioSystem.ts` moviendo la lógica. Mismo comportamiento observable: mismas suscripciones, mismas llamadas al `AudioPort`, misma limpieza. +3. Reducir `useAudioSystem.ts` al envoltorio. Conservar su firma pública y sus dependencias de efecto. +4. Reescribir los tests contra `attachAudioSystem` (sin React). Conservar los 5 escenarios actuales y sus aserciones; añadir uno que verifique que la función de limpieza desuscribe (tras llamarla, emitir un evento no genera llamadas al adapter). +5. Exportar `attachAudioSystem` y su tipo de opciones desde `src/index.ts`. +6. De paso, quitar los `as any` del test si el tipado lo permite sin forzar. + +## ✅ Success Criteria + +- [ ] `cd packages/engine-renderer-r3f && npx vitest run` → 0 fallos, ≥ 67 tests. +- [ ] `npx tsc --noEmit -p packages/engine-renderer-r3f` → 0 errores. +- [ ] `grep -n "from \"react\"" packages/engine-renderer-r3f/src/hooks/attachAudioSystem.ts` → vacío. +- [ ] `useAudioSystem` sigue exportado con la misma firma. +- [ ] `git diff --stat` solo muestra archivos permitidos. + +## Reporte + +Cambios, salida de los comandos, y si detectas que algún escenario del test original nunca pudo pasar por un bug real del hook (no del test), descríbelo sin arreglarlo fuera de alcance. diff --git a/docs/phases/phase-15-green-baseline/tasks/03-lint-react-rules.md b/docs/phases/phase-15-green-baseline/tasks/03-lint-react-rules.md new file mode 100644 index 0000000..6aef2b0 --- /dev/null +++ b/docs/phases/phase-15-green-baseline/tasks/03-lint-react-rules.md @@ -0,0 +1,47 @@ +# Task 15.03 — Lint: errores de reglas React + +**Effort**: 2.5h | **Modelo**: sonnet | **Blocks**: 09 | **Blocked by**: — + +**Archivos permitidos** (ningún otro): +- `apps/web-demo/app/components/GameTouchCanvas.tsx` +- `apps/web-demo/app/components/debug/FloatingPanel.tsx` +- `apps/web-demo/app/components/intro/IntroScene.tsx` +- `apps/web-demo/app/lib/engine/runtime/useInventoryRuntimeController.ts` + +--- + +## 🎯 Objetivo + +Eliminar los 7 errores de ESLint que afectan a comportamiento en runtime. Son cambios sensibles: cada uno debe conservar el comportamiento observable. + +## Errores a resolver + +| Archivo:línea | Regla | Qué pasa | +|---|---|---| +| `GameTouchCanvas.tsx:212` | `no-explicit-any` | `useRef` para el estado de caminata previo → tipar con `PlayerWalkingState \| null` de `@pointclick-engine/engine-core` | +| `GameTouchCanvas.tsx:236` | `no-explicit-any` | handler de `item:dropped` con `event: any` → usar el tipo del evento; ojo: el código compara `event.outcome === "pickup-success"`, valor que el tipo `GameEvent` de `item:dropped` no declara. **No cambies el tipo del core**; estrecha localmente y deja constancia en el reporte | +| `GameTouchCanvas.tsx:287` | `react-hooks/use-memo` | `useCallback(wrap(fn), deps)` no recibe función inline → usar `useMemo(() => wrapRuntimeEventForTransitions(...), [deps])` | +| `FloatingPanel.tsx:58` | `react-hooks/set-state-in-effect` | sincroniza estado local desde el store dentro de un efecto | +| `IntroScene.tsx:81–82` | `react-hooks/refs` | escribe refs durante el render | +| `useInventoryRuntimeController.ts:157` | `react-hooks/set-state-in-effect` | `setPlacedItems` síncrono dentro de un efecto al cambiar de escena | + +Además, en `useInventoryRuntimeController.ts:6` quitar el import sin usar `getGameRuntime`. + +## 📝 Instructions + +1. Para cada error, leer la función entera antes de tocar: entender por qué existe el patrón. +2. Preferir la solución idiomática (derivar estado en render, `key` para resetear, mover la escritura del ref a un efecto o handler, patrón "ajustar estado al cambiar una prop"). +3. Solo si la reescritura idiomática cambia el comportamiento o exige tocar otros archivos, usar `// eslint-disable-next-line -- ` en esa línea. Cada disable debe justificarse en el reporte. Máximo 2 disables en total. +4. No tocar los warnings `exhaustive-deps` ni `no-img-element`: cambiar dependencias de efectos sin pruebas visuales es más arriesgado que el warning. +5. No reformatear ni refactorizar nada que no esté en la tabla. + +## ✅ Success Criteria + +- [ ] `cd apps/web-demo && npx eslint app/components/GameTouchCanvas.tsx app/components/debug/FloatingPanel.tsx app/components/intro/IntroScene.tsx app/lib/engine/runtime/useInventoryRuntimeController.ts` → 0 errores. +- [ ] `npx tsc --noEmit -p apps/web-demo` no añade errores nuevos en estos 4 archivos. +- [ ] `cd apps/web-demo && npx vitest run` no empeora (los 4 fallos previos de `publicApi.test.ts` los arregla otra tarea). +- [ ] `git diff --stat` solo muestra los 4 archivos permitidos. + +## Reporte + +Por cada error: solución aplicada y por qué conserva el comportamiento. Lista de disables con motivo. Riesgos que el orquestador deba comprobar en navegador (intro, panel flotante de debug, ítems colocados al cambiar de escena, sonido al soltar ítems). diff --git a/docs/phases/phase-15-green-baseline/tasks/04-lint-trivial.md b/docs/phases/phase-15-green-baseline/tasks/04-lint-trivial.md new file mode 100644 index 0000000..d551e8c --- /dev/null +++ b/docs/phases/phase-15-green-baseline/tasks/04-lint-trivial.md @@ -0,0 +1,45 @@ +# Task 15.04 — Lint: `any` e imports sin usar + +**Effort**: 45min | **Modelo**: haiku | **Blocks**: 09 | **Blocked by**: — + +**Archivos permitidos** (ningún otro): +- `apps/web-demo/app/lib/engine/runtime/useTransitionSystem.ts` +- `apps/web-demo/app/lib/platform-web-audio.test.ts` +- `apps/web-demo/app/lib/platform-web-audio.ts` +- `apps/web-demo/app/page.tsx` + +--- + +## 🎯 Objetivo + +Quitar 4 errores y 3 warnings de ESLint puramente mecánicos. Cero cambios de comportamiento. + +## Lista exacta + +| Archivo:línea | Problema | Arreglo | +|---|---|---| +| `useTransitionSystem.ts:9` | `getRandomPhrase` importado y no usado | quitar del import | +| `useTransitionSystem.ts:174` | `any` | sustituir por el tipo real (lee el contexto; probablemente `RuntimeEvent` de `@pointclick-engine/engine-core`) | +| `useTransitionSystem.ts:177` | `any` | ídem | +| `platform-web-audio.test.ts:45` | `any` | tipar el mock con `unknown` + estrechamiento, o con una interfaz mínima local | +| `platform-web-audio.test.ts:58` | `any` | ídem | +| `platform-web-audio.ts:257` | `timeout` asignado y no usado | si el valor no se necesita, no asignarlo; **si es un `setTimeout` que debería limpiarse, no lo toques y repórtalo** | +| `page.tsx:3` | `useMemo` importado y no usado | quitar del import | + +## 📝 Instructions + +1. Abrir cada archivo en la línea indicada y leer ±20 líneas de contexto. +2. Aplicar el arreglo de la tabla. No usar `eslint-disable`. No usar `as any` ni `as unknown as X` salvo que ya existiera. +3. Si un `any` no se puede tipar sin cambiar otros archivos, déjalo y repórtalo. +4. No reformatear, no renombrar, no "mejorar" nada más. + +## ✅ Success Criteria + +- [ ] `cd apps/web-demo && npx eslint app/lib/engine/runtime/useTransitionSystem.ts app/lib/platform-web-audio.test.ts app/lib/platform-web-audio.ts app/page.tsx` → 0 errores y 0 warnings. +- [ ] `cd apps/web-demo && npx vitest run app/lib/platform-web-audio.test.ts` → todo pasa. +- [ ] `npx tsc --noEmit -p apps/web-demo` no añade errores en estos 4 archivos. +- [ ] `git diff --stat` solo muestra los 4 archivos permitidos. + +## Reporte + +Diff resumido por archivo y salida de los comandos. Lista de lo que no pudiste arreglar y por qué. diff --git a/docs/phases/phase-15-green-baseline/tasks/05-core-node-env-guard.md b/docs/phases/phase-15-green-baseline/tasks/05-core-node-env-guard.md new file mode 100644 index 0000000..198d200 --- /dev/null +++ b/docs/phases/phase-15-green-baseline/tasks/05-core-node-env-guard.md @@ -0,0 +1,45 @@ +# Task 15.05 — Core: guarda de `process.env` + +**Effort**: 30min | **Modelo**: haiku | **Blocks**: 09 | **Blocked by**: — + +**Archivos permitidos** (ningún otro): +- `packages/engine-core/src/game/state/sceneStore.ts` (solo la línea de `SHOULD_LOG_STATE_TRANSITIONS`) +- `packages/engine-core/src/__tests__/coreAgnosticism.test.ts` (nuevo) + +--- + +## 🎯 Objetivo + +`sceneStore.ts:32` lee `process.env.NODE_ENV` sin comprobar que `process` exista: + +```ts +const SHOULD_LOG_STATE_TRANSITIONS = process.env.NODE_ENV !== "production"; +``` + +En un entorno sin bundler (ESM directo en navegador) eso lanza `ReferenceError` al importar el core. Los otros dos usos del core ya llevan guarda (`game/i18n/registry.ts:9`, `game/state/i18nStore.ts:45`). + +## 📝 Instructions + +1. Cambiar la línea para usar la misma guarda que `i18nStore.ts:45`: + ```ts + const SHOULD_LOG_STATE_TRANSITIONS = + typeof process !== "undefined" && process.env?.NODE_ENV !== "production"; + ``` +2. Crear `packages/engine-core/src/__tests__/coreAgnosticism.test.ts` con un test que recorra todos los `.ts` de `packages/engine-core/src` (excluyendo `__tests__` y `*.test.ts`) usando `node:fs` y `node:path`, y falle si alguno contiene: + - un import de `react`, `react-dom`, `three`, `next`, `@react-three/…` + - uso de `window.`, `document.`, `localStorage`, `navigator.` **fuera de comentarios** + - `process.env` sin `typeof process` en la misma línea + + Para ignorar comentarios basta con descartar líneas cuyo contenido recortado empiece por `//`, `*` o `/*`. El mensaje de fallo debe listar `archivo:línea`. +3. Mira un test existente de la carpeta (p. ej. `i18nStore.test.ts`) para copiar el estilo de imports de vitest. + +## ✅ Success Criteria + +- [ ] `cd packages/engine-core && npx vitest run` → 0 fallos, ≥ 245 tests. +- [ ] `npx tsc --noEmit -p packages/engine-core` → 0 errores. +- [ ] El test nuevo falla si añades temporalmente `window.foo` a un archivo del core (compruébalo y revierte). +- [ ] `git diff --stat` solo muestra los 2 archivos permitidos. + +## Reporte + +Salida de los comandos y confirmación de la prueba negativa. diff --git a/docs/phases/phase-15-green-baseline/tasks/06-ci-workflow.md b/docs/phases/phase-15-green-baseline/tasks/06-ci-workflow.md new file mode 100644 index 0000000..907fc43 --- /dev/null +++ b/docs/phases/phase-15-green-baseline/tasks/06-ci-workflow.md @@ -0,0 +1,53 @@ +# Task 15.06 — Workflow de CI + +**Effort**: 30min | **Modelo**: haiku | **Blocks**: 09 | **Blocked by**: — + +**Archivos permitidos** (ningún otro): +- `.github/workflows/ci.yml` (nuevo) + +--- + +## 🎯 Objetivo + +El repo no tiene CI. Crear un workflow de GitHub Actions que ejecute en cada push a `main` y en cada pull request las mismas comprobaciones que el gate de la fase. + +## Contexto del repo + +- Monorepo npm workspaces: `packages/engine-core`, `packages/engine-renderer-r3f`, `apps/web-demo`. +- La demo consume los paquetes por `file:` y resuelve a `dist/`, así que **los paquetes deben compilarse antes** de testear o type-checkear la demo. +- Node 20. Gestor: npm (hay `package-lock.json`). +- No hay tests e2e todavía: no instalar navegadores de Playwright. + +## 📝 Instructions + +Crear `.github/workflows/ci.yml` con un único job `verify` en `ubuntu-latest`: + +1. `actions/checkout@v4` +2. `actions/setup-node@v4` con `node-version: 20` y `cache: npm` +3. `npm ci` +4. Build de paquetes: `npm run build -w packages/engine-core` y luego `npm run build -w packages/engine-renderer-r3f` (en ese orden) +5. `npm test` +6. Type-check, tres pasos separados: + - `npx tsc --noEmit -p packages/engine-core` + - `npx tsc --noEmit -p packages/engine-renderer-r3f` + - `npx tsc --noEmit -p apps/web-demo` +7. `npm run lint` +8. `npm run build -w apps/web-demo` + +Requisitos: +- `on: push` (ramas `main`) y `pull_request`. +- `concurrency` por ref con `cancel-in-progress: true`. +- `permissions: contents: read`. +- Cada comprobación en su propio `step` con `name` legible, para ver cuál falla. +- Fijar `env: NEXT_TELEMETRY_DISABLED: 1` a nivel de job. +- Sin secretos, sin pasos de deploy ni de publish. + +## ✅ Success Criteria + +- [ ] El archivo es YAML válido: `node -e "const fs=require('fs');const s=fs.readFileSync('.github/workflows/ci.yml','utf8');if(/\t/.test(s))throw new Error('tabs');console.log('ok',s.split('\n').length,'lines')"`. +- [ ] Contiene los 8 pasos en el orden indicado. +- [ ] `git status --short` solo muestra `.github/workflows/ci.yml` como nuevo. + +## Reporte + +Contenido del archivo. No ejecutes el workflow ni hagas push. diff --git a/docs/phases/phase-15-green-baseline/tasks/07-untrack-dist.md b/docs/phases/phase-15-green-baseline/tasks/07-untrack-dist.md new file mode 100644 index 0000000..fa3d6b5 --- /dev/null +++ b/docs/phases/phase-15-green-baseline/tasks/07-untrack-dist.md @@ -0,0 +1,40 @@ +# Task 15.07 — Sacar `dist/` de git + +**Effort**: 45min | **Modelo**: opus (orquestador) | **Blocks**: 09 | **Blocked by**: 01–06, 08 integradas + +**Archivos**: `.gitignore`, `package.json` (raíz), `packages/*/package.json`, índice de git. + +--- + +## 🎯 Objetivo + +`packages/*/dist/` está versionado (260 archivos) y 9 de ellos no coinciden con lo que genera `src` (`findPath.js`, `GameTouchSpriteRuntime.js`, `useClickToMoveController.js`). `docs/workflow/pre-commit-checklist.md` ya dice que `dist/` no se commitea. + +Lo ejecuta el orquestador porque manipula el índice de git y `package.json` raíz, que no deben tocarse en paralelo. + +## Riesgo a cubrir + +La demo depende de los paquetes por `file:` → `main: dist/index.js`. Sin `dist/` en git, un clon limpio no arranca hasta compilar. Hay que hacerlo automático. + +## 📝 Instructions + +1. `.gitignore`: añadir `packages/*/dist/`. +2. `git rm -r --cached packages/engine-core/dist packages/engine-renderer-r3f/dist` (los archivos quedan en disco). +3. `package.json` raíz, scripts: + - `"build:packages": "npm run build -w packages/engine-core && npm run build -w packages/engine-renderer-r3f"` + - `"prepare": "npm run build:packages"` (se ejecuta tras `npm install` / `npm ci`) + - `"typecheck": "tsc --noEmit -p packages/engine-core && tsc --noEmit -p packages/engine-renderer-r3f && tsc --noEmit -p apps/web-demo"` + - `"predev": "npm run build:packages"` +4. En cada `packages/*/package.json`: `"prepublishOnly": "npm run build"`. +5. Simplificar `.github/workflows/ci.yml` para usar `npm run build:packages` y `npm run typecheck`. + +## ✅ Success Criteria + +- [ ] `git ls-files packages | grep -c "/dist/"` → 0. +- [ ] Borrando ambos `dist/` y ejecutando `npm run build:packages && npm test && npm run build` → todo verde. +- [ ] `npm pack --dry-run -w packages/engine-core` sigue incluyendo `dist/`. +- [ ] `npm run dev` arranca tras borrar `dist/` (lo regenera `predev`). + +## On Complete + +Marcar `[x]` en tracking. Commit: `chore(phase-15): untrack dist and build packages on install`. diff --git a/docs/phases/phase-15-green-baseline/tasks/08-docs-resync.md b/docs/phases/phase-15-green-baseline/tasks/08-docs-resync.md new file mode 100644 index 0000000..cba9e94 --- /dev/null +++ b/docs/phases/phase-15-green-baseline/tasks/08-docs-resync.md @@ -0,0 +1,65 @@ +# Task 15.08 — Resincronizar docs con el código + +**Effort**: 1.5h | **Modelo**: haiku | **Blocks**: 09 | **Blocked by**: — + +**Archivos permitidos**: solo `.md` bajo `docs/` (excepto `docs/phases/phase-15-*` y `docs/phases/phase-16-*`), más `CLAUDE.md`, `README.md` raíz, `.gitignore` y los archivos sueltos de la raíz listados abajo. **Ningún archivo de código.** + +--- + +## 🎯 Objetivo + +Corregir estados y enlaces erróneos. Cada cambio es un hecho comprobable; no redactes contenido nuevo ni opines. + +## Cambios exactos + +### A. Estado de fases (campo `Status`/`Estado` del `README.md` y cabecera de `tracking.md`) + +| Fase | Hoy dice | Debe decir | +|---|---|---| +| `phase-6-walls-with-openings` | Planning | completed | +| `phase-8-scene-transitions` | Planned | completed | +| `phase-10-scene-entry-positions-and-pathwalking` | In Progress | completed | +| `phase-11-audio` | Planned | completed — gate de validación pendiente (ver Phase 15) | +| `phase-12-architecture-cleanup` | Planned | completed — gate de validación pendiente (ver Phase 15) | +| `phase-13-i18n` | Planned | completed — gate de validación pendiente (ver Phase 15) | +| `phase-7-walls-first-class` | planned — not started | **no tocar** (es correcto) | + +No marques ningún checkbox de los "Post-Phase Checklist": los valida el orquestador. + +### B. `docs/README.md`, sección Phases + +- `phase-7`: cambiar "✅ Completed" por "📋 Planned (not started)". +- Añadir entradas que faltan, con el mismo formato: phase-10 (✅), phase-11-audio (✅), phase-12 (✅), phase-13 (✅), `phase-15-green-baseline` (🚧 Active), `phase-16-runtime-in-library` (📋 Planning). +- Sección Decisions: añadir los ADR que existen en `docs/decisions/` y no están listados (0005 a 0009). +- Sección Architecture: añadir `07-walls-with-openings.md` y `08-scene-transitions.md`. + +### C. `CLAUDE.md` (solo estas 4 líneas) + +- Cabecera `**Versión**: 2.0-dev` → `**Versión**: 0.4.0`. +- `- **v0.1.x**: Demo R3F funcional (actual)` → quitar `(actual)` y añadirlo a la línea de `v0.4.x`. +- Borrar la línea `**Nota**: la estructura monorepo se materializa en Fase 2. Estado actual: app Next.js plana.` +- Tabla "Documentos Clave", fila "Fase activa": `docs/phases/phase-15-green-baseline/`. + +### D. Archivos sueltos + +- `git mv` a `docs/_archive/`: `FEATURE_WALLS_OPENINGS_VISUAL_GUIDE.md`, `PHASE_6_EXECUTIVE_SUMMARY.md`, `TODAY_DELIVERABLES.md`, `docs/DEBUG_MODE_REVIEW.md`. +- `git mv docs/phases/phase-11/PLAN_AUDIO_FIXES.md docs/phases/phase-11-audio/PLAN_AUDIO_FIXES.md` (la carpeta `phase-11` queda vacía y desaparece). +- `git rm --cached dev.log` y añadir `*.log` a `.gitignore`. +- Tras mover, buscar con grep referencias a las rutas antiguas en `docs/` y `README.md` y actualizarlas. + +### E. Avisos de desfase (un bloque de cita al inicio, sin reescribir el documento) + +En `docs/LIBRARY_CONSUMPTION_GUIDE.md`, `docs/LIBRARY_API_CONTRACT_V1.md` y `docs/architecture/02-public-api.md`: + +> ⚠️ **Desfase conocido (2026-10-10)**: `createGameRuntime`, `GameViewport`, `useGameState`, `useGameActions` y `registerRule` viven hoy en `apps/web-demo/app/lib/engine/publicApi.ts`; `@pointclick-engine/engine-renderer-r3f` **no** los exporta todavía. Se corrige en `docs/phases/phase-16-runtime-in-library/`. + +## ✅ Success Criteria + +- [ ] `git status --short` no muestra ningún `.ts`/`.tsx`/`.json` modificado. +- [ ] `ls docs/phases/phase-11 2>/dev/null` → no existe. +- [ ] `grep -rn "TODAY_DELIVERABLES\|PHASE_6_EXECUTIVE_SUMMARY" docs README.md CLAUDE.md` solo devuelve rutas bajo `_archive`. +- [ ] Todos los enlaces relativos añadidos en `docs/README.md` apuntan a rutas que existen. + +## Reporte + +Lista de archivos tocados y movidos. Cualquier otra incoherencia que veas: **repórtala, no la arregles**. diff --git a/docs/phases/phase-15-green-baseline/tasks/09-validation-gate.md b/docs/phases/phase-15-green-baseline/tasks/09-validation-gate.md new file mode 100644 index 0000000..dd36438 --- /dev/null +++ b/docs/phases/phase-15-green-baseline/tasks/09-validation-gate.md @@ -0,0 +1,55 @@ +# Task 15.09 — Gate de validación + +**Effort**: 1.5h | **Modelo**: opus (orquestador) | **Blocks**: Fase 16 | **Blocked by**: 01–08 + +--- + +## 🎯 Objetivo + +Validar la integración de todas las tareas, cerrar los gates heredados de las fases 11–13 y dejar constancia. Nada se marca sin ejecutar el comando. + +## 📝 Instructions + +### 1. Revisión de cada entrega + +Por tarea: leer el diff completo, comprobar que solo toca sus archivos permitidos y que ningún test se arregló relajando aserciones. Rechazar y relanzar si no cumple. + +### 2. Gate técnico (desde la raíz, con `dist/` borrado antes) + +```bash +npm run build:packages +npm test +npm run typecheck +npm run lint +npm run build +``` + +### 3. Regla de Oro + +```bash +grep -rnE "from ['\"](react|react-dom|three|next|@react-three)" packages/engine-core/src # vacío +grep -rnE "\bwindow\.|\bdocument\.|localStorage|navigator\." packages/engine-core/src | grep -v "^\S*:\d*:\s*\*" # solo comentarios +``` + +### 4. Gates heredados + +Recorrer el "Post-Phase Checklist" de `phase-11-audio`, `phase-12-architecture-cleanup` y `phase-13-i18n`. Para cada check: ejecutar su comando o verificación, marcar `[x]` si pasa. Si no pasa o ya no aplica, dejar `[ ]` con una nota de una línea y, si procede, abrir tarea en la Fase 16. + +Conocido de antemano: el check de 11 "Demo: 1+ ítem con SFX custom vía reglas" no se cumple por la vía declarativa — `GameTouchCanvas.tsx` tiene un mapa de sonidos escrito a mano y no usa `useAudioSystem`. Se resuelve en 16.07. + +### 5. Smoke en navegador + +Con la skill `run-web-demo`: intro → mover con click → recoger el trofeo → pasar a la mazmorra → abrir la puerta con la llave → cambiar idioma → recargar y comprobar que persiste. Revisar la consola por errores. + +### 6. Cierre + +- Marcar gate final en `tracking.md` y `Estado: completed` en el README de la fase. +- Actualizar `docs/README.md` y la fila "Fase activa" de `CLAUDE.md` a la Fase 16. +- Commits atómicos por tarea según `docs/workflow/commit-convention.md`. + +## ✅ Success Criteria + +- [ ] Los 5 comandos del gate técnico terminan en 0. +- [ ] Greps de la Regla de Oro limpios. +- [ ] Cada check heredado está marcado o anotado. +- [ ] Smoke en navegador sin errores de consola nuevos. diff --git a/docs/phases/phase-15-green-baseline/tracking.md b/docs/phases/phase-15-green-baseline/tracking.md new file mode 100644 index 0000000..ed8e45e --- /dev/null +++ b/docs/phases/phase-15-green-baseline/tracking.md @@ -0,0 +1,29 @@ +# Phase 15 — Tracking + +> Marca `[x]` solo con Success Criteria validados. Ver `docs/workflow/how-to-track-tasks.md`. + +## Ola 1 — en paralelo (archivos disjuntos) + +- [x] [01-fix-publicapi-contract-tests](tasks/01-fix-publicapi-contract-tests.md) — sonnet +- [x] [02-fix-audio-system-tests](tasks/02-fix-audio-system-tests.md) — sonnet +- [x] [03-lint-react-rules](tasks/03-lint-react-rules.md) — sonnet +- [x] [04-lint-trivial](tasks/04-lint-trivial.md) — haiku +- [x] [05-core-node-env-guard](tasks/05-core-node-env-guard.md) — haiku +- [x] [06-ci-workflow](tasks/06-ci-workflow.md) — haiku +- [x] [08-docs-resync](tasks/08-docs-resync.md) — haiku + +## Ola 2 — orquestador, tras integrar la ola 1 + +- [x] [07-untrack-dist](tasks/07-untrack-dist.md) — opus +- [x] [09-validation-gate](tasks/09-validation-gate.md) — opus — _gate técnico por el orquestador; puerta, audio e idioma verificado a mano por el owner, 2026-10-10_ + +## Gate final + +- [x] `npm test` verde en los 3 workspaces +- [x] `tsc --noEmit` limpio en los 3 workspaces +- [x] `npm run lint` con 0 errores +- [x] `npm run build` verde +- [x] Regla de Oro: grep de imports prohibidos en core vacío +- [x] `git ls-files packages | grep /dist/` vacío +- [x] Gates heredados de las fases 11, 12 y 13 revisados y marcados (o anotados como bloqueados) +- [x] Smoke manual en navegador: mover, recoger ítem, cambiar de escena — _intro, movimiento, recogida y persistencia por el orquestador; transición, puerta con llave, audio e idioma verificado a mano por el owner, 2026-10-10_ diff --git a/docs/phases/phase-16-runtime-in-library/README.md b/docs/phases/phase-16-runtime-in-library/README.md new file mode 100644 index 0000000..bddc955 --- /dev/null +++ b/docs/phases/phase-16-runtime-in-library/README.md @@ -0,0 +1,83 @@ +# Phase 16 — Runtime in Library + +**Objetivo**: que el juego se pueda montar importando solo los paquetes; la demo pasa de orquestadora a consumidora. +**Duración estimada**: 1.5–2 semanas +**Estado**: completed (2026-10-10) — 0.5.0 lista para publicar; la publicación en npm requiere orden del owner +**Owner**: Daniel Martínez Sebastián +**Version target**: v0.5.0 (lockstep, solo adiciones) + +--- + +## Por qué + +Ver [ADR-0009](../../decisions/0009-runtime-lives-in-packages.md). En corto: el runtime está en `apps/web-demo/app/lib/engine/publicApi.ts`, la guía de consumo documenta exports que los paquetes no tienen, `scene:set` pierde `transitions` y `music`, y la demo mantiene copias de código del renderer y del core. + +## Resultado esperado + +1. Un consumidor externo puede escribir esto y obtener un juego jugable: + ```tsx + import { createGameRuntime } from "@pointclick-engine/engine-core"; + import { GameViewport } from "@pointclick-engine/engine-renderer-r3f"; + ``` +2. `apps/web-demo/app/lib/engine/publicApi.ts` es un barrel de re-export; el contrato v1 no cambia. +3. `grep -rln "demo-content" apps/web-demo/app` solo devuelve `page.tsx` y rutas de ejemplo (el punto de composición). +4. `apps/web-demo/app/lib/engine/render/` y `app/lib/core/` no existen. +5. Un test headless en core registra dos escenas con transición y música, ejecuta `scene:set` y `transition:activate`, y verifica que no se pierde ningún campo. + +## Tareas, orden y reparto + +| # | Tarea | Modelo | Depende de | +|---|---|---|---| +| 01 | [ADR-0009 + issue](tasks/01-adr-and-issue.md) | opus | — | +| 02 | [Core: `createGameRuntime` agnóstico](tasks/02-core-runtime-factory.md) | sonnet | 01 | +| 03 | [Renderer: hooks de estado y barrel en la demo](tasks/03-renderer-state-hooks-and-barrel.md) | sonnet | 02 | +| 04 | [Unificar tipos de escena](tasks/04-unify-scene-types.md) | sonnet | 02 | +| 05 | [Borrar copias de render en la demo](tasks/05-delete-render-duplicates.md) | haiku | — | +| 06 | [Unificar `inventoryRules`](tasks/06-unify-inventory-rules.md) | sonnet | 04 | +| 07 | [Audio declarativo](tasks/07-declarative-audio-wiring.md) | sonnet | 15.02, 03 | +| 08 | [Persistencia vía `StoragePort`](tasks/08-storage-port-persistence.md) | haiku | — | +| 09 | [`CharacterSprite` configurable](tasks/09-generic-character-sprite.md) | sonnet | 05 | +| 10 | [Comando `player:stop`](tasks/10-wire-player-stop.md) | haiku | 02 | +| 11 | [`GameViewport` funcional](tasks/11-functional-game-viewport.md) | sonnet | 03, 06, 07, 09 | +| 12 | [Reescribir docs de consumo](tasks/12-rewrite-consumption-docs.md) | haiku | 11 | +| 13 | [Gate de validación y release 0.5.0](tasks/13-validation-gate.md) | opus | todas | + +Olas: **A** = 02, 05, 08 en paralelo · **B** = 03, 04, 10 · **C** = 06, 07, 09 · **D** = 11 · **E** = 12, 13. El orquestador integra y valida entre olas. + +## Principios + +- Regla de Oro intacta: el test `coreAgnosticism.test.ts` (15.05) debe seguir verde. +- Ningún nombre del contrato v1 se renombra ni se elimina. +- Mover antes de mejorar: cada tarea traslada comportamiento existente; los cambios funcionales se listan explícitamente en la tarea. +- Cada tarea lista sus archivos permitidos; las de una misma ola son disjuntas. + +## Fuera de alcance + +- Puertas como primitiva del motor → Fase 7. +- Flags, condiciones, hotspots con verbos, NPCs, diálogos con opciones, guardado → fase narrativa (por planificar, tras esta). +- Trocear `GameTouchSpriteRuntime.tsx` (886 líneas) → se evalúa al cerrar la tarea 11. +- Multijugador → Fase 14, después de la fase narrativa. + +## Retrospectiva + +**Qué cambió respecto al plan** + +- La tarea 11 se troceó en 9 pasos tras un inventario de dependencias ([11-steps](tasks/11-steps.md)); la 07 necesitó una 07b y una decisión del owner sobre el evento de recogida (`item:pickedUp`, breaking). +- La validación en navegador pasó de manual a automática: `npm run smoke` juega la demo y el ejemplo mínimo en headless y comprueba estado y sonidos. +- La prueba de instalación fuera del monorepo encontró dos fallos que ningún test veía: el rango de `three` del renderer (`^0.150.0` solo admitía 0.150.x) y un asset de la demo (`/globe.svg`) pedido desde el paquete. + +**Desviaciones aceptadas respecto a ADR-0009** + +- Los registros de escenas, ítems y reglas siguen siendo globales de módulo, no por instancia de runtime: un juego por página. +- La demo sigue poniendo en el store su escena completa (con `doors`) mediante `resolveScene`, en vez de la proyección del registro. + +**Pasa a la fase narrativa** + +- `inventory:pickup` e `inventory:drop` siguen sin executor (dependen de hotspots con verbos). +- Puertas como primitiva del motor (hoy en la demo; Fase 7). +- Outcomes legacy (`rule-miss`, `on-player`, `pickup-blocked`, `item-interact`, `unknown-item`) viajan como `item:dropped` fuera del tipo. +- `player:stop` no detiene el movimiento por teclado o joystick; `player:walkAborted` casi nunca se emite porque el pathfinding devuelve rutas parciales. +- El personaje por defecto no trae assets: el host debe servir `/assets/sprites/david/` o pasar su `character`. +- `zustand` `create` en el core arrastra el binding de React; valorar `zustand/vanilla` antes de 1.0. +- `GameTouchSpriteRuntime.tsx` (~900 líneas) sigue mezclando jugador, editor de muros y bocadillo. +- `/debug` no registra diccionarios de i18n (claves en crudo y aviso de hidratación), previo a esta fase. diff --git a/docs/phases/phase-16-runtime-in-library/tasks/01-adr-and-issue.md b/docs/phases/phase-16-runtime-in-library/tasks/01-adr-and-issue.md new file mode 100644 index 0000000..af591c8 --- /dev/null +++ b/docs/phases/phase-16-runtime-in-library/tasks/01-adr-and-issue.md @@ -0,0 +1,28 @@ +# Task 16.01 — ADR-0009 + issue + +**Effort**: 30min | **Modelo**: opus (orquestador) | **Blocks**: 02, 03 | **Blocked by**: visto bueno del owner + +--- + +## 🎯 Objetivo + +`CLAUDE.md` prohíbe cambiar `publicApi.ts` sin issue y plan de migración. Esta tarea cumple ese requisito antes de mover código. + +## 📝 Instructions + +1. Revisar con el owner [ADR-0009](../../../decisions/0009-runtime-lives-in-packages.md). Puntos que debe confirmar: + - El runtime agnóstico va a `engine-core` (no a un paquete nuevo). + - `publicApi.ts` de la demo queda como barrel; contrato v1 sin cambios breaking. + - Versión objetivo 0.5.0 en lockstep. +2. Con su aprobación, abrir el issue en GitHub con el borrador incluido en el ADR (`gh issue create`, label `architecture`). +3. Cambiar `Status` del ADR a `accepted` y añadir el número de issue. +4. Referenciar el issue en los commits de las tareas 02 y 03 (`See #N`). + +## ✅ Success Criteria + +- [ ] Issue abierto y enlazado desde el ADR. +- [ ] ADR en estado `accepted`. + +## Nota + +Abrir un issue es una acción visible fuera del repo local: no se hace sin confirmación explícita del owner. diff --git a/docs/phases/phase-16-runtime-in-library/tasks/02-core-runtime-factory.md b/docs/phases/phase-16-runtime-in-library/tasks/02-core-runtime-factory.md new file mode 100644 index 0000000..447ac90 --- /dev/null +++ b/docs/phases/phase-16-runtime-in-library/tasks/02-core-runtime-factory.md @@ -0,0 +1,54 @@ +# Task 16.02 — Core: `createGameRuntime` agnóstico + +**Effort**: 4h | **Modelo**: sonnet | **Blocks**: 03, 04, 10 | **Blocked by**: 01 + +**Archivos permitidos**: +- `packages/engine-core/src/game/runtime/**` (nuevo) +- `packages/engine-core/src/index.ts` (añadir export) +- `packages/engine-core/src/__tests__/gameRuntime*.test.ts` (nuevo) + +`apps/web-demo/app/lib/engine/publicApi.ts` es **solo lectura** en esta tarea (lo adapta la 03). + +--- + +## 🎯 Objetivo + +Llevar a `engine-core` la parte de `publicApi.ts` que no depende de React: tipos de config, registros, factoría, executors y accesores sin hooks. La demo sigue funcionando con su copia hasta la tarea 03. + +## Alcance + +Mover (copiando el comportamiento actual, líneas ~100–590 de `publicApi.ts`): + +- Tipos: `GameSceneConfig`, `GameItemConfig`, `GameItemRule`, `GameItemDropOutcome`, `GameRuleConfig`, `GameRuntime`, `GameRuntimeConfig`, `InventoryUIAdapter`, `DialogUIAdapter`, `GameState`, `GameActions`, `GameRuntimeEvent`, `GameRuntimeEventHandler`. +- Funciones: `registerScene`, `registerItem`, `registerRule`, `createGameRuntime`, `getGameRuntime`, `getGameState`, `getGameActions`. + +No mover: `useGameState`, `useGameActions`, `GameViewport` (usan React). + +## Cambios funcionales (los únicos permitidos) + +1. **Escena completa**: un único helper `toRuntimeScene(config): GameScene` sustituye las 4 copias campo a campo. Debe conservar `transitions` y `music`. `GameSceneConfig` gana `transitions?: GameSceneTransition[]` (campo opcional, no breaking). +2. **Sin `console.log`** en el camino feliz de `player:walkTo` (hoy hay uno en "no path found"); usar el logger inyectable del `sceneStore` o nada. +3. Estructura: `runtime/types.ts`, `runtime/registry.ts`, `runtime/executors.ts`, `runtime/createGameRuntime.ts`, `runtime/index.ts`. Ningún archivo > 250 líneas. + +## 📝 Instructions + +1. Leer `publicApi.ts` entero y `publicApi.test.ts` (referencia de comportamiento esperado). +2. Crear los módulos. Sin imports de React, `zustand/react`, ni nada del navegador. +3. Tests headless nuevos (≥ 15), incluyendo obligatoriamente: + - `scene:set` conserva `transitions` y `music` en `useSceneStore.getState().scene`. + - `transition:activate` cambia de escena y emite `transition:started` y `transition:completed`. + - `player:walkTo` con destino alcanzable activa `playerWalkingState`; con destino inalcanzable emite `player:walkAborted`. + - `dialog:trigger` sin adapter no lanza y emite el evento. + - `dispose()` limpia bus, comandos y singleton. + +## ✅ Success Criteria + +- [ ] `cd packages/engine-core && npx vitest run` → 0 fallos. +- [ ] `npx tsc --noEmit -p packages/engine-core` → 0 errores. +- [ ] `coreAgnosticism.test.ts` sigue verde. +- [ ] `import { createGameRuntime } from "@pointclick-engine/engine-core"` resuelve (comprobado en un test que importa desde `../index`). +- [ ] `git diff --stat` solo muestra archivos permitidos. + +## Reporte + +API exportada, diferencias de comportamiento respecto a `publicApi.ts` (deben ser solo las 2 listadas) y dudas de diseño para el orquestador. diff --git a/docs/phases/phase-16-runtime-in-library/tasks/03-renderer-state-hooks-and-barrel.md b/docs/phases/phase-16-runtime-in-library/tasks/03-renderer-state-hooks-and-barrel.md new file mode 100644 index 0000000..cff95ce --- /dev/null +++ b/docs/phases/phase-16-runtime-in-library/tasks/03-renderer-state-hooks-and-barrel.md @@ -0,0 +1,41 @@ +# Task 16.03 — Renderer: hooks de estado y barrel en la demo + +**Effort**: 2.5h | **Modelo**: sonnet | **Blocks**: 07, 11 | **Blocked by**: 02 + +**Archivos permitidos**: +- `packages/engine-renderer-r3f/src/hooks/useGameState.ts`, `useGameActions.ts` (nuevos) +- `packages/engine-renderer-r3f/src/index.ts` +- `packages/engine-renderer-r3f/src/__tests__/gameStateHooks.test.tsx` (nuevo) +- `apps/web-demo/app/lib/engine/publicApi.ts` +- `apps/web-demo/app/lib/engine/publicApi.test.ts` + +--- + +## 🎯 Objetivo + +Tras la tarea 02 el runtime existe en el core y, duplicado, en `publicApi.ts`. Aquí se elimina el duplicado: `publicApi.ts` pasa a ser un barrel de re-export y los dos hooks de React se trasladan al renderer. + +## 📝 Instructions + +1. Crear `useGameState(selector)` y `useGameActions()` en el renderer, moviendo la implementación actual de `publicApi.ts`. Deben apoyarse en `getGameActions`/registro del core para no duplicar la lógica de `setScene`. +2. Exportarlos desde `packages/engine-renderer-r3f/src/index.ts`. +3. Reescribir `apps/web-demo/app/lib/engine/publicApi.ts` como barrel: + - `"use client"` se conserva. + - Re-exporta desde `@pointclick-engine/engine-core` y `@pointclick-engine/engine-renderer-r3f` **todos** los nombres que exporta hoy. Antes de editar, genera la lista con `grep -n "^export" publicApi.ts` y guárdala en el reporte como "antes"; al terminar, compárala con el "después". + - `GameViewport` se queda definido aquí de momento (lo resuelve la tarea 11). + - Objetivo: < 120 líneas. +4. `publicApi.test.ts` debe pasar **sin modificar aserciones**. Solo se permite ajustar imports o setup si es imprescindible, explicándolo. +5. Test nuevo en el renderer: `useGameActions().setScene(id)` cambia `sceneId` (usar `renderToString` como hace `publicApi.test.ts`). +6. Recordatorio: la demo resuelve los paquetes por `dist/`. Ejecuta `npm run build:packages` antes de testear la demo. + +## ✅ Success Criteria + +- [ ] `npm run build:packages && npm test` → 0 fallos. +- [ ] `npm run typecheck` → 0 errores. +- [ ] Lista de exports de `publicApi.ts` "después" ⊇ "antes" (ningún nombre perdido). +- [ ] `grep -c "commands.register" apps/web-demo/app/lib/engine/publicApi.ts` → 0. +- [ ] `git diff --stat` solo muestra archivos permitidos. + +## Reporte + +Listas de exports antes/después, líneas finales de `publicApi.ts`, y cualquier ajuste hecho en el test con su motivo. diff --git a/docs/phases/phase-16-runtime-in-library/tasks/04-unify-scene-types.md b/docs/phases/phase-16-runtime-in-library/tasks/04-unify-scene-types.md new file mode 100644 index 0000000..eaef08e --- /dev/null +++ b/docs/phases/phase-16-runtime-in-library/tasks/04-unify-scene-types.md @@ -0,0 +1,39 @@ +# Task 16.04 — Unificar tipos de escena + +**Effort**: 3h | **Modelo**: sonnet | **Blocks**: 06 | **Blocked by**: 02 + +**Archivos permitidos**: `apps/web-demo/demo-content/scenes/scenes.ts`, `apps/web-demo/demo-content/items/types.ts`, `apps/web-demo/demo-content/dialogs/types.ts`, y los archivos de `apps/web-demo/app/**` que solo necesiten cambiar un import de tipo o quitar un cast. Nada en `packages/`. + +--- + +## 🎯 Objetivo + +`demo-content/scenes/scenes.ts` redefine `SceneWall`, `SceneWallOpening`, `SceneInteraction`, `SceneGround` y `Scene`, casi idénticos a los del core pero no asignables (`rotationY?` opcional frente a obligatorio). De ahí salen los casts `as GameSceneConfig[]` y `as GameScene | undefined` repartidos por la demo. + +## 📝 Instructions + +1. En `scenes.ts`, borrar los tipos duplicados e importar los del core: `GameSceneWall`, `GameSceneWallOpening`, `GameSceneInteractionFull`, `GameSceneGround`, `GameScene`. +2. Lo que solo existe en la demo se modela como extensión explícita: + ```ts + export type DemoSceneInteraction = GameSceneInteractionFull & { invisible?: boolean }; + export type DemoScene = Omit & { + interactions: DemoSceneInteraction[]; + doors?: SceneDoor[]; + }; + ``` + `SceneDoor` se queda en la demo (la Fase 7 lo promoverá). +3. Mantener alias de compatibilidad exportados (`export type Scene = DemoScene`, etc.) para no tocar más archivos de los necesarios. +4. Corregir los datos: cada muro sin `rotationY` recibe `rotationY: 0`. **No cambiar ningún otro valor numérico** de las escenas. +5. Hacer lo mismo con `items/types.ts` y `dialogs/types.ts` si duplican `ItemDefinition`, `ItemInteractionRule` o `DialogKey` del core: re-exportar en vez de redefinir. +6. Eliminar los casts que dejen de ser necesarios (`page.tsx`, `GameTouchCanvas.tsx`, `publicApi.test.ts`, `example-bridge/page.tsx`). Búscalos con `grep -rn "as GameScene" apps/web-demo`. + +## ✅ Success Criteria + +- [ ] `npm run typecheck` → 0 errores. +- [ ] `npm test` → 0 fallos. +- [ ] `grep -rn "as GameSceneConfig\[\]\|as GameScene | undefined" apps/web-demo/app` → vacío. +- [ ] `git diff` de `scenes.ts` no altera posiciones, tamaños ni ids (solo tipos y `rotationY: 0` añadidos). + +## Reporte + +Tipos eliminados, alias conservados, casts retirados y cualquier campo de la demo que no exista en el core (candidato a promover). diff --git a/docs/phases/phase-16-runtime-in-library/tasks/05-delete-render-duplicates.md b/docs/phases/phase-16-runtime-in-library/tasks/05-delete-render-duplicates.md new file mode 100644 index 0000000..1dcec25 --- /dev/null +++ b/docs/phases/phase-16-runtime-in-library/tasks/05-delete-render-duplicates.md @@ -0,0 +1,40 @@ +# Task 16.05 — Borrar copias de render en la demo + +**Effort**: 1.5h | **Modelo**: haiku | **Blocks**: 09 | **Blocked by**: Fase 15 + +**Archivos permitidos**: `apps/web-demo/app/lib/engine/render/**` (borrar), los shims de una línea en `apps/web-demo/app/components/scene/` y `components/sprite/`, `apps/web-demo/app/components/SpeechBubble.tsx`, y los imports de los archivos que los consumían. + +--- + +## 🎯 Objetivo + +`apps/web-demo/app/lib/engine/render/` contiene copias de 7 archivos que ya viven en `packages/engine-renderer-r3f/src/`: + +| Archivo | Paquete | Demo | Estado | +|---|---|---|---| +| `SpeechBubble.tsx` | 316 L | 242 L | divergido | +| `scene/SceneWalls.tsx` | 165 L | 130 L | divergido | +| `scene/SceneGround.tsx` | 126 | 126 | igual | +| `scene/SceneCollisionSphere.tsx` | 31 | 31 | igual | +| `scene/SceneWallPointPreview.tsx` | — | — | comprobar | +| `sprite/DavidSprite.tsx` | 230 | 230 | igual | +| `sprite/clips.ts`, `sprite/speakingAnimation.ts` | 72 / 46 | 72 / 46 | igual | + +## 📝 Instructions + +1. Para cada archivo de la copia, localizar quién lo importa: `grep -rn "engine/render" apps/web-demo/app`. Seguir también los shims de una línea de `components/scene/*.tsx` y `components/sprite/*`. +2. **Antes de borrar nada**, construir una tabla: símbolo → quién lo usa → ¿lo exporta `@pointclick-engine/engine-renderer-r3f`? (mirar `packages/engine-renderer-r3f/src/index.ts`). +3. Si un símbolo usado **no** está exportado por el paquete: no borres ese archivo, repórtalo y sigue con el resto. +4. Para los dos archivos divergidos, ejecutar `diff` entre copia y paquete y pegar el resultado en el reporte. Si la copia de la demo tiene código que el paquete no tiene y alguien lo usa, **no la borres**: repórtalo. +5. Redirigir los imports al paquete y borrar con `git rm` las copias y los shims que queden sin consumidores. +6. `npm run build:packages` antes de validar. + +## ✅ Success Criteria + +- [ ] `npm run typecheck` y `npm test` → verdes. +- [ ] `npm run build -w apps/web-demo` → verde. +- [ ] `grep -rn "lib/engine/render" apps/web-demo/app` → vacío, o solo los archivos reportados como no borrables. + +## Reporte + +La tabla del paso 2, los `diff` del paso 4 y la lista de archivos borrados y no borrados con motivo. diff --git a/docs/phases/phase-16-runtime-in-library/tasks/06-unify-inventory-rules.md b/docs/phases/phase-16-runtime-in-library/tasks/06-unify-inventory-rules.md new file mode 100644 index 0000000..a0cff10 --- /dev/null +++ b/docs/phases/phase-16-runtime-in-library/tasks/06-unify-inventory-rules.md @@ -0,0 +1,36 @@ +# Task 16.06 — Unificar `inventoryRules` + +**Effort**: 3h | **Modelo**: sonnet | **Blocks**: 11 | **Blocked by**: 04 + +**Archivos permitidos**: +- `apps/web-demo/app/lib/core/rules/inventoryRules.ts` y su test (borrar) +- `apps/web-demo/app/lib/engine/runtime/useInventoryRuntimeController.ts` +- `packages/engine-core/src/game/logic/rules/inventoryRules.ts` (solo si falta paridad, ver paso 3) +- `packages/engine-core/src/__tests__/inventoryRules*.test.ts` + +--- + +## 🎯 Objetivo + +Hay dos implementaciones de las reglas de inventario: la del core (287 líneas, con tests) y una copia en la demo (270 líneas) que importa `demo-content` directamente y es **la que el juego usa de verdad**. La del core no se ejecuta en el runtime. + +## 📝 Instructions + +1. `diff` entre ambas. Clasificar cada diferencia en: (a) solo cambia de dónde viene el registro de ítems, (b) diferencia de comportamiento real. Incluir la clasificación en el reporte. +2. Entender cómo recibe la versión del core el registro de ítems (parámetro/resolver). La demo deberá pasarle un resolver construido desde `ITEMS` — o, mejor, desde `getGameRuntime().getItems()` si la tarea 02 ya registra los ítems. +3. Si hay diferencias de tipo (b), la versión de la demo es la referencia de comportamiento (es la que está probada jugando). Portarlas al core **con un test por cada una**. No cambiar firmas exportadas del core; solo añadir. +4. Cambiar `useInventoryRuntimeController.ts` para importar de `@pointclick-engine/engine-core`. +5. Migrar al core los casos de `apps/web-demo/app/lib/core/rules/inventoryRules.test.ts` que no estén ya cubiertos. +6. `git rm` de la copia de la demo y de su test. Si `app/lib/core/` queda vacío, desaparece. +7. `npm run build:packages` antes de validar la demo. + +## ✅ Success Criteria + +- [ ] `npm test` y `npm run typecheck` → verdes. +- [ ] `ls apps/web-demo/app/lib/core` → no existe. +- [ ] Número de tests del core ≥ el anterior + casos migrados. +- [ ] `coreAgnosticism.test.ts` verde. + +## Reporte + +Clasificación de diferencias, comportamientos portados y lista de escenarios de inventario que el orquestador debe probar en navegador (colocar, consumir, devolver, recoger bloqueado, soltar sobre el jugador). diff --git a/docs/phases/phase-16-runtime-in-library/tasks/07-declarative-audio-wiring.md b/docs/phases/phase-16-runtime-in-library/tasks/07-declarative-audio-wiring.md new file mode 100644 index 0000000..5ddf5b9 --- /dev/null +++ b/docs/phases/phase-16-runtime-in-library/tasks/07-declarative-audio-wiring.md @@ -0,0 +1,39 @@ +# Task 16.07 — Audio declarativo + +**Effort**: 2.5h | **Modelo**: sonnet | **Blocks**: 11 | **Blocked by**: 15.02, 03 + +**Archivos permitidos**: +- `apps/web-demo/app/components/GameTouchCanvas.tsx` (solo los bloques de audio, líneas ~167–283) +- `apps/web-demo/demo-content/items/index.ts` +- `apps/web-demo/demo-content/scenes/scenes.ts` (solo campos `triggerSoundUrl` de transiciones) +- `apps/web-demo/app/lib/engine/runtime/useDemoAudio.ts` (nuevo, opcional) + +--- + +## 🎯 Objetivo + +La Fase 11 creó la vía declarativa (`pickupSoundUrl`/`dropSoundUrl` en ítems, `triggerSoundUrl` en transiciones, `resolveAudioEvents` en core, `useAudioSystem` en el renderer), pero la demo no la usa. `GameTouchCanvas.tsx` tiene en su lugar: + +- un `setInterval` de 50 ms esperando a que exista el runtime, +- un mapa de sonidos por `itemId` escrito a mano, +- un efecto propio para la música de escena, +- varios `console.log("[audio] …")`. + +## 📝 Instructions + +1. Leer `packages/engine-renderer-r3f/src/hooks/attachAudioSystem.ts` y `packages/engine-core/src/game/logic/rules/audioRules.ts`. +2. Declarar los sonidos en datos: `pickupSoundUrl` del gameboy en `ITEMS`; defaults (`pickup-default`, `drop-default`, `transition-default`) en un `AudioDefaultsConfig`. +3. Sustituir en `GameTouchCanvas.tsx` el `setInterval`, el mapa y el efecto de música por una llamada a `useAudioSystem`. Si el runtime puede no existir en el primer render, resolverlo con estado/suscripción, no con polling. +4. Conservar tal cual lo que no cubre el sistema declarativo: sincronización de ajustes de mute/volumen, click de UI al abrir inventario, click al empezar a caminar, sonido de letras del bocadillo. +5. Quitar los `console.log` de audio. +6. Atención a un desajuste conocido: el código actual reacciona a `item:dropped` con `outcome === "pickup-success"`, valor que el tipo `GameEvent` no declara. Comprueba qué evento emite hoy realmente la recogida y repórtalo; si `resolveAudioEvents` no dispara el sonido de recogida por ese motivo, **no parchees el core**: describe el problema para el orquestador. + +## ✅ Success Criteria + +- [ ] `grep -n "setInterval\|soundMap\|console.log(\"\[audio\]" apps/web-demo/app/components/GameTouchCanvas.tsx` → vacío. +- [ ] `npm run typecheck`, `npm run lint`, `npm test` → verdes. +- [ ] Mismos sonidos que antes en: recoger gameboy, recoger otro ítem, colocar ítem, transición, música por escena. + +## Reporte + +Qué eventos disparan cada sonido ahora, y la lista exacta de pruebas de audio para el smoke en navegador. diff --git a/docs/phases/phase-16-runtime-in-library/tasks/07b-enable-declarative-audio.md b/docs/phases/phase-16-runtime-in-library/tasks/07b-enable-declarative-audio.md new file mode 100644 index 0000000..6abebc5 --- /dev/null +++ b/docs/phases/phase-16-runtime-in-library/tasks/07b-enable-declarative-audio.md @@ -0,0 +1,32 @@ +# Task 16.07b — Desbloquear el audio declarativo + +**Effort**: 3h | **Modelo**: sonnet | **Blocks**: 11 | **Blocked by**: — (owner eligió la opción A el 2026-10-10) + +--- + +## 🎯 Objetivo + +La tarea 16.07 dejó los sonidos declarados en datos, pero la demo sigue cableando el audio a mano porque `attachAudioSystem` + `resolveAudioEvents` no reproducen hoy lo mismo que suena. Tres causas, verificadas leyendo el código: + +1. **Orden de creación del runtime.** `createGameRuntime` se llama en un `useEffect` de `app/page.tsx`, posterior al efecto de `useSceneRuntimeController` que fija la escena inicial. El `scene:changed` inicial no llega al bus (música inicial perdida) y `GameTouchCanvas.tsx` necesita un `setInterval` de 50 ms para esperar al runtime. +2. **Nadie emite `item:pickedUp`.** La recogida viaja como `item:dropped` con `outcome: "pickup-success"`, valor que el tipo `GameEvent` no declara (`legacyRuntimeEventToGameEvent` lo cuela con un cast). +3. **`resolveAudioEvents` no mira `outcome`.** Para cualquier `item:dropped` devuelve el sonido de soltar: sonaría al recoger, al devolver y en intentos bloqueados, que hoy son silenciosos. + +## Decisión (owner, 2026-10-10): opción A + +- **Opción A (elegida)**: emitir `item:pickedUp` al recoger y dejar de enviar `pickup-success` como `item:dropped`; `resolveAudioEvents` reproduce el sonido de soltar solo con `outcome: "place"`. Corrige el tipo en vez de ampliarlo. Cambia la semántica observable de `item:dropped` para quien escuche recogidas por ese evento → nota de migración en el CHANGELOG de 0.5.0. +- **Opción B (descartada)**: declarar `"pickup-success"` (y el resto de outcomes legacy) en el tipo de `item:dropped` y filtrar por `outcome` en las reglas. No rompe a nadie, pero consolida un evento con doble significado. + +## 📝 Instructions + +1. `app/page.tsx`: crear el runtime antes del primer render de `GameTouchCanvas` (estado inicial perezoso o `useMemo`) y exponerlo por contexto o prop; `dispose` en el cleanup. Eliminar el `setInterval`. +2. Aplicar la opción elegida en el emisor (`useInventoryRuntimeController.ts`), en `legacyAdapter.ts` y en `audioRules.ts`, con tests en core para cada outcome. +3. Sustituir en `GameTouchCanvas.tsx` el cableado manual de SFX y el efecto de música por `useAudioSystem` con `DEMO_AUDIO_DEFAULTS` e `ITEMS`. +4. Registrar los ítems en el runtime (`createGameRuntime({ scenes, items })`) para que `useInventoryRuntimeController` resuelva reglas desde `getGameRuntime().getItems()` en vez de importar `demo-content/items`. + +## ✅ Success Criteria + +- [ ] `grep -n "setInterval" apps/web-demo/app/components/GameTouchCanvas.tsx` → vacío. +- [ ] Gate técnico verde. +- [ ] En navegador suena igual que antes: música de la escena inicial y al cambiar de escena, recoger gameboy (sonido propio), recoger otro ítem, colocar, transición; silencio al devolver un ítem y en recogida bloqueada. +- [ ] Checks de audio pendientes de `phase-11-audio/tracking.md` marcados. diff --git a/docs/phases/phase-16-runtime-in-library/tasks/08-storage-port-persistence.md b/docs/phases/phase-16-runtime-in-library/tasks/08-storage-port-persistence.md new file mode 100644 index 0000000..dc012af --- /dev/null +++ b/docs/phases/phase-16-runtime-in-library/tasks/08-storage-port-persistence.md @@ -0,0 +1,49 @@ +# Task 16.08 — Persistencia vía `StoragePort` + +**Effort**: 1.5h | **Modelo**: haiku | **Blocks**: 13 | **Blocked by**: Fase 15 + +**Archivos permitidos**: +- `apps/web-demo/app/lib/engine/runtime/useInventoryRuntimeController.ts` (solo las líneas de `localStorage`) +- `apps/web-demo/app/lib/engine/runtime/useSceneRuntimeController.ts` (solo las líneas de `localStorage`) +- `apps/web-demo/app/components/InventoryUI.tsx` (solo la línea de `localStorage.clear()`) +- `apps/web-demo/app/lib/gamePersistence.ts` (nuevo) + +--- + +## 🎯 Objetivo + +Tres sitios acceden a `localStorage` directamente, saltándose el adapter que el repo ya tiene (`localStorageAdapter` en `apps/web-demo/app/lib/platform-web.ts`, con fallback SSR): + +- `useInventoryRuntimeController.ts` — clave `"inventory-slots"` +- `useSceneRuntimeController.ts` — clave `"current-scene-id"` +- `InventoryUI.tsx:311` — `localStorage.clear()` como "reiniciar partida", que además borra el idioma y los ajustes de audio + +No es el sistema de guardado (eso es la fase narrativa); es dejar un único punto de acceso. + +## 📝 Instructions + +1. Crear `apps/web-demo/app/lib/gamePersistence.ts` con: + ```ts + export const GAME_STORAGE_KEYS = { + inventorySlots: "inventory-slots", + currentSceneId: "current-scene-id", + } as const; + export function loadInventorySlots(): InventorySlotsState | null + export function saveInventorySlots(slots: InventorySlotsState): void + export function loadCurrentSceneId(): string | null + export function saveCurrentSceneId(id: string): void + /** Borra solo el progreso de partida, no idioma ni audio. */ + export function clearGameProgress(): void + ``` + Todo a través de `localStorageAdapter`. Conservar los mismos nombres de clave y el mismo formato JSON (compatibilidad con partidas existentes). `JSON.parse` dentro de `try/catch` devolviendo `null`. +2. `clearGameProgress` debe borrar también las claves de los stores persistidos de la demo: busca los `name:` de `persist(` en `apps/web-demo/app/store/*.ts` (p. ej. `"door-states"`) y añádelos. No borrar `"i18n-locale"` ni la clave de ajustes de audio. +3. Sustituir los accesos directos en los 3 archivos por estas funciones. No cambiar nada más de esos archivos. + +## ✅ Success Criteria + +- [ ] `grep -rn "localStorage" apps/web-demo/app --include=*.ts --include=*.tsx | grep -v "platform-web\|\.test\."` → solo comentarios. +- [ ] `npm run typecheck`, `npm run lint`, `npm test` → verdes. + +## Reporte + +Claves gestionadas, claves que `clearGameProgress` borra y cuáles conserva. diff --git a/docs/phases/phase-16-runtime-in-library/tasks/09-generic-character-sprite.md b/docs/phases/phase-16-runtime-in-library/tasks/09-generic-character-sprite.md new file mode 100644 index 0000000..cc7720f --- /dev/null +++ b/docs/phases/phase-16-runtime-in-library/tasks/09-generic-character-sprite.md @@ -0,0 +1,51 @@ +# Task 16.09 — `CharacterSprite` configurable + +**Effort**: 3h | **Modelo**: sonnet | **Blocks**: 11 | **Blocked by**: 05 + +**Archivos permitidos**: +- `packages/engine-renderer-r3f/src/sprite/**` +- `packages/engine-renderer-r3f/src/GameTouchSpriteRuntime.tsx` (solo el uso del sprite y una prop nueva) +- `packages/engine-renderer-r3f/src/index.ts`, `src/components/index.ts` +- `apps/web-demo/demo-content/characters/david.ts` (nuevo) +- `apps/web-demo/app/components/GameTouchCanvas.tsx` (solo pasar la prop nueva) + +--- + +## 🎯 Objetivo + +El paquete publicado lleva un personaje concreto dentro: `sprite/DavidSprite.tsx` y `sprite/clips.ts` con la ruta `/assets/sprites/david` fija, y `GameTouchSpriteRuntime` lo instancia directamente. Un consumidor no puede usar su propio personaje, y sin esto no habrá NPCs. + +## Diseño + +```ts +export interface CharacterClip { frames: string[]; fps: number; loop?: boolean; mirror?: boolean } +export interface CharacterDefinition { + id: string; + clips: Record<"idle" | "north" | "south" | "west" | "east", CharacterClip>; + speaking?: CharacterClip; + /** Tamaño en unidades de mundo y ancla; valores actuales de David como default. */ + size?: [number, number]; +} +``` + +- `CharacterSprite` = el `DavidSprite` actual, recibiendo `character: CharacterDefinition` en vez de leer constantes del módulo. +- `GameTouchSpriteRuntime` gana la prop `character?: CharacterDefinition`. +- La definición de David se muda a `apps/web-demo/demo-content/characters/david.ts`. + +## 📝 Instructions + +1. Leer `DavidSprite.tsx`, `clips.ts`, `speakingAnimation.ts` y cómo los usa `GameTouchSpriteRuntime.tsx`. Ajustar el diseño de arriba a los campos que el código necesita de verdad (fps, espejado, orden de frames). +2. Implementar `CharacterSprite` y su handle (`CharacterSpriteHandle`). +3. **Compatibilidad**: `DavidSprite`, `DavidSpriteHandle` y lo que hoy exporta `clips.ts` siguen exportándose, marcados `@deprecated`, implementados sobre `CharacterSprite` con la definición de David embebida como default. Si `character` no se pasa, el runtime se comporta exactamente como hoy. +4. La demo pasa `character={DAVID}` explícitamente. +5. Tests: construcción de URLs de frames a partir de una definición, y selección de clip por dirección. + +## ✅ Success Criteria + +- [ ] `npm run build:packages && npm test && npm run typecheck` → verdes. +- [ ] `DavidSprite` sigue siendo importable desde el paquete. +- [ ] Un test instancia la lógica de clips con un personaje distinto de David. + +## Reporte + +Forma final de `CharacterDefinition`, y qué mirar en navegador: animación en las 4 direcciones, idle, y boca al hablar. diff --git a/docs/phases/phase-16-runtime-in-library/tasks/10-wire-player-stop.md b/docs/phases/phase-16-runtime-in-library/tasks/10-wire-player-stop.md new file mode 100644 index 0000000..37e3f2c --- /dev/null +++ b/docs/phases/phase-16-runtime-in-library/tasks/10-wire-player-stop.md @@ -0,0 +1,37 @@ +# Task 16.10 — Comando `player:stop` + +**Effort**: 1h | **Modelo**: haiku | **Blocks**: 13 | **Blocked by**: 02 + +**Archivos permitidos**: +- `packages/engine-core/src/game/runtime/executors.ts` +- `packages/engine-core/src/__tests__/gameRuntimePlayerStop.test.ts` (nuevo) +- `apps/web-demo/app/example-bridge/HtmlBridgePanel.tsx` (solo el texto "deferred v0.2.0" del botón) + +--- + +## 🎯 Objetivo + +`player:stop` está declarado en `GameCommand` pero su executor solo imprime un aviso ("deferred to v0.2.0"). Con el sistema de caminata por ruta de la Fase 10 ya se puede implementar sin tocar el renderer: el estado de caminata vive en `sceneStore.playerWalkingState`. + +## 📝 Instructions + +1. Leer en `packages/engine-core/src/game/state/sceneStore.ts` cómo se define y se limpia `playerWalkingState` (busca `setPlayerWalkingState`). +2. Implementar el executor: + - Si hay una caminata activa (`playerWalkingState?.isActive`): limpiarla con la acción del store y emitir `{ type: "player:walkAborted", reason: "user-input" }`. + - Si no hay caminata activa: no hacer nada y no emitir. +3. Tests (≥ 3): + - Tras `player:walkTo` a un destino alcanzable, `player:stop` deja `playerWalkingState` inactivo o nulo. + - Se emite `player:walkAborted` con `reason: "user-input"` exactamente una vez. + - `player:stop` sin caminata activa no emite nada. +4. En `HtmlBridgePanel.tsx`, quitar el sufijo "(deferred v0.2.0)" de la etiqueta del botón. +5. **No tocar** `inventory:pickup` ni `inventory:drop`: siguen aplazados (dependen de los hotspots de la fase narrativa). + +## ✅ Success Criteria + +- [ ] `cd packages/engine-core && npx vitest run` → 0 fallos. +- [ ] `npx tsc --noEmit -p packages/engine-core` → 0 errores. +- [ ] `grep -n "player:stop" packages/engine-core/src/game/runtime/executors.ts` no contiene `console.warn`. + +## Reporte + +Implementación y salida de los tests. Si el movimiento por teclado/joystick no pasa por `playerWalkingState` (y por tanto `player:stop` no lo detiene), dilo: es una limitación a documentar, no a arreglar aquí. diff --git a/docs/phases/phase-16-runtime-in-library/tasks/11-functional-game-viewport.md b/docs/phases/phase-16-runtime-in-library/tasks/11-functional-game-viewport.md new file mode 100644 index 0000000..212957a --- /dev/null +++ b/docs/phases/phase-16-runtime-in-library/tasks/11-functional-game-viewport.md @@ -0,0 +1,53 @@ +# Task 16.11 — `GameViewport` funcional + +**Effort**: 1–1.5 días (dividir en 11a/11b al empezar) | **Modelo**: sonnet, diseño revisado por opus | **Blocks**: 12, 13 | **Blocked by**: 03, 06, 07, 09 + +--- + +## 🎯 Objetivo + +Hoy `GameViewport` renderiza `GameCanvasCore`, que es un `` vacío. El juego lo monta `GameTouchCanvas.tsx` (526 líneas) mezclando tres cosas: composición del juego, herramientas de debug/editor y UI propia de la demo. Hay que separar la primera y llevarla al renderer. + +## Diseño (a confirmar por el orquestador antes de implementar) + +`GameViewport` en `engine-renderer-r3f` compone lo mínimo jugable: + +- `` + cámara ortográfica + luces + `` +- fondo de escena, `GameTouchSpriteRuntime`, drop targets, ítems colocados, `SceneTransitions` +- cortina de fundido entre escenas +- lee escenas, ítems y diálogos del runtime (`getGameRuntime()`), nunca de `demo-content` + +Puntos de extensión por props: + +```ts +type GameViewportProps = { + debug?: boolean; + onRuntimeEvent?: GameRuntimeEventHandler; // contrato v1, se conserva + character?: CharacterDefinition; + audio?: { port: AudioPort; defaults: AudioDefaultsConfig }; + children?: ReactNode; // contenido extra dentro de (p. ej. SceneDoors de la demo) + overlay?: ReactNode; // UI HTML por encima del canvas + slots?: { inventory?: ComponentType; loader?: ComponentType<{ ready: boolean }> }; +}; +``` + +Se queda en la demo: paneles de debug y editores, joystick, `InventoryUI`, `SceneDoors` + `useDoorSystem`, efecto CRT, intro. + +## 📝 Instructions + +1. **11a — Inventario y traslado de hooks**: mover al renderer los hooks de orquestación que no son de editor (`useSceneRuntimeController`, `useInventoryRuntimeController`, `useTransitionSystem`, `useProximityHintController`), sustituyendo cada import de `demo-content` y de `app/store/*` por datos del runtime o por parámetros. Tabla previa obligatoria: hook → dependencias de demo → cómo se inyectan. +2. **11b — Componente**: implementar `GameViewport`, moviendo también `SceneBackgroundPlane`, `SceneCameraControllers`, `SceneDropTargets` y `PlacedSceneItems`. +3. `GameTouchCanvas.tsx` pasa a componer `` + extras de la demo. Objetivo: < 200 líneas. +4. Nueva ruta `apps/web-demo/app/example-minimal/page.tsx`: un juego de 2 escenas y 1 ítem que **solo** importa de los dos paquetes. Es la prueba de que la librería es consumible. + +## ✅ Success Criteria + +- [ ] Gate técnico verde. +- [ ] `grep -rln "demo-content" packages/` → vacío. +- [ ] `/example-minimal` arranca y permite moverse, recoger el ítem y cambiar de escena. +- [ ] Demo principal sin regresiones en el smoke completo. +- [ ] `GameViewportProps` conserva `debug` y `onRuntimeEvent`. + +## Riesgo + +Es la tarea de mayor riesgo de la fase. Si al hacer la tabla del paso 1 algún hook resulta inseparable de los stores de la demo, parar y replantear con el orquestador antes de mover nada. diff --git a/docs/phases/phase-16-runtime-in-library/tasks/11-steps.md b/docs/phases/phase-16-runtime-in-library/tasks/11-steps.md new file mode 100644 index 0000000..85c9968 --- /dev/null +++ b/docs/phases/phase-16-runtime-in-library/tasks/11-steps.md @@ -0,0 +1,44 @@ +# Task 16.11 — Troceo en pasos (tras el inventario de dependencias) + +Complementa [11-functional-game-viewport.md](11-functional-game-viewport.md). Sale del inventario de dependencias del 2026-10-10. Regla: **tras cada paso el juego sigue funcionando**: el orquestador ejecuta el gate técnico y `npm run smoke` (recorrido headless con Playwright: partida nueva, bloqueo de salida sin trofeo, recogida, transición, recarga y registro de los sonidos reproducidos; requiere la demo en marcha). + +## Decisiones de diseño (orquestador) + +1. **Spawn al cambiar de escena**: `scene:set` gana `spawnPosition?` opcional (aditivo). Los hooks movidos dejan de llamar al store con una escena resuelta a mano. +2. **Lógica propia del juego fuera del paquete**, como datos o callbacks de `GameViewport`: + - `initialSceneId`, `initialInventory`, `slotCount` + - `getInitialPlacedItems(sceneId, all)` — hoy el trofeo de `personalRoom` + - `onSceneEnter(sceneId, api)` — hoy la bienvenida de `personalRoom` + - `canLeaveScene(transition)` — hoy "no salgas sin el trofeo". No se modela como regla del core: eso es la fase narrativa. +3. **Persistencia por puerto**: `storage?: GameProgressStorage`. Sin él no se guarda. La demo lo implementa sobre `gamePersistence.ts`, mismas claves y formato. +4. **Estado de UI del juego al core**: store de diálogo y de visibilidad de inventario, cableados por defecto en `createGameRuntime` cuando no se pasan adapters. Slots e ítems colocados pasan a stores reactivos del core y desaparece la copia duplicada (estado local + `placedItemsStore`). +5. **Puertas se quedan en la demo** (ADR-0009 §5): `SceneDoors` entra por `children`, `useDoorSystem` compone `onRuntimeEvent` y `getEffectiveClickGoal`. +6. **La UI de la demo lee del viewport por un hook** (`useGameViewportApi`), no por render prop: `InventoryUI` y el panel de debug necesitan slots, arrastre e ítems colocados. + +## Pasos + +| Paso | Qué | Modelo | Ola | +|---|---|---|---| +| 11.1 | Borrar `AnimatedSprite.tsx` (código muerto). Mover al renderer `PlacedSceneItems`, `SceneDropTargets`, `SceneBackgroundPlane` (+`preloadSceneBackground`), `SceneCameraControllers` y `useProximityHintController`; exportar constantes de cámara | sonnet | D1 | +| 11.2 | Core: `spawnPosition?` en `scene:set`; stores de diálogo y de visibilidad de inventario con cableado por defecto; tests headless | sonnet | D1 | +| 11.3 | Demo adopta los stores de UI del core; registrar ítems en el runtime y resolver reglas desde él | sonnet | D2 | +| 11.4 | Mover `useSceneRuntimeController` (store + siembra + persistencia) con `initialSceneId` y `storage` | sonnet | D2 | +| 11.5 | Mover `useTransitionSystem` con `canLeaveScene` inyectado | sonnet | D3 | +| 11.6 | Core: stores reactivos de slots e ítems colocados con persistencia por puerto | sonnet | D3 | +| 11.7 | Mover `useInventoryRuntimeController` (a: stores y persistencia; b: siembra y bienvenida) | sonnet | D4 | +| 11.8 | `GameViewport` en el renderer + `useGameViewportApi`; `GameTouchCanvas` lo compone | sonnet | D5 | +| 11.9 | Ruta `/example-minimal` solo con imports de paquetes | haiku | D5 | + +## Riesgos y prueba manual por ola + +- **Orden de montaje / escena inicial**: recargar con almacenamiento vacío y con `current-scene-id` guardado. +- **Ítems colocados duplicados o perdidos**: recoger el trofeo, recargar; colocarlo en `town`, recargar. +- **Bloqueo de salida y espera al diálogo**: salir de `personalRoom` con y sin trofeo. +- **Puertas**: llave en la verja, recargar, click al otro lado con la puerta cerrada. +- **Partidas guardadas**: cargar una partida anterior y "reiniciar partida". + +## Deuda anotada (no se resuelve aquí) + +- `zustand` `create` en el core arrastra el binding de React; valorar `zustand/vanilla` antes de 1.0. +- Outcomes legacy (`rule-miss`, `on-player`, `pickup-blocked`, `item-interact`, `unknown-item`) siguen viajando como `item:dropped` fuera del tipo. +- `/debug` monta el canvas sin runtime: no tiene audio por bus ni diccionarios i18n. diff --git a/docs/phases/phase-16-runtime-in-library/tasks/12-rewrite-consumption-docs.md b/docs/phases/phase-16-runtime-in-library/tasks/12-rewrite-consumption-docs.md new file mode 100644 index 0000000..62b069f --- /dev/null +++ b/docs/phases/phase-16-runtime-in-library/tasks/12-rewrite-consumption-docs.md @@ -0,0 +1,35 @@ +# Task 16.12 — Reescribir docs de consumo + +**Effort**: 2h | **Modelo**: haiku (con plantilla del orquestador) | **Blocks**: 13 | **Blocked by**: 11 + +**Archivos permitidos**: `docs/LIBRARY_CONSUMPTION_GUIDE.md`, `docs/LIBRARY_API_CONTRACT_V1.md`, `docs/architecture/01-layers.md`, `docs/architecture/02-public-api.md`, `packages/*/README.md`, `packages/*/CHANGELOG.md`, `CLAUDE.md` (solo tabla "Dónde va cada cosa" y sección "API Pública"). + +--- + +## 🎯 Objetivo + +Que la documentación describa lo que el código hace tras la Fase 16. Cada afirmación debe poder comprobarse contra un archivo. + +## 📝 Instructions + +1. Quitar los avisos "⚠️ Desfase conocido (2026-10-10)" añadidos en la Fase 15. +2. `LIBRARY_CONSUMPTION_GUIDE.md`: cada bloque de código debe compilar. Método: copiar el ejemplo de `apps/web-demo/app/example-minimal/page.tsx` como "Flujo canónico" en vez de escribir ejemplos nuevos. Para cada `import { X } from ""` del documento, comprobar que `X` aparece en el `src/index.ts` de ese paquete. +3. `LIBRARY_API_CONTRACT_V1.md`: + - "Archivo fuente" pasa a ser `packages/engine-core/src/game/runtime/` + `packages/engine-renderer-r3f/src/index.ts`; `publicApi.ts` se menciona como barrel de compatibilidad. + - Añadir los exports nuevos de 0.5.0 (`CharacterSprite`, `CharacterDefinition`, `attachAudioSystem`, props nuevas de `GameViewport`, `transitions` en `GameSceneConfig`). + - Nota de corrección: `GameActions.setScene(sceneId)`. + - Sección 3 "No soportado": actualizar rutas (ya no existen `app/lib/engine/render/*` ni `movement/*`). +4. `architecture/02-public-api.md`: actualizar "Ubicación actual". +5. `architecture/01-layers.md` y tabla de `CLAUDE.md`: reflejar que el runtime está en core y la orquestación R3F en el renderer. +6. `CHANGELOG.md` de ambos paquetes: entrada `0.5.0` con Added / Changed / Deprecated (`DavidSprite`). +7. Ningún documento nuevo. Ningún documento por encima de 200 líneas. + +## ✅ Success Criteria + +- [ ] `grep -rn "Desfase conocido" docs` → vacío. +- [ ] Todos los símbolos importados en los ejemplos existen en el `index.ts` correspondiente (pegar la comprobación en el reporte). +- [ ] `wc -l` de cada archivo tocado ≤ 200. + +## Reporte + +Lista de afirmaciones corregidas y cualquier ejemplo que no hayas podido verificar. diff --git a/docs/phases/phase-16-runtime-in-library/tasks/13-validation-gate.md b/docs/phases/phase-16-runtime-in-library/tasks/13-validation-gate.md new file mode 100644 index 0000000..82713e8 --- /dev/null +++ b/docs/phases/phase-16-runtime-in-library/tasks/13-validation-gate.md @@ -0,0 +1,58 @@ +# Task 16.13 — Gate de validación y release 0.5.0 + +**Effort**: 2h | **Modelo**: opus (orquestador) | **Blocks**: fase narrativa | **Blocked by**: todas + +--- + +## 🎯 Objetivo + +Validar la fase completa y dejarla lista para publicar. Publicar en npm **no** forma parte de esta tarea: requiere orden explícita del owner. + +## 📝 Instructions + +### 1. Gate técnico (con `dist/` borrado antes) + +```bash +npm run build:packages && npm test && npm run typecheck && npm run lint && npm run build +``` + +### 2. Fronteras + +```bash +grep -rln "demo-content\|apps/web-demo" packages/ # vacío +grep -rln "demo-content" apps/web-demo/app # solo puntos de composición (page.tsx, rutas example-*) +ls apps/web-demo/app/lib/engine/render apps/web-demo/app/lib/core # no existen +``` + +### 3. Contrato v1 + +Comparar la lista de exports de `publicApi.ts` con la sección 2.1 de `LIBRARY_API_CONTRACT_V1.md`: ningún nombre ausente. + +### 4. Consumo real + +```bash +npm pack -w packages/engine-core -w packages/engine-renderer-r3f +``` + +Instalar los dos `.tgz` en un proyecto Next.js vacío fuera del monorepo (en el directorio temporal de la sesión), copiar `example-minimal/page.tsx` y comprobar que compila y arranca. Es la única prueba que detecta dependencias ocultas del monorepo. + +### 5. Smoke en navegador (skill `run-web-demo`) + +Demo principal: intro, movimiento por click/teclado, recoger y colocar ítems, puerta con llave, las transiciones de las 3 escenas conectadas, música y SFX, cambio de idioma, persistencia tras recargar, "reiniciar partida" conserva idioma y audio. Además `/example-minimal`, `/example-bridge` y `/debug`. + +### 6. Release + +- Versión `0.5.0` en ambos `package.json` y en las constantes `VERSION` / `RENDERER_VERSION`. +- CHANGELOG revisado. +- ADR-0009 enlazado desde el issue; cerrar el issue al fusionar. +- Estado de la fase → `completed`; actualizar `docs/README.md` y "Fase activa" en `CLAUDE.md`. + +### 7. Retrospectiva de una página en el README de la fase + +Qué quedó fuera y pasa a la fase narrativa (mínimo: `inventory:pickup`/`drop`, puertas en core, trocear `GameTouchSpriteRuntime`). + +## ✅ Success Criteria + +- [ ] Pasos 1–5 sin fallos. +- [ ] Versiones y CHANGELOG coherentes. +- [ ] Ningún check de `tracking.md` marcado sin evidencia. diff --git a/docs/phases/phase-16-runtime-in-library/tracking.md b/docs/phases/phase-16-runtime-in-library/tracking.md new file mode 100644 index 0000000..17ad001 --- /dev/null +++ b/docs/phases/phase-16-runtime-in-library/tracking.md @@ -0,0 +1,57 @@ +# Phase 16 — Tracking + +> Marca `[x]` solo con Success Criteria validados. El orquestador integra y valida entre olas. + +## Previo + +- [x] Fase 15 cerrada (gate verde) +- [x] [01-adr-and-issue](tasks/01-adr-and-issue.md) — opus + +## Ola A — en paralelo + +- [x] [02-core-runtime-factory](tasks/02-core-runtime-factory.md) — sonnet +- [x] [05-delete-render-duplicates](tasks/05-delete-render-duplicates.md) — haiku +- [x] [08-storage-port-persistence](tasks/08-storage-port-persistence.md) — haiku + +## Ola B — en paralelo + +- [x] [03-renderer-state-hooks-and-barrel](tasks/03-renderer-state-hooks-and-barrel.md) — sonnet +- [x] [04-unify-scene-types](tasks/04-unify-scene-types.md) — sonnet +- [x] [10-wire-player-stop](tasks/10-wire-player-stop.md) — haiku + +## Ola C — en paralelo + +- [x] [06-unify-inventory-rules](tasks/06-unify-inventory-rules.md) — sonnet +- [x] [07-declarative-audio-wiring](tasks/07-declarative-audio-wiring.md) — sonnet — _completada vía 07b_ +- [x] [07b-enable-declarative-audio](tasks/07b-enable-declarative-audio.md) — sonnet — _opción A; pendiente de prueba de sonido del owner_ +- [x] [09-generic-character-sprite](tasks/09-generic-character-sprite.md) — sonnet + +> Smoke tras olas A–C verificado a mano por el owner (2026-10-10): caminar y hablar, colocar/recoger gameboy, devolución fuera de diana, verja con llave, transiciones, música y SFX. + +## Ola D + +- [x] [11-functional-game-viewport](tasks/11-functional-game-viewport.md) — sonnet — _hecha en 9 pasos ([11-steps](tasks/11-steps.md)); validada con `npm run smoke` (40/40 y 5/5)_ + +## Ola E + +- [x] [12-rewrite-consumption-docs](tasks/12-rewrite-consumption-docs.md) — haiku +- [x] [13-validation-gate](tasks/13-validation-gate.md) — opus + +## Gate final + +- [x] Gate técnico verde (`build:packages`, `test`, `typecheck`, `lint`, `build`) +- [x] `coreAgnosticism.test.ts` verde +- [x] Contrato v1: todos los nombres siguen exportándose desde `publicApi.ts` +- [x] `apps/web-demo/app/lib/engine/render/` y `app/lib/core/` no existen +- [x] Ejemplo mínimo de consumo (solo imports de paquetes) arranca en navegador — _`/example-minimal`, smoke 5/5_ +- [x] Smoke completo de la demo sin regresiones +- [x] CHANGELOG y versión 0.5.0 en ambos paquetes + +## Evidencia del gate final (2026-10-10) + +- Desde `dist/` borrado: `build:packages`, `test` (503: core 348, renderer 109, demo 46), `typecheck` (0 errores), `lint` (0 errores, 1 warning de ``), `build` (5 rutas). +- `npm run smoke`: 40/40 en la demo y 5/5 en `/example-minimal`. +- Contrato v1: 64 nombres exportados por `publicApi.ts` en `main`, 64 ahora, 0 perdidos. +- Fronteras: ningún archivo de `packages/*/src` referencia la demo. +- Consumo real: los dos `.tgz` de `npm pack` instalados en un proyecto Next.js vacío fuera del monorepo; compila y pasa el smoke del ejemplo mínimo 5/5 en producción. +- Sin verificar: modo debug con sus paneles de editor, cámara libre, cambio de idioma en vivo, Safari/iOS. diff --git a/docs/phases/phase-17-narrative-primitives/README.md b/docs/phases/phase-17-narrative-primitives/README.md new file mode 100644 index 0000000..888f419 --- /dev/null +++ b/docs/phases/phase-17-narrative-primitives/README.md @@ -0,0 +1,83 @@ +# Phase 17 — Narrative Primitives + +**Objetivo**: que una aventura completa se pueda describir con datos y jugarse de principio a fin, también en headless. +**Duración estimada**: 2–3 semanas +**Estado**: completed (2026-10-11; 0.6.0 lista, sin publicar) +**Owner**: Daniel Martínez Sebastián +**Version target**: v0.6.0 (solo adiciones sobre 0.5.0) + +--- + +## Por qué + +Ver [ADR-0010](../../decisions/0010-declarative-narrative-model.md). El motor ya es consumible (Fase 16), pero solo sabe mover, recoger, colocar y cambiar de escena. Falta todo lo que hace una aventura: recordar lo ocurrido, mirar, usar, hablar, elegir, encadenar acciones y guardar. + +## Resultado esperado + +1. Un test headless en `engine-core` carga una mini-aventura de fixture (3 escenas, 2 NPCs, 5 ítems, 4 puzzles) y la resuelve solo con comandos, comprobando el estado final. +2. La demo expresa con datos sus reglas actuales (trofeo, bienvenida, ítems iniciales) y deja de usar `canLeaveScene`, `onSceneEnter` y `getInitialPlacedItems`. `npm run smoke` sigue en verde. +3. La demo incluye al menos un NPC con un diálogo con opciones, un hotspot con "mirar" y "usar", y una combinación de ítems, cubiertos por el smoke. +4. Guardar y cargar restaura la partida completa desde una sola clave versionada; las partidas de 0.5.0 migran. +5. Guía de autoría: cómo escribir una escena, un puzzle y un diálogo. + +## Tareas y reparto + +| # | Tarea | Modelo | Depende de | +|---|---|---|---| +| 01 | [ADR-0010: visto bueno](tasks/01-adr-approval.md) | opus | — | +| 02 | [Core: `ClockPort`](tasks/02-clock-port.md) | haiku | 01 | +| 03 | [Core: estado de mundo (flags)](tasks/03-world-state.md) | sonnet | 01 | +| 04 | [Core: condiciones](tasks/04-conditions.md) | sonnet | 03 | +| 05 | [Core: acciones y secuenciador](tasks/05-actions-and-sequencer.md) | sonnet | 02, 04 | +| 05b | [Renderer: avisar del fin de una caminata](tasks/05b-renderer-walk-completed.md) | sonnet | 05 | +| 06 | [Core: hotspots con verbos](tasks/06-hotspots.md) | sonnet | 05 | +| 07 | [Core: árboles de diálogo](tasks/07-dialogue-trees.md) | sonnet | 05 | +| 08 | [Core: combinar ítems](tasks/08-item-combine.md) | haiku | 05 | +| 09 | [Core: reglas de escena declarativas](tasks/09-declarative-scene-rules.md) | sonnet | 05 | +| 10 | [Core: guardado único y migración](tasks/10-save-load.md) | sonnet | 03 | +| 11 | [Core: tipar los outcomes legacy](tasks/11-legacy-outcomes.md) | haiku | — | +| 12 | [Core: validador de contenido](tasks/12-content-validator.md) | sonnet | 06, 07, 08, 09 | +| 13 | [Renderer: hotspots y verbos](tasks/13-renderer-hotspots.md) | sonnet | 06 | +| 14 | [NPCs (core + renderer)](tasks/14-renderer-npcs.md) | sonnet | 06, 07 | +| 15 | [Renderer: UI de diálogo con opciones](tasks/15-renderer-dialogue-ui.md) | sonnet | 07 | +| 16 | [Demo: migrar reglas a datos y añadir contenido de prueba](tasks/16-demo-migration.md) | sonnet | 09, 10, 12, 13, 14, 15 | +| 17 | [Recorrido headless de una mini-aventura](tasks/17-headless-walkthrough.md) | sonnet | 06–10, 12 | +| 18 | [Guía de autoría, docs y changelog](tasks/18-authoring-docs.md) | haiku | 16, 17 | +| 19 | [Gate de validación y 0.6.0](tasks/19-validation-gate.md) | opus | todas | + +Olas: **A** = 02, 03, 11 · **B** = 04, 10 · **C** = 05 · **D** = 06, 07, 08, 09 · **E** = 12, 13, 14, 15 · **F** = 16, 17 · **G** = 18, 19. + +## Principios + +- Regla de Oro intacta: todo el intérprete vive en `engine-core`, sin React ni navegador; `coreAgnosticism.test.ts` sigue verde. +- Aditivo: ningún export, comando ni evento de 0.5.0 cambia de forma. Lo nuevo es opcional. +- El contenido es serializable: sin funciones dentro de escenas, ítems ni diálogos. Excepción única y explícita: la acción `call`. +- Cada primitiva llega con tests headless antes de tener cara en el renderer. +- Validación tras cada tarea: gate técnico y `npm run smoke`. El smoke se amplía cuando una tarea añade comportamiento visible. + +## Fuera de alcance + +- Puertas como primitiva del motor → Fase 7 (los flags de esta fase la simplifican). +- Historia, arte y contenido definitivo de la demo → [Fase 18](../phase-18-story-demo/). +- Cinemáticas con cámara, editor visual de contenido, adaptador de Ink/Yarn. +- Multijugador → Fase 14, después de esta. + +## Retrospectiva (2026-10-11) + +**Resultado**: las 20 tareas integradas. Una mini-aventura de tres escenas escrita solo con datos se resuelve en un test sin renderer, y la demo usa NPC, hotspot con verbos, diálogo con opciones y combinación de ítems, cubiertos por el smoke (69 + 8 comprobaciones). Evidencia del gate en [tracking.md](tracking.md). + +**Lo que destapó la integración** (ningún test unitario lo veía): +- Nadie emitía `player:walkCompleted`; un `walkTo` de guion se habría colgado en el navegador (tarea 05b). +- El bocadillo se cerraba sin emitir `dialog:dismissed`; un `say` de guion se habría colgado igual. +- La caja clicable de un NPC solo cubría los pies, y el menú de verbos mostraba claves sin traducir. +- El validador daba por error la etiqueta libre `interactionId` de un ítem colocado. + +**Qué quedó fuera o como deuda** (entrada para la Fase 18): +- Las reglas declarativas de escena (`initialItems`, `onEnter`, `when`/`blocked`) las cablean por separado el renderer y `createPlaythrough`; deberían vivir en el core. +- El texto de `say` se resuelve por reglas registradas o por un `dialogAdapter` del host; el viewport no lo traduce solo con su i18n. +- `validateContent` no avisa de un `speaker` que no es el id de ningún NPC. +- Combinar ítems arrastrando solo existe en la `InventoryUI` de la demo, no en el renderer. +- Un host con `resolveScene` propio debe proyectar él los NPCs a hotspots. +- Los NPCs no caminan ni tienen clip de habla obligatorio; no hay cámara que siga al jugador (el fondo Sci Fi Level completo la necesitaría). +- Sigue habiendo dos sistemas de movimiento (click en el suelo y `player:walkTo`) y registros globales de módulo. +- Sin verificar en móvil real: la corrección del temblor del sprite al caminar y la UI de opciones de diálogo en táctil. diff --git a/docs/phases/phase-17-narrative-primitives/tasks/01-adr-approval.md b/docs/phases/phase-17-narrative-primitives/tasks/01-adr-approval.md new file mode 100644 index 0000000..cf0794a --- /dev/null +++ b/docs/phases/phase-17-narrative-primitives/tasks/01-adr-approval.md @@ -0,0 +1,18 @@ +# Task 17.01 — ADR-0010: visto bueno + +**Effort**: 30min | **Modelo**: opus (orquestador) | **Blocks**: todas | **Blocked by**: owner + +## 🎯 Objetivo + +Confirmar con el owner el modelo de [ADR-0010](../../../decisions/0010-declarative-narrative-model.md) antes de escribir código. Puntos a confirmar: + +1. Contenido narrativo como datos serializables, con `call` como única vía de escape. +2. Vocabulario inicial de condiciones y acciones (lista en el ADR). +3. Hotspots y NPCs como campos nuevos de la escena (`hotspots`, `npcs`), sin tocar `interactions`. +4. Guardado en una sola clave versionada, con migración desde las cuatro claves de 0.5.0. +5. Versión objetivo 0.6.0, todo aditivo. + +## ✅ Success Criteria + +- [ ] ADR en estado `accepted`, con los cambios que pida el owner incorporados. +- [ ] Si algún punto cambia el contrato v1 (no debería), issue abierto según `CLAUDE.md`. diff --git a/docs/phases/phase-17-narrative-primitives/tasks/02-clock-port.md b/docs/phases/phase-17-narrative-primitives/tasks/02-clock-port.md new file mode 100644 index 0000000..acd9e84 --- /dev/null +++ b/docs/phases/phase-17-narrative-primitives/tasks/02-clock-port.md @@ -0,0 +1,38 @@ +# Task 17.02 — Core: `ClockPort` + +**Effort**: 1h | **Modelo**: haiku | **Blocks**: 05 | **Blocked by**: 01 + +**Archivos permitidos**: `packages/engine-core/src/ports/clock.ts`, `ports/headlessClock.ts`, `ports/index.ts` (añadir exports), `src/__tests__/clockPort.test.ts`. + +## 🎯 Objetivo + +El secuenciador de guiones (tarea 05) necesita esperar ("wait 500 ms") sin usar `setTimeout` directamente, para que los tests no dependan del tiempo real. + +## API + +```ts +export interface ClockPort { + now(): number; // ms + setTimeout(fn: () => void, ms: number): () => void; // devuelve la cancelación +} +/** Implementación por defecto sobre globalThis.setTimeout y Date.now. */ +export const systemClock: ClockPort; +/** Reloj manual para tests: el tiempo solo avanza con advance(ms). */ +export class HeadlessClock implements ClockPort { + advance(ms: number): void; // dispara, en orden, los temporizadores vencidos + pending(): number; +} +``` + +## 📝 Instructions + +1. Mira `ports/gameLoop.ts` y `ports/headlessGameLoop.ts` para copiar el estilo. +2. `systemClock` usa `globalThis.setTimeout`, `globalThis.clearTimeout` y `Date.now` (no `window`). +3. `HeadlessClock.advance` dispara los temporizadores en orden de vencimiento, incluidos los que un callback programe dentro del mismo `advance` si vencen dentro del intervalo. +4. Tests (≥ 8): orden, cancelación, temporizadores anidados, `advance(0)`, `pending()`. + +## ✅ Success Criteria + +- [ ] `cd packages/engine-core && npx vitest run` verde, incluido `coreAgnosticism.test.ts`. +- [ ] `npx tsc --noEmit -p packages/engine-core` sin errores. +- [ ] `git diff --stat` solo muestra los archivos permitidos. diff --git a/docs/phases/phase-17-narrative-primitives/tasks/03-world-state.md b/docs/phases/phase-17-narrative-primitives/tasks/03-world-state.md new file mode 100644 index 0000000..556faf8 --- /dev/null +++ b/docs/phases/phase-17-narrative-primitives/tasks/03-world-state.md @@ -0,0 +1,47 @@ +# Task 17.03 — Core: estado de mundo (flags) + +**Effort**: 2.5h | **Modelo**: sonnet | **Blocks**: 04, 10 | **Blocked by**: 01 + +**Archivos permitidos**: `packages/engine-core/src/game/state/worldStateStore.ts`, `state/index.ts`, `game/commands/types.ts`, `game/events/types.ts`, `game/runtime/executors.ts`, `game/runtime/createGameRuntime.ts`, `src/__tests__/worldState.test.ts`. + +## 🎯 Objetivo + +Dar al motor memoria: flags con nombre que cualquier regla puede leer y escribir. Es la base de condiciones, guiones y guardado. + +## API + +```ts +export type FlagValue = boolean | number | string; + +// Store reactivo, mismo estilo que dialogStore.ts +type WorldStateStoreState = { + flags: Record; + visitedSceneIds: string[]; + setFlag(name: string, value: FlagValue): void; + clearFlag(name: string): void; + markSceneVisited(sceneId: string): void; + setAll(snapshot: { flags: Record; visitedSceneIds: string[] }): void; + reset(): void; +}; +export const useWorldStateStore; +export function getWorldState(): WorldStateStoreState; + +// Comandos (aditivos) +// { type: "state:setFlag"; name: string; value: FlagValue } +// { type: "state:clearFlag"; name: string } +// Eventos (aditivos) +// { type: "state:flagChanged"; name: string; value?: FlagValue; previous?: FlagValue } +``` + +## 📝 Instructions + +1. Lee `state/dialogStore.ts`, `state/inventoryStore.ts` y cómo `executors.ts` emite por el `bus`. +2. `setFlag` con el mismo valor no notifica ni emite. +3. `visitedSceneIds` se rellena cuando cambia la escena: suscríbete a `scene:changed` dentro de `createGameRuntime` (no importes un store desde otro) y libera la suscripción en `dispose`. +4. Tests (≥ 14): set y clear, sin cambio no emite, evento con `previous`, escenas visitadas sin duplicados, `reset`, `setAll`, comandos por el runtime. + +## ✅ Success Criteria + +- [ ] Tests del core verdes; ningún test existente modificado. +- [ ] `coreAgnosticism.test.ts` verde. +- [ ] Los tipos `GameCommand` y `GameEvent` solo crecen. diff --git a/docs/phases/phase-17-narrative-primitives/tasks/04-conditions.md b/docs/phases/phase-17-narrative-primitives/tasks/04-conditions.md new file mode 100644 index 0000000..9f8ea50 --- /dev/null +++ b/docs/phases/phase-17-narrative-primitives/tasks/04-conditions.md @@ -0,0 +1,52 @@ +# Task 17.04 — Core: condiciones + +**Effort**: 2.5h | **Modelo**: sonnet | **Blocks**: 05 | **Blocked by**: 03 + +**Archivos permitidos**: `packages/engine-core/src/game/narrative/conditions.ts`, `narrative/index.ts`, `src/index.ts` (añadir export), `src/__tests__/conditions.test.ts`. + +## 🎯 Objetivo + +Un tipo de dato para preguntar por el estado del juego sin efectos secundarios. + +## API + +```ts +export type Condition = + | { flag: string; equals?: FlagValue; gte?: number; lte?: number } // sin operador: "es verdadero" + | { hasItem: string; atLeast?: number } + | { itemPlaced: string; inScene?: string; at?: string } // at = interactionId + | { inScene: string } + | { visited: string } + | { all: Condition[] } + | { any: Condition[] } + | { not: Condition }; + +/** Se construye desde los stores; inyectable en tests. */ +export interface ConditionContext { + flags: Record; + inventory: InventorySlotsState; + placedItems: PlacedSceneItem[]; + sceneId: string; + visitedSceneIds: string[]; +} + +/** `undefined` cuenta como verdadero. */ +export function evaluateCondition(condition: Condition | undefined, ctx: ConditionContext): boolean; +/** Lee los stores actuales. */ +export function getConditionContext(): ConditionContext; + +// Constructores para escribir contenido legible: +// flag("x"), flag("n", { gte: 3 }), hasItem("key"), itemPlaced("trophy", { inScene: "room" }), +// inScene("room"), visited("town"), all(a, b), any(a, b), not(a) +``` + +## 📝 Instructions + +1. `evaluateCondition` es pura y no lee stores; `getConditionContext` sí. +2. Casos límite: `all: []` es verdadero; `any: []` es falso. Un flag inexistente es falso para "es verdadero", y con `equals` se compara contra `undefined`. +3. Tests (≥ 25): cada variante, combinaciones anidadas, los casos límite y que los constructores producen los objetos esperados. + +## ✅ Success Criteria + +- [ ] Tests del core verdes; `coreAgnosticism.test.ts` verde. +- [ ] Ningún archivo nuevo por encima de 200 líneas. diff --git a/docs/phases/phase-17-narrative-primitives/tasks/05-actions-and-sequencer.md b/docs/phases/phase-17-narrative-primitives/tasks/05-actions-and-sequencer.md new file mode 100644 index 0000000..eefb431 --- /dev/null +++ b/docs/phases/phase-17-narrative-primitives/tasks/05-actions-and-sequencer.md @@ -0,0 +1,59 @@ +# Task 17.05 — Core: acciones y secuenciador + +**Effort**: 5h | **Modelo**: sonnet | **Blocks**: 06–09, 17 | **Blocked by**: 02, 04 + +**Archivos permitidos**: `packages/engine-core/src/game/narrative/{actions,sequencer,branches,index}.ts`, `game/state/inputLockStore.ts`, `state/index.ts`, `game/commands/types.ts`, `game/events/types.ts`, `game/runtime/{types,executors,createGameRuntime}.ts`, `src/__tests__/sequencer*.test.ts`. + +## 🎯 Objetivo + +El corazón de la fase: ejecutar una lista de acciones en orden, esperando lo que haya que esperar. + +## API + +```ts +export type Action = + | { say: string; speaker?: string } // clave de diálogo; espera al cierre + | { setFlag: string; value?: FlagValue } // por defecto true + | { giveItem: string } + | { removeItem: string } + | { placeItem: PlacedSceneItem } + | { removePlacedItem: string } + | { changeScene: string; spawnPosition?: GameVec3 } + | { walkTo: GameVec3 } // espera al fin o al aborto de la caminata + | { wait: number } // ms, vía ClockPort + | { playSfx: string } + | { startDialogue: string } // tarea 07; espera al final + | { lockInput: boolean } + | { emit: string; payload?: unknown } // evento "custom:" + | { call: string; args?: unknown }; // manejador registrado por el host + +export type Script = Action[]; +export type Branch = { when?: Condition; do: Script }; +/** Devuelve el guion de la primera rama que cumple, o null. */ +export function pickBranch(branches: Branch[] | undefined, ctx: ConditionContext): Script | null; + +export interface ScriptRun { + done: Promise<"finished" | "cancelled">; + cancel(): void; +} +// GameRuntime gana: +// runScript(script: Script, opts?: { interrupt?: boolean }): ScriptRun +// registerHandler(name: string, fn: (args: unknown) => void | Promise): () => void +// Comandos: script:run, script:cancelAll +// Eventos: script:started, script:finished, input:lockChanged, custom: +``` + +## 📝 Instructions + +1. No dupliques lógica: el secuenciador despacha comandos existentes y escucha eventos del `bus`. `say` usa `dialog:trigger` y espera a `dialog:dismissed`; `walkTo` usa `player:walkTo`. +2. Un guion a la vez: `runScript` con otro en curso lo encola; con `{ interrupt: true }` cancela el actual. Cancelar deja el estado coherente (libera el bloqueo de entrada). +3. `call` sin manejador registrado: `console.warn` y continúa. Un manejador puede devolver una promesa. +4. `GameRuntimeConfig` gana `clock?: ClockPort` (por defecto `systemClock`). +5. El bloqueo de entrada vive en un store (`inputLocked`) que el renderer leerá en la tarea 13. +6. Tests (≥ 30) con `HeadlessClock`: cada acción, orden, esperas, cancelación a mitad, cola, `pickBranch`, `call` síncrono y asíncrono, guion vacío. + +## ✅ Success Criteria + +- [ ] Tests del core verdes sin temporizadores reales (ningún test espera tiempo de reloj). +- [ ] `coreAgnosticism.test.ts` verde. Ningún archivo nuevo por encima de 250 líneas. +- [ ] `GameRuntime`, `GameCommand` y `GameEvent` solo crecen. diff --git a/docs/phases/phase-17-narrative-primitives/tasks/05b-renderer-walk-completed.md b/docs/phases/phase-17-narrative-primitives/tasks/05b-renderer-walk-completed.md new file mode 100644 index 0000000..25638fb --- /dev/null +++ b/docs/phases/phase-17-narrative-primitives/tasks/05b-renderer-walk-completed.md @@ -0,0 +1,32 @@ +# Task 17.05b — Renderer: avisar del fin de una caminata + +**Effort**: 1.5h | **Modelo**: sonnet | **Blocks**: 13, 16 | **Blocked by**: 05 + +**Archivos permitidos**: `packages/engine-renderer-r3f/src/hooks/usePlayerWalkAnimation.ts`, `src/GameTouchSpriteRuntime.tsx` (solo el punto donde termina o se interrumpe una caminata por ruta), tests en `src/__tests__/`. + +## 🎯 Objetivo + +La acción `walkTo` del secuenciador (tarea 05) espera a `player:walkCompleted` o `player:walkAborted`. El tipo de evento existe desde la Fase 10, pero **nadie lo emite**: el core solo emite `player:walkAborted` cuando no hay ruta, y el renderer, que es quien sabe cuándo el personaje llega, no emite nada. En el navegador, un guion con `walkTo` se quedaría esperando para siempre. En headless no ocurre porque `instantWalk` lo resuelve. + +## Comportamiento + +- Cuando una caminata por ruta (`playerWalkingState` activo) llega a su destino: emitir `{ type: "player:walkCompleted", position }` por el bus del runtime, una sola vez. +- Cuando una caminata por ruta se interrumpe antes de llegar: + - por entrada del jugador (teclado, joystick o un click nuevo) → `{ type: "player:walkAborted", reason: "user-input" }`; + - por colisión o bloqueo que la detiene → `reason: "collision"`. +- El comando `player:stop` ya emite `walkAborted` desde el core: no duplicarlo. +- El movimiento manual (teclado o joystick sin ruta) no emite ninguno de los dos. + +## 📝 Instructions + +1. Lee `usePlayerWalkAnimation.ts` y cómo `GameTouchSpriteRuntime.tsx` detecta el fin y la interrupción de una caminata y limpia `playerWalkingState`. Lee también el executor de `player:walkTo` y de `player:stop` en `packages/engine-core/src/game/runtime/executors.ts` (solo lectura). +2. Emite por `getGameRuntime()?.emit(...)`. Sin runtime no pasa nada. +3. Cuidado con el doble aviso: un click nuevo durante una caminata sustituye la ruta; debe emitirse un `walkAborted` de la antigua y, al llegar, un `walkCompleted` de la nueva. +4. Extrae a una función pura la decisión "¿qué evento toca emitir en esta transición de estado?" y pruébala (llegada, interrupción por entrada, por colisión, sustitución de ruta, sin caminata). +5. No cambies la animación, la velocidad ni la lógica de llegada: solo se añade el aviso. + +## ✅ Success Criteria + +- [ ] Gate técnico verde; `npm run smoke` 40/40 y 5/5. +- [ ] Comprobación en navegador con un script temporal de Playwright: tras un click en el suelo se recibe exactamente un `player:walkCompleted`; con un segundo click a mitad, un `walkAborted` y después un `walkCompleted`. +- [ ] Ningún archivo del paquete referencia la demo. diff --git a/docs/phases/phase-17-narrative-primitives/tasks/06-hotspots.md b/docs/phases/phase-17-narrative-primitives/tasks/06-hotspots.md new file mode 100644 index 0000000..2b9cbc4 --- /dev/null +++ b/docs/phases/phase-17-narrative-primitives/tasks/06-hotspots.md @@ -0,0 +1,50 @@ +# Task 17.06 — Core: hotspots con verbos + +**Effort**: 4h | **Modelo**: sonnet | **Blocks**: 12, 13, 14, 17 | **Blocked by**: 05 + +**Archivos permitidos**: `packages/engine-core/src/game/types/index.ts` (solo añadir), `game/narrative/hotspots.ts`, `narrative/index.ts`, `game/commands/types.ts`, `game/events/types.ts`, `game/runtime/{types,registry,executors}.ts`, `src/__tests__/hotspots.test.ts`. + +## 🎯 Objetivo + +Que una escena tenga cosas que se pueden mirar, usar y con las que hablar, y que un ítem del inventario se pueda usar sobre ellas. + +## API + +```ts +export type Verb = "look" | "use" | "talk"; + +export interface GameSceneHotspot { + id: string; + label: string; // clave de i18n + position: GameVec3; + halfSize: GameVec3; + rotationY?: number; + visibleWhen?: Condition; + hasCollision?: boolean; + /** Punto al que camina el jugador antes de actuar. Sin él, actúa desde donde está. */ + approach?: GameVec3; + verbs?: Partial>; + useItem?: Record; // por itemId + useItemDefault?: Branch[]; // ítem sin regla propia +} +// GameScene y GameSceneConfig ganan: hotspots?: GameSceneHotspot[] + +// Comando: { type: "hotspot:interact"; hotspotId: string; verb: Verb | "useItem"; itemId?: string } +// Eventos: hotspot:interacted, hotspot:noAction + +/** Entre los verbos con una rama aplicable: talk, luego use, luego look. */ +export function getDefaultVerb(hotspot: GameSceneHotspot, ctx: ConditionContext): Verb | null; +``` + +## 📝 Instructions + +1. El executor resuelve la rama con `pickBranch`, camina a `approach` si existe y ejecuta el guion con el secuenciador. Sin rama aplicable emite `hotspot:noAction`; el host decide qué decir. +2. `toRuntimeScene` debe conservar `hotspots`. +3. Con esto `inventory:pickup` e `inventory:drop` dejan de ser avisos: impleméntalos sobre los stores del core y las reglas de inventario existentes (recoger un ítem colocado por id; soltar un slot sobre una interacción o un hotspot). Añade a esos comandos los campos opcionales que falten sin romper los actuales. +4. Tests (≥ 25): cada verbo, `visibleWhen`, `useItem` con y sin regla, `approach`, verbo por defecto, `noAction`, y los dos comandos de inventario. + +## ✅ Success Criteria + +- [ ] Tests del core verdes; `coreAgnosticism.test.ts` verde. +- [ ] `grep -n "deferred" packages/engine-core/src/game/runtime/executors.ts` vacío. +- [ ] Una escena sin `hotspots` se comporta exactamente como en 0.5.0. diff --git a/docs/phases/phase-17-narrative-primitives/tasks/07-dialogue-trees.md b/docs/phases/phase-17-narrative-primitives/tasks/07-dialogue-trees.md new file mode 100644 index 0000000..05d7370 --- /dev/null +++ b/docs/phases/phase-17-narrative-primitives/tasks/07-dialogue-trees.md @@ -0,0 +1,48 @@ +# Task 17.07 — Core: árboles de diálogo + +**Effort**: 4h | **Modelo**: sonnet | **Blocks**: 12, 14, 15, 17 | **Blocked by**: 05 + +**Archivos permitidos**: `packages/engine-core/src/game/narrative/dialogue.ts`, `narrative/index.ts`, `game/state/dialogueStore.ts`, `state/index.ts`, `game/commands/types.ts`, `game/events/types.ts`, `game/runtime/{types,registry,executors}.ts`, `src/__tests__/dialogueTrees.test.ts`. + +## 🎯 Objetivo + +Conversaciones con varios turnos y opciones que dependen del estado y lo modifican. Hoy un "diálogo" es una frase suelta. + +## API + +```ts +export interface DialogueNode { + id: string; + speaker?: string; // id de NPC o "player" + line?: string; // clave de i18n; sin línea, el nodo solo ejecuta `do` + do?: Script; // efectos al entrar en el nodo + choices?: DialogueChoice[]; // sin opciones, avanza a `next` + next?: string; // id de nodo; sin next ni choices, el diálogo termina +} +export interface DialogueChoice { + text: string; // clave de i18n + when?: Condition; // opción oculta si no se cumple + once?: boolean; // desaparece tras elegirla (se recuerda con un flag interno) + do?: Script; + next?: string; +} +export interface DialogueDefinition { id: string; start: string; nodes: DialogueNode[] } + +// GameRuntimeConfig gana dialogues?: DialogueDefinition[]; registerDialogue(def) +// Store: useDialogueStore { activeDialogueId, node, choices (ya filtradas), start, choose, advance, end } +// Comandos: dialogue:start, dialogue:choose, dialogue:advance, dialogue:end +// Eventos: dialogue:started, dialogue:nodeEntered, dialogue:choiceMade, dialogue:ended +``` + +## 📝 Instructions + +1. Distingue los nombres: `dialogStore` (bocadillo de una frase, existente) y `dialogueStore` (conversación, nuevo). La línea de un nodo se muestra por el camino existente del bocadillo, con `speaker`. +2. `once` se recuerda con un flag reservado `dlg...<índice>` en el estado de mundo, para que se guarde con la partida. +3. La acción `startDialogue` del secuenciador (tarea 05) espera a `dialogue:ended`. +4. Un nodo cuyas opciones quedan todas ocultas se trata como nodo sin opciones. +5. Tests (≥ 25): lineal, ramificado, opciones condicionadas, `once`, efectos de nodo y de opción, fin por falta de `next`, `end` forzado, diálogo dentro de un guion, referencia a nodo inexistente (aviso y fin). + +## ✅ Success Criteria + +- [ ] Tests del core verdes sin temporizadores reales; `coreAgnosticism.test.ts` verde. +- [ ] El bocadillo de una frase existente (`dialog:trigger`) no cambia de comportamiento. diff --git a/docs/phases/phase-17-narrative-primitives/tasks/08-item-combine.md b/docs/phases/phase-17-narrative-primitives/tasks/08-item-combine.md new file mode 100644 index 0000000..eae76d9 --- /dev/null +++ b/docs/phases/phase-17-narrative-primitives/tasks/08-item-combine.md @@ -0,0 +1,38 @@ +# Task 17.08 — Core: combinar ítems + +**Effort**: 1.5h | **Modelo**: haiku | **Blocks**: 12, 16 | **Blocked by**: 05 + +**Archivos permitidos**: `packages/engine-core/src/game/types/index.ts` (solo añadir un campo opcional), `game/runtime/types.ts` (ídem en `GameItemConfig`), `game/narrative/combine.ts`, `narrative/index.ts`, `game/commands/types.ts`, `game/events/types.ts`, `game/runtime/executors.ts`, `src/__tests__/itemCombine.test.ts`. + +## 🎯 Objetivo + +Usar un ítem del inventario sobre otro: "cuerda + gancho = garfio". + +## API + +```ts +// ItemDefinition y GameItemConfig ganan: +// combine?: Record; // por id del otro ítem + +// Comando: { type: "inventory:combine"; itemId: string; withItemId: string } +// Eventos: item:combined { itemId, withItemId }, item:combineFailed { itemId, withItemId } + +/** Busca la regla en `a.combine[b]` y, si no existe, en `b.combine[a]`. */ +export function resolveCombine( + a: ItemDefinition, b: ItemDefinition, ctx: ConditionContext, +): Script | null; +``` + +## 📝 Instructions + +1. Lee `game/narrative/branches.ts` (`pickBranch`) y cómo el executor de `hotspot:interact` (tarea 06) lanza un guion con el secuenciador: haz lo mismo. +2. La combinación es simétrica: basta declararla en uno de los dos ítems. +3. El guion decide el resultado con acciones normales (`removeItem`, `giveItem`, `say`). El executor no quita ni añade ítems por su cuenta. +4. Si alguno de los dos ítems no está en el inventario, o no hay regla aplicable, emite `item:combineFailed` y no ejecuta nada. +5. Tests (≥ 10): regla en el primero, regla en el segundo, sin regla, ítem ausente, rama condicionada, combinación de un ítem consigo mismo (falla). + +## ✅ Success Criteria + +- [ ] Tests del core verdes; `coreAgnosticism.test.ts` verde. +- [ ] Un ítem sin `combine` se comporta exactamente como en 0.5.0. +- [ ] `git diff --stat` solo muestra los archivos permitidos. diff --git a/docs/phases/phase-17-narrative-primitives/tasks/09-declarative-scene-rules.md b/docs/phases/phase-17-narrative-primitives/tasks/09-declarative-scene-rules.md new file mode 100644 index 0000000..f61a81d --- /dev/null +++ b/docs/phases/phase-17-narrative-primitives/tasks/09-declarative-scene-rules.md @@ -0,0 +1,40 @@ +# Task 17.09 — Core: reglas de escena declarativas + +**Effort**: 3.5h | **Modelo**: sonnet | **Blocks**: 12, 16 | **Blocked by**: 05 + +**Archivos permitidos**: `packages/engine-core/src/game/types/index.ts` (solo añadir), `game/runtime/{types,registry,executors,createGameRuntime}.ts`, `game/narrative/sceneRules.ts`, `narrative/index.ts`, `game/logic/rules/transitionRules.ts` (solo añadir), `src/__tests__/sceneRules.test.ts`; y en el renderer `src/hooks/useTransitionSystem.ts`, `src/hooks/useInventoryRuntime.ts`, `src/inventory/seedScene.ts` (para leer las reglas declarativas cuando existan). + +## 🎯 Objetivo + +Tres reglas que la demo escribe hoy como callbacks de TypeScript deben poder ser datos de la escena: + +| Hoy (callback, Fase 16) | Pasa a ser (dato) | +|---|---| +| `getInitialPlacedItems(sceneId, all)` | `scene.initialItems` con condición | +| `onSceneEnter(sceneId, api)` | `scene.onEnter` (ramas) | +| `canLeaveScene(transition)` | `transition.when` + `transition.blocked` (guion) | + +## API + +```ts +// GameScene y GameSceneConfig ganan: +// initialItems?: Array<{ item: PlacedSceneItem; when?: Condition }>; +// onEnter?: Branch[]; +// BaseSceneTransition gana: +// when?: Condition; // si no se cumple, la transición no ocurre +// blocked?: Script; // guion que se ejecuta al intentarlo sin cumplir `when` +``` + +## 📝 Instructions + +1. `initialItems`: se siembran una vez por escena (mecanismo de escenas sembradas del core) evaluando `when` en el momento de entrar. La regla actual del trofeo ("solo si no existe ya un trofeo en ninguna escena") debe poder escribirse con `not(itemPlaced("trophy"))` combinado con `not(hasItem("trophy"))`: comprueba que el vocabulario de condiciones lo cubre y, si no, repórtalo antes de ampliar. +2. `onEnter`: se evalúa en cada entrada a la escena, incluida la inicial y tras recargar, con la misma temporización que hoy tiene la bienvenida (lee el efecto en `useInventoryRuntime.ts`). "Solo la primera vez" se expresa con `not(visited(...))` o con un flag. +3. `when` y `blocked` en transiciones: aplican a todos los tipos de transición. +4. Convivencia: si el host pasa además los callbacks de la Fase 16, se evalúan después de las reglas declarativas y pueden vetar. Documenta el orden en el JSDoc. +5. Tests headless en core (≥ 18) para la lógica; el renderer solo cablea. + +## ✅ Success Criteria + +- [ ] Tests de core y renderer verdes; `coreAgnosticism.test.ts` verde. +- [ ] Una escena sin estos campos se comporta exactamente como en 0.5.0. +- [ ] `npm run smoke` 40/40 y 5/5 (la demo aún usa los callbacks; se migra en la tarea 16). diff --git a/docs/phases/phase-17-narrative-primitives/tasks/10-save-load.md b/docs/phases/phase-17-narrative-primitives/tasks/10-save-load.md new file mode 100644 index 0000000..a8692d3 --- /dev/null +++ b/docs/phases/phase-17-narrative-primitives/tasks/10-save-load.md @@ -0,0 +1,52 @@ +# Task 17.10 — Core: guardado único y migración + +**Effort**: 4h | **Modelo**: sonnet | **Blocks**: 16, 17 | **Blocked by**: 03 + +**Archivos permitidos**: `packages/engine-core/src/game/state/saveGame.ts`, `state/index.ts`, `game/commands/types.ts`, `game/events/types.ts`, `game/runtime/{types,executors,createGameRuntime}.ts`, `src/__tests__/saveGame.test.ts`. La demo no se toca aquí (tarea 16). + +## 🎯 Objetivo + +Hoy la partida son cuatro claves sin versión (`inventory-slots`, `current-scene-id`, `placed-items-state`, `door-states`), escritas desde sitios distintos. Con flags y diálogos hace falta una instantánea única, versionada y migrable. + +## API + +```ts +export const SAVE_FORMAT_VERSION = 1; +export interface GameSnapshot { + version: number; + sceneId: string; + playerPosition: GameVec3; + inventory: InventorySlotsState; + placedItems: PlacedSceneItem[]; + seededSceneIds: string[]; + flags: Record; + visitedSceneIds: string[]; + /** Estado propio del host (p. ej. puertas de la demo). Opaco para el core. */ + extra?: Record; +} +export function captureSnapshot(extra?: Record): GameSnapshot; +export function applySnapshot(snapshot: GameSnapshot): void; +export function saveGame(storage: KeyValueStoragePort, opts?: { key?: string; extra?: … }): void; +export function loadGame(storage: KeyValueStoragePort, opts?: { key?: string }): GameSnapshot | null; +export function clearSave(storage: KeyValueStoragePort, opts?: { key?: string }): void; +/** Construye una instantánea a partir de las cuatro claves de 0.5.0, o null si no hay partida antigua. */ +export function migrateLegacySave(storage, opts: { legacySeededSceneId?: string; defaultSceneId: string }): GameSnapshot | null; + +// GameRuntimeConfig gana storage?: KeyValueStoragePort +// Comandos: game:save, game:load, game:reset. Eventos: game:saved, game:loaded, game:reset +``` + +## 📝 Instructions + +1. Reutiliza `gameStatePersistence.ts` para leer los formatos antiguos; no los reimplementes. +2. `loadGame` devuelve `null` ante JSON inválido, forma inesperada o versión superior a la soportada, sin lanzar. Versiones inferiores pasan por una tabla de migraciones (hoy vacía, con el mecanismo y su test). +3. `applySnapshot` restaura la escena con la posición guardada (`scene:set` con `spawnPosition`). +4. `clearSave` borra solo su clave. Nunca `clear()` del almacenamiento. +5. No hay guardado automático en el core: el host decide cuándo llamar a `game:save`. +6. Tests (≥ 22): ida y vuelta completa, cada formato antiguo con un ejemplo literal, JSON corrupto, versión futura, `extra`, comandos y eventos. + +## ✅ Success Criteria + +- [ ] Tests del core verdes; `coreAgnosticism.test.ts` verde. +- [ ] Ningún archivo nuevo por encima de 250 líneas. +- [ ] Las funciones de persistencia de 0.5.0 siguen exportadas y sin cambios. diff --git a/docs/phases/phase-17-narrative-primitives/tasks/11-legacy-outcomes.md b/docs/phases/phase-17-narrative-primitives/tasks/11-legacy-outcomes.md new file mode 100644 index 0000000..c2646f2 --- /dev/null +++ b/docs/phases/phase-17-narrative-primitives/tasks/11-legacy-outcomes.md @@ -0,0 +1,39 @@ +# Task 17.11 — Core: tipar los outcomes legacy + +**Effort**: 1.5h | **Modelo**: haiku | **Blocks**: 19 | **Blocked by**: — + +**Archivos permitidos**: `packages/engine-core/src/game/events/types.ts`, `game/events/legacyAdapter.ts`, `packages/engine-core/__tests__/gameEvents.test.ts` y `src/__tests__/legacyAdapterPickup.test.ts` (solo añadir casos), `src/__tests__/legacyOutcomes.test.ts` (nuevo). + +## 🎯 Objetivo + +`legacyRuntimeEventToGameEvent` convierte el evento antiguo `onDrop` en `item:dropped` con un cast, así que por el bus viajan valores de `outcome` que el tipo no declara: `rule-miss`, `on-player`, `pickup-blocked`, `item-interact` y `unknown-item`. Quien escucha `item:dropped` con TypeScript no sabe que existen. + +## Decisión de diseño (ya tomada) + +No se inventan eventos nuevos en esta tarea ni se cambia lo que se emite. Se **declara** lo que ya ocurre, sin cast: + +```ts +| { + type: "item:dropped"; + itemId: string; + outcome: + | "consume" | "place" | "return" // resultado de una regla de ítem + | "rule-miss" | "unknown-item" | "on-player" // el drop no aplicó ninguna regla + | "pickup-blocked" | "item-interact"; // legado: no son un drop (ver nota) + interactionId?: string; + } +``` + +Añade un comentario JSDoc que marque `pickup-blocked` e `item-interact` como `@deprecated` en este evento: describen un intento de recogida y un click sobre un ítem colocado, y la tarea 06 les da eventos propios (`hotspot:*`, `inventory:*`). `pickup-success` no aparece: desde 0.5.0 viaja como `item:pickedUp`. + +## 📝 Instructions + +1. Lee `legacyAdapter.ts` y los emisores en `packages/engine-renderer-r3f/src/inventory/dropHandlers.ts` y `pickupHandlers.ts` (solo lectura) para confirmar la lista exacta de valores que se emiten hoy. Si encuentras alguno que no esté en la lista de arriba, añádelo al tipo y repórtalo. +2. Amplía el tipo y elimina el cast del adaptador. Si al quitarlo aparece un error de tipos en otro paquete, no lo fuerces: repórtalo. +3. Tests: un caso por cada valor, comprobando que el adaptador lo conserva tal cual. + +## ✅ Success Criteria + +- [ ] `grep -n " as \"consume\"" packages/engine-core/src/game/events/legacyAdapter.ts` vacío. +- [ ] `npm run build:packages && npm test && npm run typecheck` verdes. +- [ ] Ningún valor emitido cambia: `npm run smoke` 40/40 y 5/5. diff --git a/docs/phases/phase-17-narrative-primitives/tasks/12-content-validator.md b/docs/phases/phase-17-narrative-primitives/tasks/12-content-validator.md new file mode 100644 index 0000000..7d0b82f --- /dev/null +++ b/docs/phases/phase-17-narrative-primitives/tasks/12-content-validator.md @@ -0,0 +1,49 @@ +# Task 17.12 — Core: validador de contenido + +**Effort**: 3h | **Modelo**: sonnet | **Blocks**: 16, 17 | **Blocked by**: 06, 07, 08, 09 + +**Archivos permitidos**: `packages/engine-core/src/game/narrative/validateContent.ts`, `narrative/index.ts`, `game/runtime/{types,createGameRuntime}.ts`, `src/__tests__/validateContent.test.ts`. + +## 🎯 Objetivo + +Con el contenido como datos, los errores típicos de una aventura son referencias rotas: un guion que da un ítem que no existe, una transición a una escena sin registrar, una opción que salta a un nodo inexistente. Hoy se descubrirían jugando. Deben descubrirse al arrancar. + +## API + +```ts +export interface ContentIssue { + severity: "error" | "warning"; + code: string; // p. ej. "unknown-item", "unknown-scene", "unknown-dialogue-node" + where: string; // ruta legible: "scene:town > hotspot:well > verbs.use[0].do[2]" + message: string; +} +export interface GameContent { + scenes: GameSceneConfig[]; + items: GameItemConfig[]; + dialogues?: DialogueDefinition[]; + /** Claves de diálogo conocidas; si se pasa, se validan las claves de `say`, `label`, `line` y `text`. */ + dialogKeys?: ReadonlySet; + /** Nombres de manejadores `call` que el host registra. */ + handlers?: ReadonlySet; +} +export function validateContent(content: GameContent): ContentIssue[]; +// GameRuntimeConfig gana validate?: boolean | "throw" (por defecto: true en desarrollo, avisa por consola) +``` + +## Qué comprueba + +- **Errores**: ids duplicados (escenas, ítems, hotspots, NPCs, transiciones, diálogos, nodos); referencias a escenas, ítems, diálogos, nodos, interacciones o hotspots inexistentes, en cualquier acción o condición; `start` de un diálogo inexistente; nodo sin salida que no es final intencionado. +- **Avisos**: nodos de diálogo inalcanzables; escenas inalcanzables desde la inicial; ítems que nada da ni coloca; flags que se leen y nunca se escriben, y al revés; claves de diálogo desconocidas (si se pasó `dialogKeys`); `call` a un manejador no declarado (si se pasó `handlers`). + +## 📝 Instructions + +1. Un único recorrido genérico de acciones y condiciones (`walkScript`, `walkCondition`) que usen todas las comprobaciones, para que una acción nueva solo haya que enseñársela a un sitio. +2. Función pura: no lee stores ni registros globales. +3. `where` debe bastar para encontrar el dato sin depurar. +4. Tests (≥ 30): un contenido válido sin incidencias y un caso mínimo por cada código. + +## ✅ Success Criteria + +- [ ] Tests del core verdes; `coreAgnosticism.test.ts` verde. +- [ ] Validar el contenido actual de la demo no produce errores (los avisos se listan en el reporte). +- [ ] Ningún archivo nuevo por encima de 300 líneas. diff --git a/docs/phases/phase-17-narrative-primitives/tasks/13-renderer-hotspots.md b/docs/phases/phase-17-narrative-primitives/tasks/13-renderer-hotspots.md new file mode 100644 index 0000000..d415046 --- /dev/null +++ b/docs/phases/phase-17-narrative-primitives/tasks/13-renderer-hotspots.md @@ -0,0 +1,47 @@ +# Task 17.13 — Renderer: hotspots y verbos + +**Effort**: 4h | **Modelo**: sonnet | **Blocks**: 16 | **Blocked by**: 06 + +**Archivos permitidos**: `packages/engine-renderer-r3f/src/scene/SceneHotspots.tsx`, `src/hooks/useHotspotInteractions.ts`, `src/components/VerbMenu.tsx`, `src/viewport/{useGameViewportController.ts,GameViewportView.tsx}`, `src/GameTouchSpriteRuntime.tsx` (solo leer el bloqueo de entrada), `src/index.ts`, tests nuevos en `src/__tests__/`. + +## 🎯 Objetivo + +Que el jugador pueda hacer click en un hotspot y actuar sobre él, y arrastrar un ítem del inventario encima. + +## Comportamiento + +- **Click** sobre un hotspot: ejecuta su verbo por defecto (`getDefaultVerb` del core). Si el hotspot tiene más de un verbo aplicable, aparece un menú de verbos junto al cursor. +- **Arrastrar un ítem** desde la mochila y soltarlo sobre un hotspot: `hotspot:interact` con `verb: "useItem"`. Debe convivir con las dianas de arrastre actuales (`SceneDropTargets`): si el punto de suelta cae sobre ambos, gana la diana (comportamiento de 0.5.0). +- **`hotspot:noAction`**: el viewport muestra una frase genérica configurable (`noActionDialogKey`, por defecto una clave del motor). +- **Bloqueo de entrada**: mientras `inputLocked` del core es verdadero, ni el movimiento por click, teclado o joystick ni los hotspots responden. +- **Depuración**: con `debug`, los volúmenes de los hotspots se pintan como hoy las dianas. + +## API + +```tsx +// Vista: se monta sola si la escena tiene hotspots. +// Props nuevas de GameViewportView / GameViewport: +// verbMenu?: ComponentType // por defecto, VerbMenu del paquete +// noActionDialogKey?: string +export interface VerbMenuProps { + hotspot: GameSceneHotspot; + verbs: Verb[]; + position: { x: number; y: number }; // píxeles de pantalla + labels: Record; // ya traducidas + onSelect(verb: Verb): void; + onClose(): void; +} +``` + +## 📝 Instructions + +1. Toma como modelo `src/inventory/SceneDropTargets.tsx` (volúmenes, detección de suelta) y `src/scene/SceneTransitions.tsx`. +2. `VerbMenu` es HTML sin estilos de la demo: accesible por teclado, con `role="menu"`. +3. Extrae a funciones puras lo que se pueda probar sin React (qué verbos mostrar, resolución de conflicto diana/hotspot) y pruébalo. +4. Añade una comprobación al smoke del ejemplo mínimo solo si el ejemplo gana un hotspot (se decide en la tarea 16). + +## ✅ Success Criteria + +- [ ] Gate técnico verde; ningún archivo del paquete referencia la demo. +- [ ] Una escena sin hotspots se ve y se comporta exactamente como en 0.5.0: `npm run smoke` 40/40 y 5/5. +- [ ] Ningún archivo nuevo por encima de 300 líneas. diff --git a/docs/phases/phase-17-narrative-primitives/tasks/14-renderer-npcs.md b/docs/phases/phase-17-narrative-primitives/tasks/14-renderer-npcs.md new file mode 100644 index 0000000..aced7df --- /dev/null +++ b/docs/phases/phase-17-narrative-primitives/tasks/14-renderer-npcs.md @@ -0,0 +1,49 @@ +# Task 17.14 — NPCs (core + renderer) + +**Effort**: 4h | **Modelo**: sonnet | **Blocks**: 16 | **Blocked by**: 06, 07 + +**Archivos permitidos**: core — `packages/engine-core/src/game/types/index.ts` (solo añadir), `game/runtime/{types,registry}.ts`, `game/narrative/npcs.ts`, `narrative/index.ts`, `src/__tests__/npcs.test.ts`; renderer — `src/scene/SceneNpcs.tsx`, `src/sprite/NpcSprite.tsx`, `src/viewport/{useGameViewportController.ts,GameViewportView.tsx}`, `src/index.ts`, tests nuevos. + +## 🎯 Objetivo + +Personajes en la escena con los que se puede hablar. + +## API + +```ts +export interface GameSceneNpc { + id: string; + name: string; // clave de i18n + /** Id de un personaje registrado en el viewport (prop `characters`). */ + characterId: string; + position: GameVec3; + facing?: "north" | "south" | "west" | "east"; + visibleWhen?: Condition; + hasCollision?: boolean; + approach?: GameVec3; + /** Atajo: hablar inicia este diálogo. Equivale a verbs.talk = [{ do: [{ startDialogue }] }]. */ + dialogueId?: string; + /** Verbos e ítems, igual que un hotspot. */ + verbs?: Partial>; + useItem?: Record; +} +// GameScene y GameSceneConfig ganan: npcs?: GameSceneNpc[] +// GameViewport gana: characters?: Record + +/** Proyecta un NPC a hotspot para reutilizar toda la interacción de la tarea 06. */ +export function npcToHotspot(npc: GameSceneNpc): GameSceneHotspot; +``` + +## 📝 Instructions + +1. Un NPC **es** un hotspot con sprite: el core lo proyecta con `npcToHotspot` y `hotspot:interact` funciona con su id. No dupliques la lógica de verbos. +2. `NpcSprite` reutiliza `CharacterSprite` y los helpers de `sprite/character.ts`: clip `idle` orientado según `facing`, y el clip `speaking` mientras el bocadillo activo tenga `speaker` igual a su id. +3. El bocadillo se coloca sobre quien habla: hoy siempre va sobre el jugador. Lee cómo `GameTouchSpriteRuntime.tsx` posiciona `SpeechBubble` y haz que, con `speaker` de un NPC, se ancle a la posición de ese NPC. Sin `speaker` o con `"player"`, igual que hoy. +4. Escala por profundidad: usa la misma función que el jugador, para que un NPC a la misma distancia tenga el mismo tamaño. +5. Un `characterId` sin registrar: aviso por consola y volumen visible solo en `debug`; no rompe la escena. +6. Tests: `npcToHotspot` (con y sin `dialogueId`, con verbos propios), selección de clip, y visibilidad condicionada. + +## ✅ Success Criteria + +- [ ] Gate técnico verde; `coreAgnosticism.test.ts` verde; ningún archivo del paquete referencia la demo. +- [ ] Una escena sin NPCs se ve y se comporta exactamente como en 0.5.0: `npm run smoke` 40/40 y 5/5. diff --git a/docs/phases/phase-17-narrative-primitives/tasks/15-renderer-dialogue-ui.md b/docs/phases/phase-17-narrative-primitives/tasks/15-renderer-dialogue-ui.md new file mode 100644 index 0000000..48e5576 --- /dev/null +++ b/docs/phases/phase-17-narrative-primitives/tasks/15-renderer-dialogue-ui.md @@ -0,0 +1,49 @@ +# Task 17.15 — Renderer: UI de diálogo con opciones + +**Effort**: 3h | **Modelo**: sonnet | **Blocks**: 16 | **Blocked by**: 07 + +**Archivos permitidos**: `packages/engine-renderer-r3f/src/components/DialogueChoices.tsx`, `src/hooks/useDialogue.ts`, `src/viewport/{useGameViewportController.ts,GameViewportView.tsx}`, `src/index.ts`, tests nuevos en `src/__tests__/`. + +## 🎯 Objetivo + +Mostrar las opciones de una conversación y dejar elegir. La línea de cada nodo ya se muestra con el bocadillo existente; lo que falta es la lista de opciones y el avance. + +## Comportamiento + +- Mientras hay un diálogo activo, la entrada del juego está bloqueada (lo gestiona el core). +- **Nodo sin opciones**: al cerrarse el bocadillo (solo o con un click) se avanza con `dialogue:advance`. +- **Nodo con opciones**: cuando termina de escribirse la línea aparece la lista. Elegir despacha `dialogue:choose`. +- Las opciones llegan ya filtradas y traducibles desde `useDialogueStore`. + +## API + +```tsx +export function useDialogue(): { + active: boolean; + speaker?: string; + choices: Array<{ index: number; text: string }>; // texto ya traducido + choose(index: number): void; + advance(): void; + end(): void; +}; +export interface DialogueChoicesProps { + choices: Array<{ index: number; text: string }>; + onChoose(index: number): void; +} +/** Lista accesible sin estilos de la demo: navegable con flechas, Enter y números 1–9. */ +export function DialogueChoices(props: DialogueChoicesProps): JSX.Element | null; +// GameViewport / GameViewportView ganan: dialogueChoices?: ComponentType +``` + +## 📝 Instructions + +1. Lee `src/SpeechBubble.tsx` para saber cuándo termina de escribirse una línea y cuándo se descarta, y `src/components/LocaleSwitcher.tsx` como modelo de componente del paquete con render sustituible. +2. El bocadillo se cierra solo tras un tiempo de lectura. En un nodo con opciones no debe cerrarse solo: la línea permanece hasta que se elige. Si eso exige una prop nueva en `SpeechBubble`, que sea opcional y con el comportamiento actual por defecto. +3. `DialogueChoices` es HTML superpuesto, con `role="listbox"` y foco gestionado. +4. Extrae a funciones puras la navegación por teclado y pruébala. + +## ✅ Success Criteria + +- [ ] Gate técnico verde; ningún archivo del paquete referencia la demo. +- [ ] Sin diálogos activos, nada cambia respecto a 0.5.0: `npm run smoke` 40/40 y 5/5. +- [ ] Ningún archivo nuevo por encima de 250 líneas. diff --git a/docs/phases/phase-17-narrative-primitives/tasks/16-demo-migration.md b/docs/phases/phase-17-narrative-primitives/tasks/16-demo-migration.md new file mode 100644 index 0000000..9b66de4 --- /dev/null +++ b/docs/phases/phase-17-narrative-primitives/tasks/16-demo-migration.md @@ -0,0 +1,41 @@ +# Task 17.16 — Demo: migrar reglas a datos y añadir contenido de prueba + +**Effort**: 5h (dividir en 16a y 16b) | **Modelo**: sonnet | **Blocks**: 18, 19 | **Blocked by**: 09, 10, 12, 13, 14, 15 + +**Archivos permitidos**: `apps/web-demo/demo-content/**`, `apps/web-demo/app/lib/engine/runtime/{demoSceneRules.ts,demoViewportOptions.ts}`, `apps/web-demo/app/lib/gamePersistence.ts`, `apps/web-demo/app/components/{GameTouchCanvas.tsx,InventoryUI.tsx}`, `apps/web-demo/app/{page.tsx,debug/page.tsx,example-bridge/page.tsx}`, `apps/web-demo/app/example-minimal/**`, `e2e/**`. + +## 🎯 Objetivo + +Demostrar que el modelo declarativo sustituye a los callbacks, y dar al smoke algo narrativo que probar. **No es la historia de la demo** (eso es la Fase 18): es contenido de prueba mínimo sobre las escenas actuales. + +## 16a — Migrar lo existente (sin cambio observable) + +| Hoy | Pasa a | +|---|---| +| `getDemoInitialPlacedItems` (trofeo en `personalRoom`) | `initialItems` de la escena, con su condición | +| `onDemoSceneEnter` (bienvenida) | `onEnter` de la escena | +| `canLeaveSceneDemo` (no salir sin el trofeo) | `when` + `blocked` en la transición `personalRoom → dungeon` | +| Cuatro claves de guardado + `startGamePersistence` | `game:save` sobre una instantánea única; `door-states` va en `extra`; `migrateLegacySave` al arrancar | +| `localStorage` de `clearGameProgress` | `game:reset` + `clearSave` (sigue sin tocar idioma, audio ni claves ajenas) | + +Al terminar, `demoSceneRules.ts` desaparece y `DEMO_VIEWPORT_OPTIONS` no pasa `canLeaveScene`, `onSceneEnter` ni `getInitialPlacedItems`. El guardado automático se dispara al cambiar inventario, ítems colocados, flags, escena o puertas. + +## 16b — Contenido de prueba nuevo + +1. **Un NPC** en `town` (reutilizando el sprite de David con otro id de personaje) con un diálogo de 4–5 nodos: una opción condicionada a tener el trofeo, una opción `once`, y un efecto que pone un flag y entrega un ítem. +2. **Un hotspot** en `personalRoom` con `look` y `use`, y una regla `useItem` para el gameboy. +3. **Una combinación** de dos ítems que produce un tercero (hacen falta dos ítems nuevos sencillos; usa sprites existentes). +4. **`InventoryUI`**: soltar un ítem sobre otro slot despacha `inventory:combine`. +5. Textos en `es` y `en`. +6. **`/example-minimal`** gana un hotspot con `look`, para probar la primitiva sin código de la demo. + +## Smoke + +Amplía `e2e/smoke.mjs` y `e2e/smoke-minimal.mjs` con: hablar con el NPC y elegir una opción (comprobando el flag o el ítem recibido en la partida guardada), mirar el hotspot, combinar los dos ítems, y cargar una partida en el formato de 0.5.0 (inyectada en `localStorage` antes de abrir la página) comprobando que migra. Actualiza las comprobaciones que leían las claves antiguas para que lean la instantánea nueva. + +## ✅ Success Criteria + +- [ ] `grep -rn "canLeaveScene\|onSceneEnter\|getInitialPlacedItems" apps/web-demo/app` vacío. +- [ ] Gate técnico verde; `validateContent` sobre el contenido de la demo sin errores. +- [ ] `npm run smoke` verde con las comprobaciones nuevas; las 40 + 5 anteriores siguen pasando (adaptadas solo en cómo leen el guardado). +- [ ] Captura de `personalRoom` en partida nueva idéntica a la de antes de 16a. diff --git a/docs/phases/phase-17-narrative-primitives/tasks/17-headless-walkthrough.md b/docs/phases/phase-17-narrative-primitives/tasks/17-headless-walkthrough.md new file mode 100644 index 0000000..4a4fa30 --- /dev/null +++ b/docs/phases/phase-17-narrative-primitives/tasks/17-headless-walkthrough.md @@ -0,0 +1,55 @@ +# Task 17.17 — Recorrido headless de una mini-aventura + +**Effort**: 4h | **Modelo**: sonnet | **Blocks**: 18, 19 | **Blocked by**: 06, 07, 08, 09, 10, 12 + +**Archivos permitidos**: `packages/engine-core/src/testing/{playthrough.ts,index.ts}`, `packages/engine-core/package.json` (subpath export `./testing`), `packages/engine-core/src/__tests__/fixtures/miniAdventure.ts`, `src/__tests__/miniAdventure.playthrough.test.ts`. + +## 🎯 Objetivo + +La prueba de que el modelo alcanza: una aventura pequeña pero completa, escrita solo con datos, que un test resuelve de principio a fin sin renderer. Y una utilidad para que cualquier juego hecho con el motor tenga su propio test de recorrido. + +## La mini-aventura de fixture + +Tres escenas, dos NPCs, cinco ítems y cuatro puzzles encadenados, que entre todos ejercitan cada primitiva al menos una vez: + +1. **Recoger y usar**: un ítem del suelo abre un hotspot cerrado (`useItem`, flag). +2. **Conversación con condición**: un NPC solo da una pista si ya se miró un objeto (`look` pone un flag; opción con `when`). +3. **Combinar**: dos ítems producen un tercero. +4. **Intercambio y final**: entregar el ítem combinado a otro NPC desbloquea la transición final (`transition.when`), que ejecuta un guion de cierre y pone el flag `game.finished`. + +Debe incluir además: una transición bloqueada con guion `blocked`, un `onEnter` que solo se dispara la primera vez, una opción `once`, y un `call` a un manejador registrado. + +## API de la utilidad + +```ts +// @pointclick-engine/engine-core/testing +export function createPlaythrough(content: GameContent, opts?: { initialSceneId: string }): { + runtime: GameRuntime; + clock: HeadlessClock; + look(id: string): Promise; + use(id: string): Promise; + talk(id: string): Promise; + useItemOn(itemId: string, id: string): Promise; + combine(a: string, b: string): Promise; + pickUp(placedItemId: string): Promise; + choose(index: number): Promise; + goThrough(transitionId: string): Promise; + /** Avanza el reloj y descarta bocadillos hasta que no quede ningún guion en curso. */ + settle(): Promise; + state(): { sceneId: string; inventory: string[]; flags: Record; dialogueActive: boolean }; + save(): GameSnapshot; + dispose(): void; +}; +``` + +## 📝 Instructions + +1. `createPlaythrough` usa `HeadlessClock` y un almacenamiento en memoria, valida el contenido al crear (lanza si hay errores) y resuelve el pathfinding de forma instantánea: en headless caminar termina de inmediato. +2. Tests: (a) el recorrido completo de principio a fin; (b) cada puzzle intentado en el orden equivocado no avanza; (c) guardar a mitad, crear una partida nueva desde la instantánea y terminar; (d) `validateContent` del fixture sin errores ni avisos. +3. Ningún test usa tiempo real ni `setTimeout`. + +## ✅ Success Criteria + +- [ ] Tests del core verdes; `coreAgnosticism.test.ts` verde. +- [ ] El recorrido completo tarda menos de 1 s. +- [ ] `import { createPlaythrough } from "@pointclick-engine/engine-core/testing"` resuelve tras `npm run build:packages`. diff --git a/docs/phases/phase-17-narrative-primitives/tasks/18-authoring-docs.md b/docs/phases/phase-17-narrative-primitives/tasks/18-authoring-docs.md new file mode 100644 index 0000000..27a01ea --- /dev/null +++ b/docs/phases/phase-17-narrative-primitives/tasks/18-authoring-docs.md @@ -0,0 +1,36 @@ +# Task 17.18 — Guía de autoría, docs y changelog + +**Effort**: 3h | **Modelo**: haiku (con verificación del orquestador) | **Blocks**: 19 | **Blocked by**: 16, 17 + +**Archivos permitidos**: `docs/authoring/{README.md,01-scenes-and-hotspots.md,02-conditions-and-actions.md,03-dialogues-and-npcs.md,04-items-and-combining.md,05-saving-and-testing.md}` (nuevos), `docs/architecture/10-narrative-model.md` (nuevo), `docs/LIBRARY_CONSUMPTION_GUIDE.md`, `docs/LIBRARY_API_CONTRACT_V1.md`, `docs/architecture/05-bidirectional-communication.md`, `docs/README.md`, `packages/*/README.md`, `packages/*/CHANGELOG.md`. Ningún archivo de código. + +## 🎯 Objetivo + +Que alguien que no ha visto el código pueda escribir una escena con un puzzle y un diálogo siguiendo la documentación. + +## Contenido + +- **`docs/authoring/`** — una guía por tema, cada una con un ejemplo completo y corto: + 1. Escenas, transiciones, hotspots y verbos. + 2. Flags, condiciones y acciones; ramas; cuándo usar `call`. + 3. Diálogos con opciones y NPCs. + 4. Ítems, reglas de drop y combinaciones. + 5. Guardado, validación de contenido y test de recorrido con `createPlaythrough`. +- **`docs/architecture/10-narrative-model.md`** — cómo encajan las piezas (estado de mundo → condiciones → ramas → secuenciador → comandos y eventos), con un diagrama de texto. +- **Contrato y guía de consumo** — exports nuevos de 0.6.0, comandos y eventos nuevos, props nuevas de `GameViewport`. +- **CHANGELOG 0.6.0** de ambos paquetes: Added, Changed, Deprecated (los callbacks `canLeaveScene`, `onSceneEnter` y `getInitialPlacedItems` no se eliminan; se marcan como vía avanzada). + +## 📝 Instructions + +1. **Los ejemplos se copian de código que existe y se ejecuta**: el fixture `packages/engine-core/src/__tests__/fixtures/miniAdventure.ts` y el contenido de `apps/web-demo/demo-content/`. No escribas ejemplos de memoria. +2. Para cada símbolo que aparezca en un `import` de un bloque de código, comprueba con grep que el paquete indicado lo exporta. Pega la tabla en el reporte. +3. Para cada tipo que documentes (campos de `GameSceneHotspot`, variantes de `Condition` y `Action`…), copia la lista del archivo de tipos real y cita la ruta. +4. Ningún documento por encima de 200 líneas. Español, mismo tono que el resto de `docs/`. +5. No describas nada como disponible si la tarea que lo implementa no está marcada en `tracking.md`. + +## ✅ Success Criteria + +- [ ] Tabla de verificación de símbolos sin faltas. +- [ ] `wc -l` de cada documento ≤ 200. +- [ ] Todos los enlaces relativos apuntan a archivos que existen. +- [ ] `docs/README.md` enlaza la guía de autoría. diff --git a/docs/phases/phase-17-narrative-primitives/tasks/19-validation-gate.md b/docs/phases/phase-17-narrative-primitives/tasks/19-validation-gate.md new file mode 100644 index 0000000..ad2fc8d --- /dev/null +++ b/docs/phases/phase-17-narrative-primitives/tasks/19-validation-gate.md @@ -0,0 +1,55 @@ +# Task 17.19 — Gate de validación y 0.6.0 + +**Effort**: 2h | **Modelo**: opus (orquestador) | **Blocks**: Fase 18 | **Blocked by**: todas + +## 🎯 Objetivo + +Validar la fase completa y dejar 0.6.0 lista para publicar. Publicar en npm y hacer push no forman parte de esta tarea: requieren orden explícita del owner. + +## 📝 Instructions + +### 1. Gate técnico (con `dist/` borrado antes) + +```bash +npm run build:packages && npm test && npm run typecheck && npm run lint && npm run build +``` + +### 2. Compatibilidad con 0.5.0 + +- Lista de exports de `publicApi.ts` y de los dos `index.ts` de los paquetes: ninguno perdido respecto a la etiqueta o commit de 0.5.0. +- `GameCommand` y `GameEvent`: todas las variantes de 0.5.0 siguen existiendo con la misma forma. +- `/example-minimal` tal como estaba en 0.5.0 (recuperado de git a un archivo temporal) compila y funciona contra 0.6.0. + +### 3. Fronteras + +```bash +grep -rln "demo-content\|apps/web-demo" packages/*/src # vacío +``` + +`coreAgnosticism.test.ts` verde. + +### 4. Narrativa + +- El recorrido headless de la mini-aventura (tarea 17) pasa. +- `validateContent` sobre el contenido de la demo: 0 errores. +- `grep -rn "canLeaveScene\|onSceneEnter\|getInitialPlacedItems" apps/web-demo/app` vacío. + +### 5. Smoke y consumo real + +- `npm run smoke` completo, con las comprobaciones narrativas. +- `npm pack` de ambos paquetes, instalación en un proyecto Next.js vacío fuera del monorepo con una copia de `/example-minimal`, build y smoke del ejemplo. En la Fase 16 esta prueba encontró dos fallos que ningún test veía. + +### 6. Partidas guardadas + +Una partida real de 0.5.0 (las cuatro claves, generadas con el smoke de 0.5.0 o escritas a mano en el formato exacto) carga en 0.6.0 con escena, inventario, ítems colocados y puertas intactos. + +### 7. Release + +- Versión `0.6.0` en ambos `package.json`, en las constantes `VERSION` y `RENDERER_VERSION`, y en el rango de la dependencia del renderer sobre el core. +- CHANGELOG revisado. Estado de la fase `completed`. `docs/README.md` y `CLAUDE.md` actualizados. +- Retrospectiva en el README de la fase: qué quedó fuera y qué primitivas echó en falta el contenido de prueba (entrada directa para la Fase 18). + +## ✅ Success Criteria + +- [ ] Pasos 1–6 sin fallos, con la evidencia anotada en `tracking.md`. +- [ ] Ningún check marcado sin haber ejecutado su comprobación. diff --git a/docs/phases/phase-17-narrative-primitives/tracking.md b/docs/phases/phase-17-narrative-primitives/tracking.md new file mode 100644 index 0000000..e35c988 --- /dev/null +++ b/docs/phases/phase-17-narrative-primitives/tracking.md @@ -0,0 +1,61 @@ +# Phase 17 — Tracking + +> Marca `[x]` solo con Success Criteria validados. Tras cada tarea: gate técnico y `npm run smoke`. + +## Previo + +- [x] [01-adr-approval](tasks/01-adr-approval.md) — opus + +## Ola A — en paralelo + +- [x] [02-clock-port](tasks/02-clock-port.md) — haiku +- [x] [03-world-state](tasks/03-world-state.md) — sonnet +- [x] [11-legacy-outcomes](tasks/11-legacy-outcomes.md) — haiku + +## Ola B — en paralelo + +- [x] [04-conditions](tasks/04-conditions.md) — sonnet +- [x] [10-save-load](tasks/10-save-load.md) — sonnet + +## Ola C + +- [x] [05-actions-and-sequencer](tasks/05-actions-and-sequencer.md) — sonnet +- [x] [05b-renderer-walk-completed](tasks/05b-renderer-walk-completed.md) — sonnet — _añadida al integrar la 05: nadie emitía `player:walkCompleted`_ + +## Ola D — en secuencia (las cuatro amplían los mismos archivos de tipos y executors) + +- [x] [06-hotspots](tasks/06-hotspots.md) — sonnet +- [x] [07-dialogue-trees](tasks/07-dialogue-trees.md) — sonnet +- [x] [08-item-combine](tasks/08-item-combine.md) — haiku +- [x] [09-declarative-scene-rules](tasks/09-declarative-scene-rules.md) — sonnet + +## Ola E — en paralelo + +- [x] [12-content-validator](tasks/12-content-validator.md) — sonnet +- [x] [13-renderer-hotspots](tasks/13-renderer-hotspots.md) — sonnet +- [x] [14-renderer-npcs](tasks/14-renderer-npcs.md) — sonnet +- [x] [15-renderer-dialogue-ui](tasks/15-renderer-dialogue-ui.md) — sonnet + +## Ola F + +- [x] [16-demo-migration](tasks/16-demo-migration.md) — sonnet +- [x] [17-headless-walkthrough](tasks/17-headless-walkthrough.md) — sonnet + +## Ola G + +- [x] [18-authoring-docs](tasks/18-authoring-docs.md) — haiku +- [x] [19-validation-gate](tasks/19-validation-gate.md) — opus + +## Gate final (ejecutado el 2026-10-11) + +- [x] Gate técnico verde desde `dist/` limpio — build de paquetes, tests (core 718, renderer 159, demo 47), typecheck, lint (0 errores) y `next build` +- [x] `coreAgnosticism.test.ts` verde; `grep "demo-content|apps/web-demo" packages/*/src` vacío +- [x] Ningún export, comando ni evento de 0.5.0 cambia de forma — exports: core 176 → 259, renderer 94 → 130, ninguno perdido; `GameCommand` y `GameEvent` de 0.5.0 asignables a los actuales (comprobación de tipos); `/example-minimal` de 0.5.0 sin tocar compila y pasa sus 5 comprobaciones +- [x] Recorrido headless de la mini-aventura resuelto solo con comandos (14 tests; recorrido completo en ~13 ms) +- [x] La demo no usa `canLeaveScene`, `onSceneEnter` ni `getInitialPlacedItems` (grep vacío) +- [x] `npm run smoke` verde, ampliado con NPC, diálogo con opciones, hotspot y combinación — 69/69 y 8/8 +- [x] Una partida guardada con 0.5.0 carga con 0.6.0 — comprobación del smoke con las cuatro claves antiguas inyectadas: escena, inventario, ítem colocado y puertas intactos, y sin resembrar el trofeo +- [x] Consumo real: `npm pack` de ambos paquetes instalado en un proyecto Next.js fuera del monorepo; build y smoke del ejemplo 8/8 +- [x] Guía de autoría publicada (`docs/authoring/`); CHANGELOG y versión 0.6.0 + +Pendiente del owner: push de la rama, publicar 0.6.0 en npm. diff --git a/docs/phases/phase-18-story-demo/README.md b/docs/phases/phase-18-story-demo/README.md new file mode 100644 index 0000000..3434503 --- /dev/null +++ b/docs/phases/phase-18-story-demo/README.md @@ -0,0 +1,78 @@ +# Phase 18 — Story Demo + +**Objetivo**: una aventura corta, completa y con historia, jugable de principio a fin en la demo. +**Duración estimada**: 2 semanas de contenido, más el tiempo del arte +**Estado**: next (desbloqueada: Fase 17 completada el 2026-10-11; premisa, arte y ruta decididos el 2026-10-10) +**Owner**: Daniel Martínez Sebastián +**Version target**: demo 1.0 sobre los paquetes 0.6.x + +--- + +## Por qué + +La demo actual enseña mecánicas sueltas: mover, recoger, una puerta, tres escenas. No tiene principio, objetivo ni final. Una aventura de 10–15 minutos es la mejor prueba del motor y su mejor escaparate. + +## Resultado esperado + +- Se juega de principio a fin en 10–15 minutos: intro, 6–8 puzzles encadenados, final y créditos. +- 4–5 escenas, 2–3 NPCs con conversaciones, 8–10 ítems, al menos dos combinaciones. +- En español e inglés. +- Un test headless la resuelve entera (`createPlaythrough`), y el smoke recorre su camino principal en el navegador. +- Todo el contenido es dato: ningún callback propio del juego fuera de `call`. + +## Decisiones del owner (2026-10-10) + +1. **Premisa**: B, "No es un bug, es una feature". +2. **Arte**: ítems de dos packs CC0 ya descargados; los NPCs no llevan arte nuevo (el NPC atascado es una copia con glitch de David y el Programador es una voz sin sprite). Detalle en [assets.md](assets.md). De momento la demo solo se ejecuta en local, para pruebas. Antes de enseñarla fuera hay que revisar la licencia de cada asset, incluidos los fondos actuales. +3. **Ruta**: convive con la demo actual en una ruta propia (`/adventure`), para poder enseñarla en beta cerrada a colaboradores y revisores sin tocar `/`. + +## Propuestas de premisa + +Las tres reutilizan los fondos que ya existen (`personalRoom`, `town`, `mazmorra`, `volcanico`, `lava`) y el tono de los diálogos actuales. + +### A. "Partida guardada" + +David está a un jefe de terminar su juego cuando el cartucho del gameboy desaparece dentro de la pantalla. Entra tras él. El pueblo, la mazmorra y el volcán son los niveles del juego, y sus habitantes saben que son personajes. Para recuperar el cartucho hay que resolver lo que el juego dejó a medias. +*Arte nuevo*: 2 NPCs, unos 6 ítems. *A favor*: encaja con el gameboy y el trofeo actuales; objetivo claro desde el minuto uno. + +### B. "No es un bug, es una feature" *(elegida)* + +La demo del motor está rota y David lo sabe: paredes invisibles, una puerta sin llave, un NPC atascado repitiendo una frase. El Programador, agotado, le pide ayuda desde fuera de la pantalla. Cada puzzle es arreglar un fallo con las herramientas del propio mundo, y el final es conseguir que la demo "compile". +*Arte nuevo*: 1–2 NPCs, unos 6 ítems; el Programador puede ser solo una voz. *A favor*: continúa el humor que ya tienen los textos ("El programador fue muy vago", "Esto no es un bug, es una feature"), necesita el mínimo de arte y enseña el motor hablando de sí mismo. + +### C. "El trofeo de la abuela" + +El trofeo de la estantería no es de David: su abuela lo ganó en el concurso de tapas del pueblo en 1987 y alguien lo ha cambiado por una copia. Una investigación pequeña por el pueblo, con sospechosos, coartadas y un sótano que resulta ser una mazmorra. +*Arte nuevo*: 3 NPCs, unos 8 ítems, quizá un interior más. *A favor*: la más clásica como aventura gráfica; da más juego a los diálogos. *En contra*: la que más arte pide. + +## Plan (se detalla en tareas al desbloquearse) + +| # | Paso | Quién | +|---|---|---| +| 1 | Documento de diseño: sinopsis, personajes, grafo de dependencias de puzzles, lista de escenas, ítems, flags y arte necesario | opus, con el owner | +| 2 | Recorrido en papel validado contra el grafo: sin callejones sin salida ni ítems huérfanos | opus | +| 3 | Guion completo en `es` y `en` | sonnet, revisado por opus y el owner | +| 4 | Contenido como datos, con arte provisional (cajas y sprites actuales) | sonnet | +| 5 | Test headless del recorrido completo y de los órdenes alternativos | sonnet | +| 6 | Integración del arte y el audio definitivos | owner + sonnet | +| 7 | Geometría fina de escenas con el editor de debug (muros, hotspots sobre el fondo) | owner, o sonnet con capturas | +| 8 | Intro, final, créditos, menú de pausa y "nueva partida" | sonnet | +| 9 | Prueba con jugadores reales: dónde se atascan, qué no se entiende | owner | +| 10 | Pulido, smoke ampliado y gate | opus | + +Los pasos 1–5 no dependen del arte: el juego puede estar completo y probado con arte provisional antes de que exista el definitivo. + +## Qué puede hacer Opus 5.5 y qué no + +| Trabajo | ¿Ejecutable? | +|---|---| +| Diseño de puzzles, grafo de dependencias, guion y diálogos en `es`/`en` | Sí; el tono y la premisa los valida el owner | +| Contenido como datos, tests de recorrido, smoke | Sí, completo | +| Geometría de escenas sobre un fondo dado | Parcial: se puede escribir y revisar con capturas; el ajuste fino es más rápido a mano con el editor | +| Fondos, sprites, animaciones | No | +| Música y efectos | No | +| Saber si es divertido | No: hace falta gente jugando | + +## Fuera de alcance + +Multijugador (Fase 14), puertas como primitiva (Fase 7), cinemáticas con cámara, voces. diff --git a/docs/phases/phase-18-story-demo/assets.md b/docs/phases/phase-18-story-demo/assets.md new file mode 100644 index 0000000..fa3be03 --- /dev/null +++ b/docs/phases/phase-18-story-demo/assets.md @@ -0,0 +1,58 @@ +# Phase 18 — Arte: packs candidatos + +Investigación del 2026-10-10 para la premisa B ("No es un bug, es una feature"). Uso previsto: demo no comercial, de momento solo en local. + +**Estado (2026-10-10)**: el owner aprobó la recomendación. Los dos packs CC0 de ítems están descargados sin modificar en `apps/web-demo/assets-src/items/` (fuera de `public/`, no se sirven), con su tabla de origen y licencia en `apps/web-demo/assets-src/README.md`. Los NPCs no llevan arte nuevo. + +## Qué arte hace falta + +| Necesidad | Formato actual de referencia | +|---|---| +| 6–8 ítems de inventario | PNG 64×64 con transparencia (`trophy.png`) | +| 1–2 NPCs en escena | David mide 93×255 px, con paseo en 4 direcciones y clip de habla | +| Cursor y menú de verbos | HTML; iconos de 32 px bastan | +| Fondos | Ya existen 5; la premisa B no pide más | + +## Recomendación + +1. **Ítems: packs CC0.** Dominio público: se pueden usar, modificar y subir al repo sin condiciones. + - *496 pixel art icons for medieval/fantasy RPG*, de Henrique Lazarini (7Soul1). 496 iconos de 34×34. CC0. https://opengameart.org/node/39455 + - *Idylwild's Inventory*, de Idylwild. 50 iconos de 32×32 (llave, cuerda, cadena, libro, pergamino, cubo, saco…). CC0. https://opengameart.org/content/idylwilds-inventory + + Se escalan ×2 sin suavizado para igualar los 64×64 actuales. +2. **NPCs: no usar un pack; reutilizar a David.** Ningún pack gratuito encontrado se parece a David (alto, detallado, 93×255); un NPC de 32–48 px a su lado se vería de otro juego. La premisa B lo resuelve sola: + - El NPC atascado es **una copia con glitch de David**: sus mismos frames con un tinte y un parpadeo. Cero arte nuevo, y es un chiste coherente con la historia. + - **El Programador es una voz** fuera de pantalla: un bocadillo sin sprite. +3. **Cursores**: cualquiera de los packs de abajo, o iconos propios de 32 px. + +## Otros candidatos vistos + +| Pack | Qué trae | Licencia declarada | Nota | +|---|---|---|---| +| *Point and Click Adventure Game Sprite Template*, Danger Goose — https://danger-goose.itch.io/point-and-click-adventure-game-sprite-template | Plantilla de personaje con proporciones de aventura clásica: idle, paseo, correr, empujar, usar, sentarse. PNG y Aseprite | "100% free… personal and commercial projects. Credit is not necessary" (dicho por el autor en un comentario; no hay documento de licencia) | La mejor base si más adelante se dibujan NPCs propios | +| *Character Animation Asset Pack*, Mucho Pixels — https://muchopixels.itch.io/character-animation-asset-pack | 2 personajes, 3 atuendos, 15 animaciones, entre ellas hablar, usar y recoger | Uso comercial permitido; **prohíbe redistribuir los assets directamente** | Vista lateral, pensado para plataformas. No subir al repo público | +| *Lenore – Point and Click Character*, Danger Goose — https://danger-goose.itch.io/lenore-point-and-click-character | Un personaje de 36×46 con paseo en 4 direcciones | Sin licencia declarada | Descartado mientras no haya licencia | +| *Mouse Cursor Pack* (Megabyte Games), *154 Mouse Cursors* (KabGames), *Point and Click* (Kicked-in-Teeth) — https://itch.io/game-assets/free/tag-point-and-click | Cursores | Sin comprobar | Comprobar la licencia antes de usar | + +## Avisos de licencia que afectan a lo que ya hay + +- **El repositorio es público y cada PR se despliega en Vercel.** "Solo en local" no describe la situación real: lo que se sube al repo se distribuye. Por eso la recomendación para todo lo que se commitee es CC0. +- **`town.jpg` lleva la marca de agua "DanielThomasArt.com"** y no hay constancia de su licencia en el repo. `LICENSES.md` solo cubre el audio. Antes de enseñar la demo a colaboradores conviene documentar el origen y la licencia de los cinco fondos, del sprite de David y de los tres ítems, o sustituirlos. +- **Decisión del owner (2026-10-10)**: `town.jpg` se mantiene tal cual, con la marca de agua visible. No recortarla, taparla ni retocarla. La firma acredita al autor pero no es una licencia: revisar si la demo sale de la beta cerrada. +- Los packs sin documento de licencia (Danger Goose) son de bajo riesgo para pruebas, pero no equivalen a CC0. + +## Escenario aportado por el owner (2026-10-11) + +*Sci Fi Level*, de Jeremy Gooch — https://opengameart.org/content/sci-fi-level. CC-BY 3.0: exige acreditar "Jeremy Gooch (jeremygooch.blogspot.com)". Nivel lateral de ciencia ficción de 5121×841 en dos capas (fondo y primer plano), oscurecido a propósito para que destaquen los personajes. Descargado sin modificar en `apps/web-demo/assets-src/backgrounds/sci-fi-level/`. + +Uso previsto: escena candidata para la aventura (encaja con la premisa B como "el interior del motor") y escena de pruebas seleccionable en el modo debug. Es mucho más ancho que los fondos actuales: hay que trocearlo en varias pantallas o usarlo con cámara que siga al personaje. + +## Personaje aportado por el owner (2026-10-11) + +*8 Directional 2D Point and Click Male Character*, de DeMoNiCaTeD — https://opengameart.org/content/8-directional-2d-point-and-click-male-character. CC-BY-SA 4.0 (o GPL 3.0): atribución y misma licencia para las versiones modificadas. Una hoja de sprites con reposo y paseo en 8 direcciones a 64×64. Descargado sin modificar en `apps/web-demo/assets-src/characters/helix-male/`. + +Para usarlo como NPC hay que recortar la hoja en frames sueltos (el motor carga un PNG por frame) y no trae clip de habla. A 64 px de alto, junto a David (255 px) se verá de otra resolución: sirve para probar NPCs y como personaje lejano o "de otro juego", que en la premisa B puede ser un chiste a favor. + +## Siguiente paso + +En el documento de diseño de la Fase 18: elegir los iconos concretos de entre los descargados, copiarlos escalados ×2 a `apps/web-demo/public/assets/items/` y anotarlos en un `LICENSES.md` de arte junto al de audio. diff --git a/docs/phases/phase-6-walls-with-openings/README.md b/docs/phases/phase-6-walls-with-openings/README.md index 3cf08d9..d8bb0e9 100644 --- a/docs/phases/phase-6-walls-with-openings/README.md +++ b/docs/phases/phase-6-walls-with-openings/README.md @@ -1,6 +1,6 @@ # Phase 6: Walls with Openings (Doors/Windows) -**Status**: Planning | **Owner**: Feature development | **Version target**: v0.2.0 +**Status**: completed | **Owner**: Feature development | **Version target**: v0.2.0 --- @@ -168,7 +168,7 @@ app/lib/engine/types/gameRuntime.ts docs/architecture/07-walls-with-openings.md └─ CREATED: Design doc (✅ done) -docs/DEBUG_MODE_REVIEW.md +docs/_archive/DEBUG_MODE_REVIEW.md └─ CREATED: Status del debug mode (✅ done) docs/phases/phase-6-walls-with-openings/ @@ -246,7 +246,7 @@ docs/phases/phase-6-walls-with-openings/ - `docs/architecture/01-layers.md` — arquitectura general - `docs/architecture/03-rules-core-vs-render.md` — core vs renderer - `docs/architecture/07-walls-with-openings.md` — design doc detallado -- `docs/DEBUG_MODE_REVIEW.md` — estado del debug mode +- `docs/_archive/DEBUG_MODE_REVIEW.md` — estado del debug mode - `docs/workflow/commit-convention.md` — formato de commits - `docs/workflow/pre-commit-checklist.md` — checks antes de commit diff --git a/docs/phases/phase-8-scene-transitions/README.md b/docs/phases/phase-8-scene-transitions/README.md index f7bf7c1..2e764c9 100644 --- a/docs/phases/phase-8-scene-transitions/README.md +++ b/docs/phases/phase-8-scene-transitions/README.md @@ -1,6 +1,6 @@ # Phase 8 — Scene Transitions as First-Class Engine Primitives -**Status**: Planned | **Owner**: TBD | **Version target**: v0.3.0 +**Status**: completed | **Owner**: TBD | **Version target**: v0.3.0 --- diff --git a/e2e/smoke-minimal.mjs b/e2e/smoke-minimal.mjs new file mode 100644 index 0000000..47846ee --- /dev/null +++ b/e2e/smoke-minimal.mjs @@ -0,0 +1,69 @@ +// Smoke headless de /example-minimal: un juego que solo importa de los paquetes. +// Uso: node e2e/smoke-minimal.mjs [baseUrl] (requiere el servidor de la demo en marcha) +// SMOKE_PATH cambia la ruta de la página (por defecto /example-minimal); sirve para +// probar el mismo ejemplo servido desde un proyecto externo al monorepo. +import { chromium } from "playwright"; + +const BASE = process.argv[2] ?? "http://localhost:3000"; +const PAGE_PATH = process.env.SMOKE_PATH ?? "/example-minimal"; +const TROPHY = [789, 540]; // viewport 1280x720, escena minimal-a +const NOTICE = [770, 340]; // hotspot `notice` (cartel de la pared), mismo viewport +const checks = []; +const check = (name, ok, detail = "") => { + checks.push(Boolean(ok)); + console.log(`${ok ? "PASS" : "FAIL"} ${name}${detail ? ` — ${detail}` : ""}`); +}; + +const browser = await chromium.launch({ + headless: true, + args: ["--use-gl=swiftshader", "--enable-unsafe-swiftshader", "--ignore-gpu-blocklist"], +}); +const page = await browser.newPage({ viewport: { width: 1280, height: 720 } }); +const errors = []; +page.on("pageerror", (e) => errors.push(String(e).slice(0, 300))); +page.on("console", (m) => { if (m.type() === "error") errors.push(m.text().slice(0, 300)); }); +page.on("response", (r) => { if (r.status() >= 400) errors.push(`HTTP ${r.status()} ${r.url().slice(0, 120)}`); }); + +const status = async () => (await page.textContent('[data-testid="minimal-status"]')) ?? ""; +const waitForStatus = async (pattern, timeoutMs) => { + const start = Date.now(); + while (Date.now() - start < timeoutMs) { + if (pattern.test(await status())) return true; + await page.waitForTimeout(500); + } + return false; +}; + +try { + await page.goto(`${BASE}${PAGE_PATH}`, { waitUntil: "networkidle" }); + await page.waitForSelector("canvas", { timeout: 30000 }); + check("arranca en la escena inicial con el ítem sembrado", await waitForStatus(/escena: minimal-a \| inventario: 0 \| en escena: 1/, 20000), await status()); + await page.waitForTimeout(4000); + + check("el hotspot empieza sin ver", /cartel: sin ver/.test(await status()), await status()); + await page.mouse.click(...NOTICE); + check("mirar el hotspot (un solo verbo, sin menú) ejecuta su guion", await waitForStatus(/cartel: visto/, 8000), await status()); + check("el hotspot con un solo verbo no abre menú", (await page.getByRole("menu").count()) === 0); + await page.waitForTimeout(9000); // el bocadillo del hotspot se cierra solo + + await page.mouse.click(...TROPHY); + check("recoger el ítem con un click lo mete en el inventario", await waitForStatus(/inventario: 1 \| en escena: 0/, 15000), await status()); + await page.waitForTimeout(9000); // el bocadillo de recogida se cierra solo + + await page.keyboard.down("w"); + const changed = await waitForStatus(/escena: minimal-b/, 20000); + await page.keyboard.up("w"); + check("caminar hasta la zona de transición cambia de escena", changed, await status()); + check("el inventario se conserva al cambiar de escena", /inventario: 1/.test(await status()), await status()); + + check("sin errores de página ni de consola", errors.length === 0, errors.slice(0, 3).join(" | ")); +} catch (error) { + check("el smoke terminó sin excepción", false, String(error).slice(0, 300)); +} finally { + if (process.argv[3]) await page.screenshot({ path: process.argv[3] }).catch(() => {}); + await browser.close(); +} + +const failed = checks.filter((ok) => !ok).length; +console.log(`\n${checks.length - failed}/${checks.length} comprobaciones correctas`); +process.exit(failed === 0 ? 0 : 1); diff --git a/e2e/smoke.mjs b/e2e/smoke.mjs new file mode 100644 index 0000000..d5dbcc5 --- /dev/null +++ b/e2e/smoke.mjs @@ -0,0 +1,344 @@ +// Smoke headless de la demo: juega un recorrido corto y comprueba estado y audio. +// Uso: node e2e/smoke.mjs [baseUrl] (requiere el servidor de la demo en marcha) +// Sale con código 1 si alguna comprobación falla. +import { chromium } from "playwright"; + +const BASE = process.argv[2] ?? "http://localhost:3000"; +// Coordenadas para viewport 1280x720 en la escena personalRoom. +const POS = { trophy: [846, 575], doorstep: [570, 455], introTap: [640, 600], backpack: [82, 640], gameboyPad: [763, 566], emptyFloor: [420, 640], confirmReset: [779, 423], dungeonGate: [615, 330], computer: [270, 315], guide: [397, 470], keyBit: [601, 598] }; +// El bocadillo se cierra solo tras escribir el texto y un tiempo de lectura; +// mientras está visible no se puede recoger ni interactuar. +const DIALOG_MS = 10000; + +const checks = []; +const check = (name, ok, detail = "") => { + checks.push({ name, ok: Boolean(ok), detail }); + console.log(`${ok ? "PASS" : "FAIL"} ${name}${detail ? ` — ${detail}` : ""}`); +}; + +const browser = await chromium.launch({ + headless: true, + args: ["--use-gl=swiftshader", "--enable-unsafe-swiftshader", "--ignore-gpu-blocklist", "--autoplay-policy=no-user-gesture-required"], +}); +const context = await browser.newContext({ viewport: { width: 1280, height: 720 } }); +// Registra cada reproducción de audio (el oído lo pone el test). +await context.addInitScript(() => { + window.__plays = []; + const original = HTMLMediaElement.prototype.play; + HTMLMediaElement.prototype.play = function play() { + window.__plays.push(String(this.currentSrc || this.src).split("/").pop()); + return original.call(this).catch(() => {}); + }; +}); +const page = await context.newPage(); +const errors = []; +page.on("pageerror", (e) => errors.push(String(e).slice(0, 300))); +page.on("console", (m) => { if (m.type() === "error") errors.push(m.text().slice(0, 300)); }); +page.on("response", (r) => { if (r.status() >= 400) errors.push(`HTTP ${r.status()} ${r.url().slice(0, 120)}`); }); + +// La partida vive en una sola instantánea (`pointclick-save`); las puertas van en `extra.doors`. +const SAVE_KEY = "pointclick-save"; +const LEGACY_KEYS = ["inventory-slots", "current-scene-id", "placed-items-state", "door-states"]; +const state = () => page.evaluate(([saveKey, legacyKeys]) => { + const parse = (k) => { try { return JSON.parse(localStorage.getItem(k) ?? "null"); } catch { return null; } }; + const save = parse(saveKey); + return { + scene: save?.sceneId ?? null, + inventory: (save?.inventory ?? []).filter(Boolean).map((s) => s.id), + placed: (save?.placedItems ?? []).map((i) => `${i.itemId}@${i.sceneId}`), + doors: save?.extra?.doors ?? {}, + version: save?.version ?? null, + seeded: save?.seededSceneIds ?? [], + flags: save?.flags ?? {}, + legacyLeft: legacyKeys.filter((k) => localStorage.getItem(k) !== null), + plays: window.__plays.slice(), + }; +}, [SAVE_KEY, LEGACY_KEYS]); +const waitFor = async (predicate, timeoutMs) => { + const start = Date.now(); + while (Date.now() - start < timeoutMs) { + const s = await state(); + if (predicate(s)) return s; + await page.waitForTimeout(500); + } + return state(); +}; +const enterGame = async () => { + await page.goto(BASE, { waitUntil: "networkidle" }); + await page.waitForTimeout(1200); + await page.mouse.click(...POS.introTap); + await page.waitForTimeout(800); + await page.mouse.click(...POS.introTap); + await page.waitForTimeout(800); + await page.getByRole("button", { name: /continu/i }).first().click(); + return page + .waitForFunction(() => document.querySelector("canvas") && !document.querySelector('[aria-label="Cargando…"]'), null, { timeout: 40000 }) + .then(() => true, () => false); +}; +// Abre la mochila y arrastra el ítem cuyo slot contiene `label` hasta `target`. +const dragFromInventory = async (label, target) => { + await page.mouse.click(...POS.backpack); + await page.waitForTimeout(1200); + const box = await page.getByRole("button", { name: label }).first().boundingBox(); + if (!box) return false; + await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2); + await page.mouse.down(); + await page.mouse.move(target[0], target[1], { steps: 25 }); + await page.waitForTimeout(400); + await page.mouse.up(); + return true; +}; +// Arrastra el ítem del slot `from` y lo suelta sobre el slot `to` (combinar). Devuelve false si falta alguno. +const dragSlotOntoSlot = async (from, to) => { + await page.mouse.click(...POS.backpack); + await page.waitForTimeout(1200); + const a = await page.getByRole("button", { name: from }).first().boundingBox(); + const b = await page.getByRole("button", { name: to }).first().boundingBox(); + if (!a || !b) return false; + await page.mouse.move(a.x + a.width / 2, a.y + a.height / 2); + await page.mouse.down(); + await page.mouse.move(b.x + b.width / 2, b.y + b.height / 2, { steps: 20 }); + await page.waitForTimeout(400); + await page.mouse.up(); + return true; +}; +// Partida en el formato de la instantánea nueva (versión 1), inyectada antes de cargar la página. +const injectSave = (overrides) => page.evaluate(([saveKey, o]) => { + const slots = Array.from({ length: 9 }, () => null); + (o.items ?? []).forEach((it, i) => { slots[i] = { id: it.id, name: it.name, spriteUrl: it.spriteUrl, quantity: 1 }; }); + localStorage.setItem(saveKey, JSON.stringify({ + version: 1, sceneId: o.sceneId, playerPosition: [0, 0, 0], inventory: slots, placedItems: [], + seededSceneIds: ["personalRoom"], flags: {}, visitedSceneIds: ["personalRoom"], extra: { doors: {} }, + })); +}, [SAVE_KEY, overrides]); +const GAMEBOY = { id: "gameboy", name: "Gameboy", spriteUrl: "/assets/gameboy/gameboy.png" }; +const TROPHY = { id: "trophy", name: "Trophy", spriteUrl: "/assets/trophy/trophy.png" }; +const optionTexts = () => page.locator('[role="option"]').allTextContents(); +const waitForOptions = (timeoutMs) => page.waitForSelector('[role="listbox"]', { timeout: timeoutMs }).then(() => true, () => false); +const count = (plays, name) => plays.filter((p) => p.includes(name)).length; +const music = (plays) => plays.filter((p) => !p.startsWith("speak") && !p.startsWith("click")).join(","); +// Camina hasta el umbral de la puerta central y empuja hacia el norte: la +// transición es una zona de colisión, no un click sobre la puerta. +const walkThroughCenterDoor = async () => { + await page.mouse.click(...POS.doorstep); + await page.waitForTimeout(5000); + await page.keyboard.down("w"); + await page.waitForTimeout(2500); + await page.keyboard.up("w"); +}; + +try { + // 1. Primera visita. + check("la partida nueva pasa la pantalla de carga", await enterGame()); + await page.waitForTimeout(3000); + let s = await state(); + check("arranca en personalRoom", s.scene === "personalRoom", `scene=${s.scene}`); + check("inventario inicial: gameboy y llave", s.inventory.join() === "gameboy,gold-key", s.inventory.join()); + check("el trofeo está sembrado en la habitación", s.placed.includes("trophy@personalRoom"), s.placed.join()); + check("suena la música inicial una sola vez", count(s.plays, "personal-room-loop") === 1, `audio=${music(s.plays)}`); + + // 2. No se puede salir sin el trofeo. + await walkThroughCenterDoor(); + await page.waitForTimeout(2000); + s = await state(); + check("la puerta no deja salir sin el trofeo", s.scene === "personalRoom", `scene=${s.scene}`); + check("no suena la transición al quedar bloqueado", count(s.plays, "transition-default") === 0); + await page.waitForTimeout(DIALOG_MS); + + // 3. Recoger el trofeo. + await page.mouse.click(...POS.trophy); + s = await waitFor((x) => x.inventory.includes("trophy"), 15000); + check("recoger el trofeo lo mete en el inventario", s.inventory.includes("trophy"), s.inventory.join()); + check("el trofeo deja de estar colocado", !s.placed.some((p) => p.startsWith("trophy@")), s.placed.join()); + check("suena el sonido de recoger", count(s.plays, "pickup-default") === 1, `audio=${music(s.plays)}`); + check("no suena el sonido de soltar al recoger", count(s.plays, "drop-default") === 0); + await page.waitForTimeout(DIALOG_MS); + + // 4. Colocar, recoger y devolver ítems arrastrando desde la mochila. + check("el gameboy se puede arrastrar desde la mochila", await dragFromInventory(/Gameboy/i, POS.gameboyPad)); + s = await waitFor((x) => x.placed.includes("gameboy@personalRoom"), 8000); + check("soltar el gameboy en su sitio lo coloca", s.placed.includes("gameboy@personalRoom"), s.placed.join()); + check("el gameboy sale del inventario", !s.inventory.includes("gameboy"), s.inventory.join()); + check("colocar suena una vez", count(s.plays, "drop-default") === 1, `audio=${music(s.plays)}`); + await page.waitForTimeout(DIALOG_MS); + + await page.mouse.click(...POS.gameboyPad); + s = await waitFor((x) => x.inventory.includes("gameboy"), 15000); + check("recoger el gameboy colocado lo devuelve al inventario", s.inventory.includes("gameboy"), s.inventory.join()); + check("el gameboy tiene su propio sonido de recogida", count(s.plays, "pickup-gameboy") === 1, `audio=${music(s.plays)}`); + await page.waitForTimeout(DIALOG_MS); + + const dropsBefore = count(s.plays, "drop-default"); + await dragFromInventory(/Llave/i, POS.emptyFloor); + await page.waitForTimeout(3000); + s = await state(); + check("soltar la llave fuera de su diana la devuelve", s.inventory.includes("gold-key"), s.inventory.join()); + check("la llave no queda colocada en la escena", !s.placed.some((p) => p.startsWith("gold-key@")), s.placed.join()); + check("devolver un ítem no suena", count(s.plays, "drop-default") === dropsBefore, `audio=${music(s.plays)}`); + await page.waitForTimeout(DIALOG_MS); + + // 5. Transición a la mazmorra. + await walkThroughCenterDoor(); + s = await waitFor((x) => x.scene === "dungeon", 15000); + check("la puerta central lleva a la mazmorra", s.scene === "dungeon", `scene=${s.scene}`); + await page.waitForTimeout(2500); + s = await state(); + check("suena la transición", count(s.plays, "transition-default") >= 1, `audio=${music(s.plays)}`); + check("cambia la música a la de la mazmorra", count(s.plays, "dungeon-loop") >= 1); + + // 6. Abrir la verja de la mazmorra con la llave. + await page.waitForTimeout(7000); // el personaje entra caminando + const dropsBeforeKey = count(s.plays, "drop-default"); + await dragFromInventory(/Llave/i, POS.dungeonGate); + s = await waitFor((x) => x.doors["dungeon-gate-door"] === true, 8000); + check("la llave abre la verja", s.doors["dungeon-gate-door"] === true, JSON.stringify(s.doors)); + check("la llave se consume", !s.inventory.includes("gold-key"), s.inventory.join()); + check("consumir la llave no suena como soltar", count(s.plays, "drop-default") === dropsBeforeKey); + await page.waitForTimeout(DIALOG_MS); + + // 7. Persistencia tras recargar. + check("tras recargar pasa la pantalla de carga", await enterGame()); + await page.waitForTimeout(3000); + s = await state(); + check("la escena guardada se restaura", s.scene === "dungeon", `scene=${s.scene}`); + check("el inventario guardado se restaura", s.inventory.slice().sort().join() === "gameboy,trophy", s.inventory.join()); + check("no reaparecen ítems ya recogidos", s.placed.length === 0, s.placed.join()); + check("la verja sigue abierta tras recargar", s.doors["dungeon-gate-door"] === true, JSON.stringify(s.doors)); + check("tras recargar suena la música de la mazmorra", count(s.plays, "dungeon-loop") === 1, `audio=${music(s.plays)}`); + + // 8. Reiniciar partida: borra el progreso y conserva lo demás. + const keptBefore = await page.evaluate(() => { + localStorage.setItem("smoke-foreign-key", "keep"); + return JSON.stringify([localStorage.getItem("i18n-locale"), localStorage.getItem("audio-settings")]); + }); + await page.mouse.click(...POS.backpack); + await page.waitForTimeout(1200); + await page.getByRole("button", { name: /Reiniciar/i }).first().click(); + await page.waitForTimeout(800); + await Promise.all([ + page.waitForEvent("load", { timeout: 15000 }).catch(() => {}), + page.mouse.click(...POS.confirmReset), + ]); + await page.waitForTimeout(1500); + const afterReset = await page.evaluate(([saveKey, legacyKeys]) => ({ + game: [saveKey, ...legacyKeys].filter((k) => localStorage.getItem(k) !== null), + foreign: localStorage.getItem("smoke-foreign-key"), + kept: JSON.stringify([localStorage.getItem("i18n-locale"), localStorage.getItem("audio-settings")]), + }), [SAVE_KEY, LEGACY_KEYS]); + check("reiniciar borra las claves de la partida", afterReset.game.length === 0, afterReset.game.join()); + check("reiniciar conserva datos ajenos al juego", afterReset.foreign === "keep"); + check("reiniciar no toca idioma ni ajustes de audio", afterReset.kept === keptBefore, afterReset.kept); + check("tras reiniciar se puede volver a entrar", await enterGame()); + await page.waitForTimeout(3000); + s = await state(); + check("la partida reiniciada arranca en la habitación", s.scene === "personalRoom", `scene=${s.scene}`); + check("la partida reiniciada tiene el inventario inicial", s.inventory.join() === "gameboy,gold-key", s.inventory.join()); + check("la partida reiniciada vuelve a sembrar el trofeo", s.placed.join() === "trophy@personalRoom", s.placed.join()); + + // 9. Una partida guardada con el formato de 0.5.0 (cuatro claves sueltas) se migra al cargar. + await page.evaluate(([saveKey]) => { + localStorage.removeItem(saveKey); + const slots = Array.from({ length: 9 }, () => null); + slots[0] = { id: "gold-key", name: "Llave dorada", spriteUrl: "/assets/key/gold-key.png", quantity: 1 }; + slots[1] = { id: "trophy", name: "Trophy", spriteUrl: "/assets/trophy/trophy.png", quantity: 1 }; + localStorage.setItem("inventory-slots", JSON.stringify(slots)); + localStorage.setItem("current-scene-id", "dungeon"); + localStorage.setItem("placed-items-state", JSON.stringify({ + state: { + items: [{ id: "gameboy-legacy", itemId: "gameboy", interactionId: "legacy-gameboy", name: "Gameboy", spriteUrl: "/assets/gameboy/gameboy.png", worldPosition: [3, -2, 20], canPickup: true, sceneId: "dungeon" }], + initialItemsCreated: true, + }, + version: 0, + })); + localStorage.setItem("door-states", JSON.stringify({ state: { doorOpenStates: { "dungeon-gate-door": true } }, version: 0 })); + }, [SAVE_KEY]); + check("tras inyectar una partida de 0.5.0 se puede cargar", await enterGame()); + await page.waitForTimeout(3000); + s = await state(); + check("la partida de 0.5.0 conserva la escena", s.scene === "dungeon", `scene=${s.scene}`); + check("la partida de 0.5.0 conserva el inventario", s.inventory.slice().sort().join() === "gold-key,trophy", s.inventory.join()); + check("la partida de 0.5.0 conserva el ítem colocado", s.placed.join() === "gameboy@dungeon", s.placed.join()); + check("la partida de 0.5.0 conserva las puertas", s.doors["dungeon-gate-door"] === true, JSON.stringify(s.doors)); + check("la migración traduce el flag antiguo a escena sembrada", s.seeded.join() === "personalRoom", s.seeded.join()); + check("existe la instantánea nueva (versión 1) y no quedan claves antiguas", s.version === 1 && s.legacyLeft.length === 0, `version=${s.version} antiguas=${s.legacyLeft.join()}`); + check("la partida migrada no resiembra el trofeo", !s.placed.some((p) => p.startsWith("trophy@")), s.placed.join()); + + // 10. Hotspot de personalRoom: menú de verbos, mirar y soltar un ítem encima (useItem). + await injectSave({ sceneId: "personalRoom", items: [GAMEBOY] }); + check("tras inyectar una partida en personalRoom se puede cargar", await enterGame()); + await page.waitForTimeout(3000); + s = await state(); + check("la partida inyectada arranca en personalRoom sin flags", s.scene === "personalRoom" && Object.keys(s.flags).length === 0, `scene=${s.scene} flags=${JSON.stringify(s.flags)}`); + await page.waitForTimeout(DIALOG_MS); // bienvenida + await page.mouse.click(...POS.computer); + await page.waitForTimeout(800); + const verbs = await page.getByRole("menuitem").allTextContents(); + check("clic en un hotspot con dos verbos abre el menú de verbos (traducido)", verbs.join() === "Usar,Mirar", verbs.join()); + await page.getByRole("menuitem", { name: /Mirar/ }).click(); + s = await waitFor((x) => x.flags["computer.seen"] === true, 8000); + check("mirar el hotspot ejecuta su guion (flag en la partida guardada)", s.flags["computer.seen"] === true, JSON.stringify(s.flags)); + await page.waitForTimeout(DIALOG_MS); + await dragFromInventory(/Gameboy/i, POS.computer); + s = await waitFor((x) => x.flags["computer.gameboyTried"] === true, 8000); + check("soltar el gameboy sobre el hotspot ejecuta su regla useItem", s.flags["computer.gameboyTried"] === true, JSON.stringify(s.flags)); + check("la regla useItem no quita el gameboy ni lo deja colocado", s.inventory.join() === "gameboy" && s.placed.length === 0, `inv=${s.inventory.join()} placed=${s.placed.join()}`); + await page.waitForTimeout(DIALOG_MS); + + // 11. NPC de town: conversación con opciones (when / once), efecto con flag e ítem, y combinar ítems. + await injectSave({ sceneId: "town", items: [GAMEBOY] }); + check("tras inyectar una partida en town se puede cargar", await enterGame()); + await page.waitForTimeout(3000); + s = await state(); + check("la partida inyectada arranca en town y siembra el paletón", s.scene === "town" && s.placed.includes("key-bit@town"), `scene=${s.scene} placed=${s.placed.join()}`); + await page.mouse.click(...POS.guide); + check("clic en el NPC abre las opciones de diálogo", await waitForOptions(15000)); + let options = await optionTexts(); + check("sin trofeo la opción condicionada al trofeo no aparece", options.length === 3 && !options.some((o) => /trofeo/i.test(o)), options.join(" | ")); + await page.getByRole("option", { name: /Hasta luego/ }).click(); + await page.waitForTimeout(DIALOG_MS); // la despedida se cierra sola + check("elegir la despedida cierra las opciones", (await page.locator('[role="listbox"]').count()) === 0); + + await injectSave({ sceneId: "town", items: [GAMEBOY, TROPHY] }); + await enterGame(); + await page.waitForTimeout(3000); + await page.mouse.click(...POS.guide); + await waitForOptions(15000); + options = await optionTexts(); + check("con el trofeo aparece la opción condicionada (4 opciones)", options.length === 4 && options.some((o) => /trofeo/i.test(o)), options.join(" | ")); + await page.getByRole("option", { name: /ayudarme/ }).click(); + s = await waitFor((x) => x.inventory.includes("key-handle"), 8000); + check("la opción entrega el ítem (mango roto en el inventario)", s.inventory.includes("key-handle"), s.inventory.join()); + check("la opción pone su flag en la partida guardada", s.flags["guide.helped"] === true, JSON.stringify(s.flags)); + check("la opción once deja constancia en la partida (dlg.guide-talk.root.2)", s.flags["dlg.guide-talk.root.2"] === true, JSON.stringify(s.flags)); + await waitForOptions(20000); // el guía responde y vuelve a las opciones + options = await optionTexts(); + check("la opción once ya no se vuelve a ofrecer", options.length === 3 && !options.some((o) => /ayudarme/.test(o)), options.join(" | ")); + await page.getByRole("option", { name: /Hasta luego/ }).click(); + await page.waitForTimeout(DIALOG_MS); + await page.mouse.click(...POS.keyBit); + s = await waitFor((x) => x.inventory.includes("key-bit"), 15000); + check("recoger el paletón del suelo lo mete en el inventario", s.inventory.includes("key-bit"), s.inventory.join()); + await page.waitForTimeout(DIALOG_MS); + + check("se puede arrastrar un ítem sobre otro slot", await dragSlotOntoSlot(/Gameboy/i, /Trophy/i)); + await page.waitForTimeout(2500); + s = await state(); + check("combinar ítems sin receta no pierde ninguno", s.inventory.slice().sort().join() === "gameboy,key-bit,key-handle,trophy", s.inventory.join()); + await page.waitForTimeout(DIALOG_MS); + await dragSlotOntoSlot(/Mango/i, /Palet/i); + s = await waitFor((x) => x.inventory.includes("bronze-key"), 8000); + check("soltar el mango sobre el paletón produce la llave de bronce", s.inventory.includes("bronze-key"), s.inventory.join()); + check("la combinación consume los dos ingredientes y no toca los demás", s.inventory.slice().sort().join() === "bronze-key,gameboy,trophy", s.inventory.join()); + await page.waitForTimeout(DIALOG_MS); + + check("sin errores de página ni de consola", errors.length === 0, errors.slice(0, 3).join(" | ")); +} catch (error) { + check("el smoke terminó sin excepción", false, String(error).slice(0, 300)); +} finally { + if (process.argv[3]) await page.screenshot({ path: process.argv[3] }).catch(() => {}); + await browser.close(); +} + +const failed = checks.filter((c) => !c.ok); +console.log(`\n${checks.length - failed.length}/${checks.length} comprobaciones correctas`); +process.exit(failed.length === 0 ? 0 : 1); diff --git a/package-lock.json b/package-lock.json index 0775e9c..c10cda1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5603,7 +5603,6 @@ "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", - "dev": true, "hasInstallScript": true, "license": "MIT", "optional": true, @@ -7176,7 +7175,7 @@ }, "packages/engine-core": { "name": "@pointclick-engine/engine-core", - "version": "0.4.0", + "version": "0.6.0", "license": "MIT", "dependencies": { "zustand": "^5.0.13" @@ -7192,10 +7191,10 @@ }, "packages/engine-renderer-r3f": { "name": "@pointclick-engine/engine-renderer-r3f", - "version": "0.4.0", + "version": "0.6.0", "license": "MIT", "dependencies": { - "@pointclick-engine/engine-core": "^0.4.0" + "@pointclick-engine/engine-core": "^0.6.0" }, "devDependencies": { "@react-three/drei": "^10.7.7", @@ -7218,7 +7217,7 @@ "@react-three/rapier": "^1.0.0 || ^2.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", - "three": "^0.150.0", + "three": ">=0.150.0", "zustand": "^4.0.0 || ^5.0.0" }, "peerDependenciesMeta": { diff --git a/package.json b/package.json index 3207fba..9c73d15 100644 --- a/package.json +++ b/package.json @@ -8,9 +8,15 @@ "scripts": { "dev": "npm run dev -w apps/web-demo", "dev:debug": "npm run dev:debug -w apps/web-demo", + "predev": "npm run build:packages", + "predev:debug": "npm run build:packages", + "build:packages": "npm run build -w packages/engine-core && npm run build -w packages/engine-renderer-r3f", "build": "npm run build --workspaces --if-present", + "prepare": "npm run build:packages", "test": "npm run test --workspaces --if-present", - "lint": "npm run lint --workspaces --if-present" + "typecheck": "tsc --noEmit -p packages/engine-core && tsc --noEmit -p packages/engine-renderer-r3f && tsc --noEmit -p apps/web-demo", + "lint": "npm run lint --workspaces --if-present", + "smoke": "node e2e/smoke.mjs && node e2e/smoke-minimal.mjs" }, "devDependencies": { "@playwright/test": "^1.60.0", diff --git a/packages/engine-core/CHANGELOG.md b/packages/engine-core/CHANGELOG.md index da60be0..2b8f9ac 100644 --- a/packages/engine-core/CHANGELOG.md +++ b/packages/engine-core/CHANGELOG.md @@ -7,6 +7,99 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.6.0] — Unreleased + +Phase 17: narrative primitives (ADR-0010, [authoring guide](../../docs/authoring/README.md)). +Additive over 0.5.0. + +### Added + +- World state (`useWorldStateStore`, flags, visited scenes), conditions + (`Condition`, `evaluateCondition`, `cond`) and actions (`Action`, `Script`, + `Branch`, `pickBranch`, `act`, `branch`, `otherwise`), with `createSequencer`, + `GameRuntime.runScript` / `registerHandler` / `getDialogues`, commands + `state:*` and `script:*`, and events `state:flagChanged`, `script:*`, + `input:lockChanged`, `custom`. +- Hotspots with verbs (`Verb`, `GameSceneHotspot`, `hotspot:interact`), NPCs + (`GameSceneNpc`, `npcToHotspot`; `toRuntimeScene` projects them), dialogue + trees (`DialogueDefinition`, `dialogue`, `dialogue:*`) and item combination + (`combine`, `inventory:combine`), with their events. +- Declarative scene rules: `initialItems` (with `when`), `onEnter`, and + `when` / `blocked` on transitions (`resolveInitialItems`, + `resolveEnterScript`, `evaluateTransitionGate`). +- `validateContent`, run by `createGameRuntime` per `validate` (dev only by default). +- Single versioned save (`GameSnapshot`, `saveGame`, `loadGame`, + `migrateLegacySave` for the 0.5.0 keys), commands `game:save|load|reset`, + config `storage` / `saveKey`. +- `ClockPort`, `systemClock`, `HeadlessClock`; config `clock`, `instantWalk`; + subpath `engine-core/testing` with `createPlaythrough`. +- Executors for `inventory:pickup` / `inventory:drop`; events + `inventory:pickupFailed`, `inventory:full`, `item:removed`. + +### Changed + +- `item:dropped.outcome` declares every value that can travel (`rule-miss`, + `unknown-item`, `on-player`, and the `@deprecated` `pickup-blocked` and + `item-interact`). +- `dialog:trigger`, `dialog:triggered` and `DialogUIAdapter.show` accept `speaker`. + +## [0.5.0] — Unreleased + +Phase 16: the game runtime moves into this package. `createGameRuntime` and +the content registries no longer live in the demo app. + +### Added — Agnostic runtime (`src/game/runtime/`) + +- `createGameRuntime`, `getGameRuntime`, `getGameState`, `getGameActions`, + `registerScene`, `registerItem`, `registerRule`, `toRuntimeScene`, + `createInventoryRuleContext`, plus the config types (`GameSceneConfig`, + `GameItemConfig`, `GameRuntimeConfig`, `GameRuntime`, `GameState`, + `GameActions`, `InventoryUIAdapter`, `DialogUIAdapter`, ...). +- `GameSceneConfig` keeps `transitions` and `music` through registration + and `scene:set`. +- `scene:set` accepts `spawnPosition?`. +- `player:stop` executor: aborts route walks (emits `player:walkAborted`); + it does not stop manual keyboard/joystick movement. + +### Added — Stores and persistence + +- `useDialogStore`, `useInventoryUiStore` (used by `dialog:*` and + `inventory:toggle` when no host adapter is passed), `useInventoryStateStore` + and `usePlacedItemsStateStore` (reactive slots and placed items). +- Port-based persistence in `gameStatePersistence.ts`: `KeyValueStoragePort`, + `loadInventorySlotsState` / `saveInventorySlotsState`, + `loadPlacedItemsState` / `savePlacedItemsState`. +- Declarative audio: item `pickupSoundUrl` / `dropSoundUrl` and scene + `music` are resolved by `audioRules` from `item:pickedUp` / `item:dropped`. +- Test `coreAgnosticism.test.ts`; `process.env` access is guarded. + +### Changed + +- `transition:activate` respects the transition's `spawnPosition`. +- Default dialog-key fallbacks in the core inventory rules use `??` + instead of `||`: an explicit empty key is now respected. +- `GameActions.setScene` is `(sceneId: string) => void`. +- Audio rules play the drop sound only for `outcome: "place"`. + +### Breaking + +- Picking up an item travels on the bus as `item:pickedUp`; it used to + arrive as `item:dropped` with `outcome: "pickup-success"`. Listeners that + detected pick-ups on `item:dropped` must listen to `item:pickedUp`. The + legacy `onRuntimeEvent` callback is unchanged. + +### Fixed + +- Test files are no longer shipped in the published package. + +### Known limitations + +- `inventory:pickup` and `inventory:drop` have no executor (they only warn). +- Scene/item/rule registries are module-global. +- Other legacy outcomes (`rule-miss`, `on-player`, `pickup-blocked`, + `item-interact`, `unknown-item`) still travel as `item:dropped` with an + `outcome` outside the declared type. + ## [0.4.0] — 2026-05-31 This release folds in everything between v0.1.x and v0.4.0 (phases 6, 8, 9, diff --git a/packages/engine-core/README.md b/packages/engine-core/README.md index 4e44b3b..345fe19 100644 --- a/packages/engine-core/README.md +++ b/packages/engine-core/README.md @@ -1,6 +1,6 @@ # @pointclick-engine/engine-core -Framework-agnostic core for the Point & Click Game Engine. State, rules, pathfinding, i18n, ports — zero React, zero Three.js, zero browser globals. +Framework-agnostic core for the Point & Click Game Engine. Runtime, state, rules, pathfinding, i18n, ports — zero React, zero Three.js, zero browser globals. ## Install @@ -8,30 +8,52 @@ Framework-agnostic core for the Point & Click Game Engine. State, rules, pathfin npm install @pointclick-engine/engine-core ``` -This package alone is **not** a runnable game. Pair it with a renderer: +This package alone is **not** a visible game: it holds the runtime (`createGameRuntime`) but draws nothing. Pair it with a renderer: -- [@pointclick-engine/engine-renderer-r3f](https://www.npmjs.com/package/@pointclick-engine/engine-renderer-r3f) — React Three Fiber +- [@pointclick-engine/engine-renderer-r3f](https://www.npmjs.com/package/@pointclick-engine/engine-renderer-r3f) — React Three Fiber (`GameViewport`) - Or write your own (see [renderer guide](https://github.com/DanielMartinezSebastian/pointclick-engine/blob/main/docs/architecture/06-renderer-implementation-guide.md)) ## Quick example -```ts -import { CommandHandler, EventBus } from "@pointclick-engine/engine-core"; -import type { GameCommand, GameEvent } from "@pointclick-engine/engine-core"; +Runs without React or a browser: register content, send commands, listen to events. -const bus = new EventBus(); -const commands = new CommandHandler(); +```ts +import { + createGameRuntime, + type GameItemConfig, + type GameSceneConfig, +} from "@pointclick-engine/engine-core"; -commands.register("scene:set", (cmd) => { - bus.emit("scene:changed", { type: "scene:changed", sceneId: cmd.sceneId }); -}); +const town: GameSceneConfig = { + id: "town", + label: "Town", + background: "/assets/background/town.jpg", + playerSpawn: [0, 0, 10], + ground: { minX: -15, maxX: 15, minZ: -10, maxZ: 30, y: -3 }, + walls: [], + interactions: [], +}; + +const trophy: GameItemConfig = { + id: "trophy", + name: "Trophy", + spriteUrl: "/assets/trophy/trophy.png", + interactionRules: {}, + defaultRule: { outcome: "return" }, +}; + +const runtime = createGameRuntime({ scenes: [town], items: [trophy] }); + +const unsub = runtime.on("scene:changed", (ev) => console.log(ev.sceneId)); +runtime.executeCommand({ type: "scene:set", sceneId: "town" }); -const unsub = bus.on("scene:changed", (ev) => console.log(ev)); -commands.execute({ type: "scene:set", sceneId: "town" }); // later unsub(); +runtime.dispose(); ``` +`scene:set` also accepts `spawnPosition?`. `player:stop` aborts route walks (not manual keyboard/joystick movement). `inventory:pickup` and `inventory:drop` have no executor yet. + ### i18n ```ts @@ -41,11 +63,11 @@ import { getRandomPhrase, } from "@pointclick-engine/engine-core"; -registerDictionary("en", { "greeting.hello": ["Hello!", "Hey there!"] }); -registerDictionary("es", { "greeting.hello": ["¡Hola!", "¡Buenas!"] }); +registerDictionary("en", { "greeting.hello": { phrases: ["Hello!", "Hey there!"] } }); +registerDictionary("es", { "greeting.hello": { phrases: ["¡Hola!", "¡Buenas!"] } }); -translate("greeting.hello", "es"); // "¡Hola!" or "¡Buenas!" -getRandomPhrase("greeting.hello", "en"); // random pick +translate("greeting.hello", { locale: "es" }); // first phrase of the entry +getRandomPhrase("greeting.hello", { locale: "en" }); // random pick ``` ## Subpath exports @@ -53,35 +75,43 @@ getRandomPhrase("greeting.hello", "en"); // random pick Import only what you need: ```ts -import type { GameCommand } from "@pointclick-engine/engine-core/commands"; -import type { GameEvent } from "@pointclick-engine/engine-core/events"; -import type { IGameLoopPort } from "@pointclick-engine/engine-core/ports"; -import type { GameVec3 } from "@pointclick-engine/engine-core/types"; -import { useSceneStore } from "@pointclick-engine/engine-core/state"; +import type { GameCommand } from "@pointclick-engine/engine-core/commands"; +import type { GameEvent } from "@pointclick-engine/engine-core/events"; +import type { GameLoopPort } from "@pointclick-engine/engine-core/ports"; +import type { GameVec3 } from "@pointclick-engine/engine-core/types"; +import { useSceneStore } from "@pointclick-engine/engine-core/state"; +import { createPlaythrough } from "@pointclick-engine/engine-core/testing"; // headless playthroughs (0.6.0, unreleased) ``` ## What's inside | Module | Key exports | |---------------|-------------| -| `(root)` | Re-exports all modules below | +| `(root)` | Re-exports all modules below, plus the runtime and `EventBus` | | `/commands` | `CommandHandler`, `GameCommand` union | -| `/events` | `EventBus`, `GameEvent` union | -| `/ports` | `IGameLoopPort`, `IInputPort`, `IViewportPort`, `IAudioPort`, `I18nPort` | +| `/events` | `GameEvent` union, `GameEventHandler`, legacy adapters | +| `/ports` | `GameLoopPort`, `InputPort`, `ViewportPort`, `AudioPort`, `I18nPort` and headless adapters | | `/types` | `GameVec3`, `GameScene`, `GameSceneWall`, `GameSceneInteraction`, `GameSceneTransition`, `PlacedSceneItem`, `ItemDefinition`, `SoundDefinition`, `SceneMusicConfig`, `AudioSettings`, `Locale`, `DialogEntry`, `I18nConfig`, `I18nState` | -| `/state` | `useSceneStore`, `createInventorySlotsStore`, `createPlacedItemsStore`, `createAudioSettingsStore`, `createI18nStore` | -| `(root only)` | `findPath`, `inventoryRules`, `transitionRules`, `audioRules`, `registerDictionary`, `registerDictionaries`, `translate`, `getRandomPhrase`, `matchLocale`, `registerI18nExecutors` | +| `/state` | `useSceneStore`, `useDialogStore`, `useInventoryUiStore`, `useInventoryStateStore`, `usePlacedItemsStateStore`, `createAudioSettingsStore`, `createI18nStore`, persistence helpers (`loadInventorySlotsState`, `savePlacedItemsState`, ...) | +| `/testing` | `createPlaythrough`: runs an adventure without a renderer (0.6.0, unreleased) | +| `(root only)` | `createGameRuntime`, `getGameRuntime`, `registerScene`, `registerItem`, `registerRule`, `getGameState`, `getGameActions`, `toRuntimeScene`, `createInventoryRuleContext`, `EventBus`, `findPath`, `sceneTransitionOnCollision`, `resolveAudioEvents`, `registerDictionary`, `translate`, `getRandomPhrase`, `matchLocale`, `registerI18nExecutors` | + +The runtime registries (scenes, items, rules) are module-global: one game per page. + +### Narrative (0.6.0, unreleased) + +Scenes can declare `hotspots`, `npcs`, `initialItems` and `onEnter`; transitions take `when` / `blocked`; items take `combine`; conversations are `dialogues`. Conditions (`cond`), actions (`act`), the sequencer, the single save (`game:save` / `game:load`) and `validateContent` are exported from the root. See the [authoring guide](https://github.com/DanielMartinezSebastian/pointclick-engine/blob/main/docs/authoring/README.md). ### Ports -Each port interface has a **headless implementation** included for testing without mocks: +Each port interface has a **headless implementation** included for testing without mocks (`HeadlessGameLoop`, `HeadlessInput`, `HeadlessAudioAdapter`, `HeadlessI18nAdapter`). `ViewportPort` has none. | Interface | Purpose | |-----------|---------| -| `IGameLoopPort` | Frame-tick integration (renderer drives) | -| `IInputPort` | Keyboard / pointer input | -| `IViewportPort` | Camera and viewport projection | -| `IAudioPort` | Sound playback and music | +| `GameLoopPort` | Frame-tick integration (renderer drives) | +| `InputPort` | Keyboard / pointer input | +| `ViewportPort` | Camera and viewport projection | +| `AudioPort` | Sound playback and music | | `I18nPort` | Locale detection and persistence | ## Design principles @@ -98,4 +128,4 @@ MIT © Daniel Martínez Sebastián ## Status -`v0.4.0` — active development. Core API is stabilising; i18n system added in v0.4. +`v0.5.0` — active development. The runtime now lives in this package; see [CHANGELOG](./CHANGELOG.md) for the `item:pickedUp` breaking note. diff --git a/packages/engine-core/dist/events/EventBus.d.ts b/packages/engine-core/dist/events/EventBus.d.ts deleted file mode 100644 index e5ef057..0000000 --- a/packages/engine-core/dist/events/EventBus.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -type EventHandler = (data: T) => void; -export declare class EventBus { - private listeners; - on(event: string, handler: EventHandler): () => void; - emit(event: string, data: T): void; - clear(): void; -} -export {}; -//# sourceMappingURL=EventBus.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/events/EventBus.d.ts.map b/packages/engine-core/dist/events/EventBus.d.ts.map deleted file mode 100644 index bbb284f..0000000 --- a/packages/engine-core/dist/events/EventBus.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"EventBus.d.ts","sourceRoot":"","sources":["../../src/events/EventBus.ts"],"names":[],"mappings":"AAAA,KAAK,YAAY,CAAC,CAAC,GAAG,OAAO,IAAI,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,CAAC;AAEnD,qBAAa,QAAQ;IACnB,OAAO,CAAC,SAAS,CAAqC;IAEtD,EAAE,CAAC,CAAC,GAAG,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,MAAM,IAAI;IAUpE,IAAI,CAAC,CAAC,GAAG,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,GAAG,IAAI;IAI/C,KAAK,IAAI,IAAI;CAGd"} \ No newline at end of file diff --git a/packages/engine-core/dist/events/EventBus.js b/packages/engine-core/dist/events/EventBus.js deleted file mode 100644 index fdd1929..0000000 --- a/packages/engine-core/dist/events/EventBus.js +++ /dev/null @@ -1,23 +0,0 @@ -export class EventBus { - constructor() { - this.listeners = new Map(); - } - on(event, handler) { - if (!this.listeners.has(event)) - this.listeners.set(event, []); - const handlers = this.listeners.get(event); - handlers.push(handler); - return () => { - const i = handlers.indexOf(handler); - if (i > -1) - handlers.splice(i, 1); - }; - } - emit(event, data) { - this.listeners.get(event)?.forEach((h) => h(data)); - } - clear() { - this.listeners.clear(); - } -} -//# sourceMappingURL=EventBus.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/events/EventBus.js.map b/packages/engine-core/dist/events/EventBus.js.map deleted file mode 100644 index 8f40645..0000000 --- a/packages/engine-core/dist/events/EventBus.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"EventBus.js","sourceRoot":"","sources":["../../src/events/EventBus.ts"],"names":[],"mappings":"AAEA,MAAM,OAAO,QAAQ;IAArB;QACU,cAAS,GAAG,IAAI,GAAG,EAA0B,CAAC;IAmBxD,CAAC;IAjBC,EAAE,CAAc,KAAa,EAAE,OAAwB;QACrD,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC;YAAE,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QAC9D,MAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,KAAK,CAAE,CAAC;QAC5C,QAAQ,CAAC,IAAI,CAAC,OAAuB,CAAC,CAAC;QACvC,OAAO,GAAG,EAAE;YACV,MAAM,CAAC,GAAG,QAAQ,CAAC,OAAO,CAAC,OAAuB,CAAC,CAAC;YACpD,IAAI,CAAC,GAAG,CAAC,CAAC;gBAAE,QAAQ,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QACpC,CAAC,CAAC;IACJ,CAAC;IAED,IAAI,CAAc,KAAa,EAAE,IAAO;QACtC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;IACrD,CAAC;IAED,KAAK;QACH,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC;IACzB,CAAC;CACF"} \ No newline at end of file diff --git a/packages/engine-core/dist/events/index.d.ts b/packages/engine-core/dist/events/index.d.ts deleted file mode 100644 index f6a2a33..0000000 --- a/packages/engine-core/dist/events/index.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export { EventBus } from "./EventBus"; -export { emitRuntimeEvent } from "./runtimeEvents"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/events/index.d.ts.map b/packages/engine-core/dist/events/index.d.ts.map deleted file mode 100644 index a437035..0000000 --- a/packages/engine-core/dist/events/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/events/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/events/index.js b/packages/engine-core/dist/events/index.js deleted file mode 100644 index 5952d33..0000000 --- a/packages/engine-core/dist/events/index.js +++ /dev/null @@ -1,3 +0,0 @@ -export { EventBus } from "./EventBus"; -export { emitRuntimeEvent } from "./runtimeEvents"; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/events/index.js.map b/packages/engine-core/dist/events/index.js.map deleted file mode 100644 index 683c549..0000000 --- a/packages/engine-core/dist/events/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/events/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/events/runtimeEvents.d.ts b/packages/engine-core/dist/events/runtimeEvents.d.ts deleted file mode 100644 index 6209040..0000000 --- a/packages/engine-core/dist/events/runtimeEvents.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { RuntimeEvent, RuntimeEventHandler } from "../game/types"; -/** - * Helper to safely dispatch a RuntimeEvent to a handler. - * No-ops if handler is undefined (optional event listener pattern). - */ -export declare function emitRuntimeEvent(handler: RuntimeEventHandler | undefined, event: RuntimeEvent): void; -//# sourceMappingURL=runtimeEvents.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/events/runtimeEvents.d.ts.map b/packages/engine-core/dist/events/runtimeEvents.d.ts.map deleted file mode 100644 index e022c35..0000000 --- a/packages/engine-core/dist/events/runtimeEvents.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"runtimeEvents.d.ts","sourceRoot":"","sources":["../../src/events/runtimeEvents.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAEvE;;;GAGG;AACH,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,mBAAmB,GAAG,SAAS,EACxC,KAAK,EAAE,YAAY,GAClB,IAAI,CAGN"} \ No newline at end of file diff --git a/packages/engine-core/dist/events/runtimeEvents.js b/packages/engine-core/dist/events/runtimeEvents.js deleted file mode 100644 index c7ab005..0000000 --- a/packages/engine-core/dist/events/runtimeEvents.js +++ /dev/null @@ -1,10 +0,0 @@ -/** - * Helper to safely dispatch a RuntimeEvent to a handler. - * No-ops if handler is undefined (optional event listener pattern). - */ -export function emitRuntimeEvent(handler, event) { - if (!handler) - return; - handler(event); -} -//# sourceMappingURL=runtimeEvents.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/events/runtimeEvents.js.map b/packages/engine-core/dist/events/runtimeEvents.js.map deleted file mode 100644 index 559a17a..0000000 --- a/packages/engine-core/dist/events/runtimeEvents.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"runtimeEvents.js","sourceRoot":"","sources":["../../src/events/runtimeEvents.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,MAAM,UAAU,gBAAgB,CAC9B,OAAwC,EACxC,KAAmB;IAEnB,IAAI,CAAC,OAAO;QAAE,OAAO;IACrB,OAAO,CAAC,KAAK,CAAC,CAAC;AACjB,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/commands/CommandHandler.d.ts b/packages/engine-core/dist/game/commands/CommandHandler.d.ts deleted file mode 100644 index b7a34ab..0000000 --- a/packages/engine-core/dist/game/commands/CommandHandler.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -import type { GameCommand, GameCommandType } from "./types"; -type Executor = (cmd: Extract) => void; -/** - * Despachador de comandos tipo-seguro. - * - * Completamente agnóstico: no importa nada de sceneStore, React ni R3F. - * El cableado a stores concretos se realiza desde el runtime (createGameRuntime) - * registrando executors via `register()`. - * - * Behavior: - * - Comando sin executor: invoca `onUnknown` (default: console.warn) y retorna. - * - Múltiples `register()` para el mismo tipo: el último gana. - * - `register()` retorna un `unsubscribe` para quitar el executor. - * - * Ver ADR-0006 para decisiones de diseño. - */ -export declare class CommandHandler { - private executors; - private unknownLogger; - constructor(opts?: { - onUnknown?: (cmd: GameCommand) => void; - }); - /** - * Registra un executor para un tipo de comando. - * Sobrescribe si ya existía uno para ese tipo. - * @returns unsubscribe — llámalo para eliminar el executor. - */ - register(type: T, executor: Executor): () => void; - /** - * Ejecuta un comando. Sync, fire-and-forget. - * Si no hay executor registrado para el tipo, invoca `onUnknown`. - */ - execute(cmd: GameCommand): void; - /** Para tests e introspección: lista de tipos con executor registrado. */ - registeredTypes(): GameCommandType[]; - /** Elimina todos los executors registrados. */ - clear(): void; -} -export {}; -//# sourceMappingURL=CommandHandler.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/commands/CommandHandler.d.ts.map b/packages/engine-core/dist/game/commands/CommandHandler.d.ts.map deleted file mode 100644 index a718cea..0000000 --- a/packages/engine-core/dist/game/commands/CommandHandler.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"CommandHandler.d.ts","sourceRoot":"","sources":["../../../src/game/commands/CommandHandler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE5D,KAAK,QAAQ,CAAC,CAAC,SAAS,eAAe,IAAI,CACzC,GAAG,EAAE,OAAO,CAAC,WAAW,EAAE;IAAE,IAAI,EAAE,CAAC,CAAA;CAAE,CAAC,KACnC,IAAI,CAAC;AAMV;;;;;;;;;;;;;GAaG;AACH,qBAAa,cAAc;IACzB,OAAO,CAAC,SAAS,CAAmB;IACpC,OAAO,CAAC,aAAa,CAA6B;gBAEtC,IAAI,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,CAAC,GAAG,EAAE,WAAW,KAAK,IAAI,CAAA;KAAE;IAM7D;;;;OAIG;IACH,QAAQ,CAAC,CAAC,SAAS,eAAe,EAAE,IAAI,EAAE,CAAC,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,MAAM,IAAI;IAO/E;;;OAGG;IACH,OAAO,CAAC,GAAG,EAAE,WAAW,GAAG,IAAI;IAW/B,0EAA0E;IAC1E,eAAe,IAAI,eAAe,EAAE;IAIpC,+CAA+C;IAC/C,KAAK,IAAI,IAAI;CAGd"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/commands/CommandHandler.js b/packages/engine-core/dist/game/commands/CommandHandler.js deleted file mode 100644 index 7589e05..0000000 --- a/packages/engine-core/dist/game/commands/CommandHandler.js +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Despachador de comandos tipo-seguro. - * - * Completamente agnóstico: no importa nada de sceneStore, React ni R3F. - * El cableado a stores concretos se realiza desde el runtime (createGameRuntime) - * registrando executors via `register()`. - * - * Behavior: - * - Comando sin executor: invoca `onUnknown` (default: console.warn) y retorna. - * - Múltiples `register()` para el mismo tipo: el último gana. - * - `register()` retorna un `unsubscribe` para quitar el executor. - * - * Ver ADR-0006 para decisiones de diseño. - */ -export class CommandHandler { - constructor(opts) { - this.executors = {}; - this.unknownLogger = - opts?.onUnknown ?? - ((cmd) => console.warn(`[CommandHandler] no executor for: ${cmd.type}`)); - } - /** - * Registra un executor para un tipo de comando. - * Sobrescribe si ya existía uno para ese tipo. - * @returns unsubscribe — llámalo para eliminar el executor. - */ - register(type, executor) { - this.executors[type] = executor; - return () => { - delete this.executors[type]; - }; - } - /** - * Ejecuta un comando. Sync, fire-and-forget. - * Si no hay executor registrado para el tipo, invoca `onUnknown`. - */ - execute(cmd) { - const executor = this.executors[cmd.type]; - if (!executor) { - this.unknownLogger(cmd); - return; - } - executor(cmd); - } - /** Para tests e introspección: lista de tipos con executor registrado. */ - registeredTypes() { - return Object.keys(this.executors); - } - /** Elimina todos los executors registrados. */ - clear() { - this.executors = {}; - } -} -//# sourceMappingURL=CommandHandler.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/commands/CommandHandler.js.map b/packages/engine-core/dist/game/commands/CommandHandler.js.map deleted file mode 100644 index e1a5e97..0000000 --- a/packages/engine-core/dist/game/commands/CommandHandler.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"CommandHandler.js","sourceRoot":"","sources":["../../../src/game/commands/CommandHandler.ts"],"names":[],"mappings":"AAUA;;;;;;;;;;;;;GAaG;AACH,MAAM,OAAO,cAAc;IAIzB,YAAY,IAAiD;QAHrD,cAAS,GAAgB,EAAE,CAAC;QAIlC,IAAI,CAAC,aAAa;YAChB,IAAI,EAAE,SAAS;gBACf,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,qCAAqC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;IAC7E,CAAC;IAED;;;;OAIG;IACH,QAAQ,CAA4B,IAAO,EAAE,QAAqB;QAC/D,IAAI,CAAC,SAAqC,CAAC,IAAI,CAAC,GAAG,QAAQ,CAAC;QAC7D,OAAO,GAAG,EAAE;YACV,OAAQ,IAAI,CAAC,SAAqC,CAAC,IAAI,CAAC,CAAC;QAC3D,CAAC,CAAC;IACJ,CAAC;IAED;;;OAGG;IACH,OAAO,CAAC,GAAgB;QACtB,MAAM,QAAQ,GACZ,IAAI,CAAC,SACN,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACZ,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC;YACxB,OAAO;QACT,CAAC;QACA,QAAuC,CAAC,GAAG,CAAC,CAAC;IAChD,CAAC;IAED,0EAA0E;IAC1E,eAAe;QACb,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAsB,CAAC;IAC1D,CAAC;IAED,+CAA+C;IAC/C,KAAK;QACH,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;IACtB,CAAC;CACF"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/commands/index.d.ts b/packages/engine-core/dist/game/commands/index.d.ts deleted file mode 100644 index b06f527..0000000 --- a/packages/engine-core/dist/game/commands/index.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export type { GameCommand, GameCommandType } from "./types"; -export { CommandHandler } from "./CommandHandler"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/commands/index.d.ts.map b/packages/engine-core/dist/game/commands/index.d.ts.map deleted file mode 100644 index 4861c69..0000000 --- a/packages/engine-core/dist/game/commands/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/game/commands/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/commands/index.js b/packages/engine-core/dist/game/commands/index.js deleted file mode 100644 index 1f6b1aa..0000000 --- a/packages/engine-core/dist/game/commands/index.js +++ /dev/null @@ -1,2 +0,0 @@ -export { CommandHandler } from "./CommandHandler"; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/commands/index.js.map b/packages/engine-core/dist/game/commands/index.js.map deleted file mode 100644 index 05a3369..0000000 --- a/packages/engine-core/dist/game/commands/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/game/commands/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/commands/types.d.ts b/packages/engine-core/dist/game/commands/types.d.ts deleted file mode 100644 index b411cc8..0000000 --- a/packages/engine-core/dist/game/commands/types.d.ts +++ /dev/null @@ -1,63 +0,0 @@ -import type { DialogDictionary, GameVec3, Locale, SoundCategory } from "../types"; -type AudioMuteTarget = "master" | SoundCategory; -/** - * Union exhaustiva de todos los comandos que el motor acepta. - * Naming: : (ver ADR-0006). - */ -export type GameCommand = { - type: "scene:set"; - sceneId: string; -} | { - type: "scene:respawn"; -} | { - type: "player:move"; - position: GameVec3; -} | { - type: "player:stop"; -} | { - type: "player:walkTo"; - position: GameVec3; -} | { - type: "inventory:toggle"; -} | { - type: "inventory:pickup"; - itemId: string; -} | { - type: "inventory:drop"; - itemId: string; - slotIndex: number; -} | { - type: "dialog:trigger"; - dialogKey: string; -} | { - type: "dialog:dismiss"; -} | { - type: "transition:activate"; - transitionId: string; -} | { - type: "transition:cancel"; - transitionId: string; -} | { - type: "audio:playSfx"; - soundUrl: string; - category?: SoundCategory; - volume?: number; -} | { - type: "audio:setMuted"; - target: AudioMuteTarget; - muted: boolean; -} | { - type: "audio:setVolume"; - target: AudioMuteTarget; - volume: number; -} | { - type: "i18n:setLocale"; - locale: Locale; -} | { - type: "i18n:registerDictionary"; - locale: Locale; - dict: DialogDictionary; -}; -export type GameCommandType = GameCommand["type"]; -export {}; -//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/commands/types.d.ts.map b/packages/engine-core/dist/game/commands/types.d.ts.map deleted file mode 100644 index ad62c13..0000000 --- a/packages/engine-core/dist/game/commands/types.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/game/commands/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAGlF,KAAK,eAAe,GAAG,QAAQ,GAAG,aAAa,CAAC;AAEhD;;;GAGG;AACH,MAAM,MAAM,WAAW,GAEnB;IAAE,IAAI,EAAE,WAAW,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GACtC;IAAE,IAAI,EAAE,eAAe,CAAA;CAAE,GAEzB;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC,QAAQ,EAAE,QAAQ,CAAA;CAAE,GAC3C;IAAE,IAAI,EAAE,aAAa,CAAA;CAAE,GACvB;IAAE,IAAI,EAAE,eAAe,CAAC;IAAC,QAAQ,EAAE,QAAQ,CAAA;CAAE,GAE7C;IAAE,IAAI,EAAE,kBAAkB,CAAA;CAAE,GAC5B;IAAE,IAAI,EAAE,kBAAkB,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAC5C;IAAE,IAAI,EAAE,gBAAgB,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GAE7D;IAAE,IAAI,EAAE,gBAAgB,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GAC7C;IAAE,IAAI,EAAE,gBAAgB,CAAA;CAAE,GAE1B;IAAE,IAAI,EAAE,qBAAqB,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,GACrD;IAAE,IAAI,EAAE,mBAAmB,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,GAEnD;IAAE,IAAI,EAAE,eAAe,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,aAAa,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GACtF;IAAE,IAAI,EAAE,gBAAgB,CAAC;IAAC,MAAM,EAAE,eAAe,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,GACnE;IAAE,IAAI,EAAE,iBAAiB,CAAC;IAAC,MAAM,EAAE,eAAe,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAEpE;IAAE,IAAI,EAAE,gBAAgB,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAC1C;IAAE,IAAI,EAAE,yBAAyB,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,gBAAgB,CAAA;CAAE,CAAC;AAEhF,MAAM,MAAM,eAAe,GAAG,WAAW,CAAC,MAAM,CAAC,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/commands/types.js b/packages/engine-core/dist/game/commands/types.js deleted file mode 100644 index 718fd38..0000000 --- a/packages/engine-core/dist/game/commands/types.js +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/commands/types.js.map b/packages/engine-core/dist/game/commands/types.js.map deleted file mode 100644 index 804b973..0000000 --- a/packages/engine-core/dist/game/commands/types.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/game/commands/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/engine-core/dist/game/events/index.d.ts b/packages/engine-core/dist/game/events/index.d.ts deleted file mode 100644 index 76aa76b..0000000 --- a/packages/engine-core/dist/game/events/index.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export type { GameEvent, GameEventType, GameEventHandler } from "./types"; -export { legacyRuntimeEventToGameEvent, gameEventToLegacyRuntimeEvent, } from "./legacyAdapter"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/events/index.d.ts.map b/packages/engine-core/dist/game/events/index.d.ts.map deleted file mode 100644 index f18604f..0000000 --- a/packages/engine-core/dist/game/events/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/game/events/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,SAAS,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAC1E,OAAO,EACL,6BAA6B,EAC7B,6BAA6B,GAC9B,MAAM,iBAAiB,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/events/index.js b/packages/engine-core/dist/game/events/index.js deleted file mode 100644 index e173902..0000000 --- a/packages/engine-core/dist/game/events/index.js +++ /dev/null @@ -1,2 +0,0 @@ -export { legacyRuntimeEventToGameEvent, gameEventToLegacyRuntimeEvent, } from "./legacyAdapter"; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/events/index.js.map b/packages/engine-core/dist/game/events/index.js.map deleted file mode 100644 index 425646d..0000000 --- a/packages/engine-core/dist/game/events/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/game/events/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,6BAA6B,EAC7B,6BAA6B,GAC9B,MAAM,iBAAiB,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/events/legacyAdapter.d.ts b/packages/engine-core/dist/game/events/legacyAdapter.d.ts deleted file mode 100644 index e6656d9..0000000 --- a/packages/engine-core/dist/game/events/legacyAdapter.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { GameEvent } from "./types"; -import type { RuntimeEvent } from "../types"; -/** - * Mapea un RuntimeEvent legacy (onMove/onCollide/onDrop/onDialog) - * al nuevo GameEvent equivalente. Permite mantener el callback - * `onRuntimeEvent` mientras el bus es la fuente de verdad. - */ -export declare function legacyRuntimeEventToGameEvent(ev: RuntimeEvent): GameEvent; -/** - * Inverso: GameEvent → RuntimeEvent (solo los 4 legacy soportados). - * Retorna null para eventos sin equivalente legacy (ej. scene:changed). - */ -export declare function gameEventToLegacyRuntimeEvent(ev: GameEvent): RuntimeEvent | null; -//# sourceMappingURL=legacyAdapter.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/events/legacyAdapter.d.ts.map b/packages/engine-core/dist/game/events/legacyAdapter.d.ts.map deleted file mode 100644 index cb85333..0000000 --- a/packages/engine-core/dist/game/events/legacyAdapter.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"legacyAdapter.d.ts","sourceRoot":"","sources":["../../../src/game/events/legacyAdapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAE7C;;;;GAIG;AACH,wBAAgB,6BAA6B,CAAC,EAAE,EAAE,YAAY,GAAG,SAAS,CAyBzE;AAED;;;GAGG;AACH,wBAAgB,6BAA6B,CAAC,EAAE,EAAE,SAAS,GAAG,YAAY,GAAG,IAAI,CAuBhF"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/events/legacyAdapter.js b/packages/engine-core/dist/game/events/legacyAdapter.js deleted file mode 100644 index f6ac1e6..0000000 --- a/packages/engine-core/dist/game/events/legacyAdapter.js +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Mapea un RuntimeEvent legacy (onMove/onCollide/onDrop/onDialog) - * al nuevo GameEvent equivalente. Permite mantener el callback - * `onRuntimeEvent` mientras el bus es la fuente de verdad. - */ -export function legacyRuntimeEventToGameEvent(ev) { - switch (ev.type) { - case "onMove": - return { type: "player:moved", position: ev.position, action: ev.action }; - case "onCollide": - return { - type: "player:collided", - reason: ev.reason, - position: ev.position, - }; - case "onDrop": - return { - type: "item:dropped", - itemId: ev.itemId, - outcome: ev.outcome, - interactionId: ev.interactionId, - }; - case "onDialog": - return { - type: "dialog:triggered", - text: ev.text, - dialogKey: ev.dialogKey, - source: ev.source, - }; - } -} -/** - * Inverso: GameEvent → RuntimeEvent (solo los 4 legacy soportados). - * Retorna null para eventos sin equivalente legacy (ej. scene:changed). - */ -export function gameEventToLegacyRuntimeEvent(ev) { - switch (ev.type) { - case "player:moved": - return { type: "onMove", position: ev.position, action: ev.action }; - case "player:collided": - return { type: "onCollide", reason: ev.reason, position: ev.position }; - case "item:dropped": - return { - type: "onDrop", - itemId: ev.itemId, - outcome: ev.outcome, - interactionId: ev.interactionId, - }; - case "dialog:triggered": - return { - type: "onDialog", - text: ev.text, - dialogKey: ev.dialogKey, - source: ev.source, - }; - default: - return null; - } -} -//# sourceMappingURL=legacyAdapter.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/events/legacyAdapter.js.map b/packages/engine-core/dist/game/events/legacyAdapter.js.map deleted file mode 100644 index 1a76f12..0000000 --- a/packages/engine-core/dist/game/events/legacyAdapter.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"legacyAdapter.js","sourceRoot":"","sources":["../../../src/game/events/legacyAdapter.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AACH,MAAM,UAAU,6BAA6B,CAAC,EAAgB;IAC5D,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC;QAChB,KAAK,QAAQ;YACX,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,QAAQ,EAAE,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,CAAC,MAAM,EAAE,CAAC;QAC5E,KAAK,WAAW;YACd,OAAO;gBACL,IAAI,EAAE,iBAAiB;gBACvB,MAAM,EAAE,EAAE,CAAC,MAAM;gBACjB,QAAQ,EAAE,EAAE,CAAC,QAAQ;aACtB,CAAC;QACJ,KAAK,QAAQ;YACX,OAAO;gBACL,IAAI,EAAE,cAAc;gBACpB,MAAM,EAAE,EAAE,CAAC,MAAM;gBACjB,OAAO,EAAE,EAAE,CAAC,OAAyC;gBACrD,aAAa,EAAE,EAAE,CAAC,aAAa;aAChC,CAAC;QACJ,KAAK,UAAU;YACb,OAAO;gBACL,IAAI,EAAE,kBAAkB;gBACxB,IAAI,EAAE,EAAE,CAAC,IAAI;gBACb,SAAS,EAAE,EAAE,CAAC,SAAS;gBACvB,MAAM,EAAE,EAAE,CAAC,MAAM;aAClB,CAAC;IACN,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,6BAA6B,CAAC,EAAa;IACzD,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC;QAChB,KAAK,cAAc;YACjB,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,CAAC,MAAM,EAAE,CAAC;QACtE,KAAK,iBAAiB;YACpB,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,EAAE,CAAC,MAAM,EAAE,QAAQ,EAAE,EAAE,CAAC,QAAQ,EAAE,CAAC;QACzE,KAAK,cAAc;YACjB,OAAO;gBACL,IAAI,EAAE,QAAQ;gBACd,MAAM,EAAE,EAAE,CAAC,MAAM;gBACjB,OAAO,EAAE,EAAE,CAAC,OAAO;gBACnB,aAAa,EAAE,EAAE,CAAC,aAAa;aAChC,CAAC;QACJ,KAAK,kBAAkB;YACrB,OAAO;gBACL,IAAI,EAAE,UAAU;gBAChB,IAAI,EAAE,EAAE,CAAC,IAAI;gBACb,SAAS,EAAE,EAAE,CAAC,SAAS;gBACvB,MAAM,EAAE,EAAE,CAAC,MAA4C;aACxD,CAAC;QACJ;YACE,OAAO,IAAI,CAAC;IAChB,CAAC;AACH,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/events/types.d.ts b/packages/engine-core/dist/game/events/types.d.ts deleted file mode 100644 index e00bd18..0000000 --- a/packages/engine-core/dist/game/events/types.d.ts +++ /dev/null @@ -1,92 +0,0 @@ -import type { AudioSettings, GameScene, GameVec3, Locale, SoundCategory } from "../types"; -/** - * Union exhaustiva de todos los eventos que el motor puede emitir. - * Naming: : (ver ADR-0006). - */ -export type GameEvent = { - type: "scene:changed"; - sceneId: string; - scene: GameScene; -} | { - type: "scene:respawnRequested"; - sceneId: string; -} | { - type: "player:moved"; - position: GameVec3; - action: "idle" | "north" | "south" | "west" | "east"; -} | { - type: "player:collided"; - reason: "boundary" | "stuck" | "pathblocked"; - position: GameVec3; -} | { - type: "item:pickedUp"; - itemId: string; - quantity: number; -} | { - type: "item:dropped"; - itemId: string; - outcome: "consume" | "place" | "return"; - interactionId?: string; -} | { - type: "dialog:triggered"; - text: string; - dialogKey?: string; - source: string; -} | { - type: "dialog:dismissed"; - dialogKey?: string; -} | { - type: "transition:triggered"; - transitionId: string; - targetSceneId: string; -} | { - type: "transition:started"; - transitionId: string; -} | { - type: "transition:completed"; - fromSceneId: string; - toSceneId: string; -} | { - type: "transition:colliderClicked"; - transitionId: string; - position: GameVec3; -} | { - type: "player:walkStarted"; - targetPosition: GameVec3; -} | { - type: "player:walkCompleted"; - position: GameVec3; -} | { - type: "player:walkAborted"; - reason: "user-input" | "collision" | "unreachable"; -} | { - type: "audio:sfxRequested"; - soundUrl: string; - category: SoundCategory; - volume?: number; -} | { - type: "audio:musicRequested"; - trackUrl: string; - fadeMs?: number; - volume?: number; - loop?: boolean; -} | { - type: "audio:musicStopped"; - fadeMs?: number; -} | { - type: "audio:settingsChanged"; - settings: AudioSettings; -} | { - type: "i18n:localeChanged"; - locale: Locale; - previous: Locale; -} | { - type: "i18n:dictionaryUpdated"; - locale: Locale; - keysAdded: number; -}; -export type GameEventType = GameEvent["type"]; -export type GameEventHandler = (event: Extract) => void; -//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/events/types.d.ts.map b/packages/engine-core/dist/game/events/types.d.ts.map deleted file mode 100644 index a75c015..0000000 --- a/packages/engine-core/dist/game/events/types.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"types.d.ts","sourceRoot":"","sources":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AE,CAAC;AAE1E,MAAM,MAAM,aAAa,GAAG,SAAS,CAAC,MAAM,CAAC,CAAC;AAE9C,MAAM,MAAM,gBAAgB,CAAC,CAAC,SAAS,aAAa,GAAG,aAAa,IAAI,CACtE,KAAK,EAAE,OAAO,CAAC,SAAS,EAAE;IAAE,IAAI,EAAE,CAAC,CAAA;CAAE,CAAC,KACnC,IAAI,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/events/types.js b/packages/engine-core/dist/game/events/types.js deleted file mode 100644 index 718fd38..0000000 --- a/packages/engine-core/dist/game/events/types.js +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/events/types.js.map b/packages/engine-core/dist/game/events/types.js.map deleted file mode 100644 index 2166492..0000000 --- a/packages/engine-core/dist/game/events/types.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/game/events/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/engine-core/dist/game/i18n/executors.d.ts b/packages/engine-core/dist/game/i18n/executors.d.ts deleted file mode 100644 index 9df3cba..0000000 --- a/packages/engine-core/dist/game/i18n/executors.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { CommandHandler } from "../commands/CommandHandler"; -import type { GameEvent } from "../events/types"; -type EmitFn = (event: GameEvent) => void; -/** - * Register i18n command executors against a {@link CommandHandler}. Returns - * an unsubscribe that removes every executor installed by this call. - * - * `emit` is invoked when a dictionary changes; the locale change event is - * emitted by the store itself (see `setI18nStoreEmitter`). - */ -export declare function registerI18nExecutors(commands: CommandHandler, emit?: EmitFn): () => void; -export {}; -//# sourceMappingURL=executors.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/i18n/executors.d.ts.map b/packages/engine-core/dist/game/i18n/executors.d.ts.map deleted file mode 100644 index 0e1fb30..0000000 --- a/packages/engine-core/dist/game/i18n/executors.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"executors.d.ts","sourceRoot":"","sources":["../../../src/game/i18n/executors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAIjD,KAAK,MAAM,GAAG,CAAC,KAAK,EAAE,SAAS,KAAK,IAAI,CAAC;AAEzC;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CACnC,QAAQ,EAAE,cAAc,EACxB,IAAI,CAAC,EAAE,MAAM,GACZ,MAAM,IAAI,CAyBZ"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/i18n/executors.js b/packages/engine-core/dist/game/i18n/executors.js deleted file mode 100644 index 46cd438..0000000 --- a/packages/engine-core/dist/game/i18n/executors.js +++ /dev/null @@ -1,30 +0,0 @@ -import { getI18nStore } from "../state/i18nStore"; -import { getDictionary, registerDictionary } from "./registry"; -/** - * Register i18n command executors against a {@link CommandHandler}. Returns - * an unsubscribe that removes every executor installed by this call. - * - * `emit` is invoked when a dictionary changes; the locale change event is - * emitted by the store itself (see `setI18nStoreEmitter`). - */ -export function registerI18nExecutors(commands, emit) { - const unsubscribeFns = []; - unsubscribeFns.push(commands.register("i18n:setLocale", (cmd) => { - getI18nStore().setLocale(cmd.locale); - })); - unsubscribeFns.push(commands.register("i18n:registerDictionary", (cmd) => { - const before = Object.keys(getDictionary(cmd.locale) ?? {}).length; - registerDictionary(cmd.locale, cmd.dict); - const after = Object.keys(getDictionary(cmd.locale) ?? {}).length; - emit?.({ - type: "i18n:dictionaryUpdated", - locale: cmd.locale, - keysAdded: after - before, - }); - })); - return () => { - for (const fn of unsubscribeFns) - fn(); - }; -} -//# sourceMappingURL=executors.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/i18n/executors.js.map b/packages/engine-core/dist/game/i18n/executors.js.map deleted file mode 100644 index ec6817a..0000000 --- a/packages/engine-core/dist/game/i18n/executors.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"executors.js","sourceRoot":"","sources":["../../../src/game/i18n/executors.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAI/D;;;;;;GAMG;AACH,MAAM,UAAU,qBAAqB,CACnC,QAAwB,EACxB,IAAa;IAEb,MAAM,cAAc,GAAsB,EAAE,CAAC;IAE7C,cAAc,CAAC,IAAI,CACjB,QAAQ,CAAC,QAAQ,CAAC,gBAAgB,EAAE,CAAC,GAAG,EAAE,EAAE;QAC1C,YAAY,EAAE,CAAC,SAAS,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACvC,CAAC,CAAC,CACH,CAAC;IAEF,cAAc,CAAC,IAAI,CACjB,QAAQ,CAAC,QAAQ,CAAC,yBAAyB,EAAE,CAAC,GAAG,EAAE,EAAE;QACnD,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC;QACnE,kBAAkB,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;QACzC,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC;QAClE,IAAI,EAAE,CAAC;YACL,IAAI,EAAE,wBAAwB;YAC9B,MAAM,EAAE,GAAG,CAAC,MAAM;YAClB,SAAS,EAAE,KAAK,GAAG,MAAM;SAC1B,CAAC,CAAC;IACL,CAAC,CAAC,CACH,CAAC;IAEF,OAAO,GAAG,EAAE;QACV,KAAK,MAAM,EAAE,IAAI,cAAc;YAAE,EAAE,EAAE,CAAC;IACxC,CAAC,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/i18n/index.d.ts b/packages/engine-core/dist/game/i18n/index.d.ts deleted file mode 100644 index 491abda..0000000 --- a/packages/engine-core/dist/game/i18n/index.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export { registerDictionary, registerDictionaries, getDictionary, clearRegistry, getRegisteredLocales, } from "./registry"; -export { translate, getRandomPhrase, matchLocale, type TranslateOptions, type GetRandomPhraseOptions, } from "./translator"; -export { registerI18nExecutors } from "./executors"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/i18n/index.d.ts.map b/packages/engine-core/dist/game/i18n/index.d.ts.map deleted file mode 100644 index f000094..0000000 --- a/packages/engine-core/dist/game/i18n/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/game/i18n/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,oBAAoB,EACpB,aAAa,EACb,aAAa,EACb,oBAAoB,GACrB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,SAAS,EACT,eAAe,EACf,WAAW,EACX,KAAK,gBAAgB,EACrB,KAAK,sBAAsB,GAC5B,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/i18n/index.js b/packages/engine-core/dist/game/i18n/index.js deleted file mode 100644 index 9d25470..0000000 --- a/packages/engine-core/dist/game/i18n/index.js +++ /dev/null @@ -1,4 +0,0 @@ -export { registerDictionary, registerDictionaries, getDictionary, clearRegistry, getRegisteredLocales, } from "./registry"; -export { translate, getRandomPhrase, matchLocale, } from "./translator"; -export { registerI18nExecutors } from "./executors"; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/i18n/index.js.map b/packages/engine-core/dist/game/i18n/index.js.map deleted file mode 100644 index bc773ea..0000000 --- a/packages/engine-core/dist/game/i18n/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/game/i18n/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,oBAAoB,EACpB,aAAa,EACb,aAAa,EACb,oBAAoB,GACrB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,SAAS,EACT,eAAe,EACf,WAAW,GAGZ,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/i18n/registry.d.ts b/packages/engine-core/dist/game/i18n/registry.d.ts deleted file mode 100644 index 2005d83..0000000 --- a/packages/engine-core/dist/game/i18n/registry.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -import type { DialogDictionary, Locale, LocaleDictionaries } from "../types"; -/** - * Register (or extend) a dictionary for a locale. Existing keys are - * overwritten with a warning in development; new keys are merged in. - */ -export declare function registerDictionary(locale: Locale, dict: DialogDictionary): void; -/** Register multiple locales at once. */ -export declare function registerDictionaries(all: LocaleDictionaries): void; -/** Lookup the current dictionary for `locale`. */ -export declare function getDictionary(locale: Locale): DialogDictionary | undefined; -/** Empty the registry. Primarily for tests / `resetI18n`. */ -export declare function clearRegistry(): void; -/** Diagnostic helper — list all currently registered locales. */ -export declare function getRegisteredLocales(): Locale[]; -//# sourceMappingURL=registry.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/i18n/registry.d.ts.map b/packages/engine-core/dist/game/i18n/registry.d.ts.map deleted file mode 100644 index ed893f7..0000000 --- a/packages/engine-core/dist/game/i18n/registry.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../../src/game/i18n/registry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAChB,MAAM,EACN,kBAAkB,EACnB,MAAM,UAAU,CAAC;AAYlB;;;GAGG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,gBAAgB,GACrB,IAAI,CAgBN;AAED,yCAAyC;AACzC,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,kBAAkB,GAAG,IAAI,CAIlE;AAED,kDAAkD;AAClD,wBAAgB,aAAa,CAC3B,MAAM,EAAE,MAAM,GACb,gBAAgB,GAAG,SAAS,CAE9B;AAED,6DAA6D;AAC7D,wBAAgB,aAAa,IAAI,IAAI,CAEpC;AAED,iEAAiE;AACjE,wBAAgB,oBAAoB,IAAI,MAAM,EAAE,CAE/C"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/i18n/registry.js b/packages/engine-core/dist/game/i18n/registry.js deleted file mode 100644 index fc20ea7..0000000 --- a/packages/engine-core/dist/game/i18n/registry.js +++ /dev/null @@ -1,47 +0,0 @@ -const SHOULD_WARN = (() => { - try { - return typeof process !== "undefined" && process.env?.NODE_ENV !== "production"; - } - catch { - return false; - } -})(); -const registry = new Map(); -/** - * Register (or extend) a dictionary for a locale. Existing keys are - * overwritten with a warning in development; new keys are merged in. - */ -export function registerDictionary(locale, dict) { - const existing = registry.get(locale); - if (!existing) { - registry.set(locale, { ...dict }); - return; - } - if (SHOULD_WARN && typeof console !== "undefined") { - for (const key of Object.keys(dict)) { - if (existing[key]) { - console.warn(`[i18n] overwriting key "${key}" in locale "${locale}"`); - } - } - } - registry.set(locale, { ...existing, ...dict }); -} -/** Register multiple locales at once. */ -export function registerDictionaries(all) { - for (const locale of Object.keys(all)) { - registerDictionary(locale, all[locale]); - } -} -/** Lookup the current dictionary for `locale`. */ -export function getDictionary(locale) { - return registry.get(locale); -} -/** Empty the registry. Primarily for tests / `resetI18n`. */ -export function clearRegistry() { - registry.clear(); -} -/** Diagnostic helper — list all currently registered locales. */ -export function getRegisteredLocales() { - return Array.from(registry.keys()); -} -//# sourceMappingURL=registry.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/i18n/registry.js.map b/packages/engine-core/dist/game/i18n/registry.js.map deleted file mode 100644 index 6fb8ea3..0000000 --- a/packages/engine-core/dist/game/i18n/registry.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"registry.js","sourceRoot":"","sources":["../../../src/game/i18n/registry.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,GAAG,CAAC,GAAG,EAAE;IACxB,IAAI,CAAC;QACH,OAAO,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,CAAC,GAAG,EAAE,QAAQ,KAAK,YAAY,CAAC;IAClF,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC,CAAC,EAAE,CAAC;AAEL,MAAM,QAAQ,GAAG,IAAI,GAAG,EAA4B,CAAC;AAErD;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CAChC,MAAc,EACd,IAAsB;IAEtB,MAAM,QAAQ,GAAG,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACtC,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,QAAQ,CAAC,GAAG,CAAC,MAAM,EAAE,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC;QAClC,OAAO;IACT,CAAC;IACD,IAAI,WAAW,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE,CAAC;QAClD,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;YACpC,IAAI,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;gBAClB,OAAO,CAAC,IAAI,CACV,2BAA2B,GAAG,gBAAgB,MAAM,GAAG,CACxD,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC;IACD,QAAQ,CAAC,GAAG,CAAC,MAAM,EAAE,EAAE,GAAG,QAAQ,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC;AACjD,CAAC;AAED,yCAAyC;AACzC,MAAM,UAAU,oBAAoB,CAAC,GAAuB;IAC1D,KAAK,MAAM,MAAM,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;QACtC,kBAAkB,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,CAAE,CAAC,CAAC;IAC3C,CAAC;AACH,CAAC;AAED,kDAAkD;AAClD,MAAM,UAAU,aAAa,CAC3B,MAAc;IAEd,OAAO,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;AAC9B,CAAC;AAED,6DAA6D;AAC7D,MAAM,UAAU,aAAa;IAC3B,QAAQ,CAAC,KAAK,EAAE,CAAC;AACnB,CAAC;AAED,iEAAiE;AACjE,MAAM,UAAU,oBAAoB;IAClC,OAAO,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;AACrC,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/i18n/translator.d.ts b/packages/engine-core/dist/game/i18n/translator.d.ts deleted file mode 100644 index 6275a47..0000000 --- a/packages/engine-core/dist/game/i18n/translator.d.ts +++ /dev/null @@ -1,34 +0,0 @@ -import type { DialogKey, Locale } from "../types"; -export interface TranslateOptions { - vars?: Record; - /** Override of the locale read from the store (e.g. for SSR). */ - locale?: Locale; -} -export interface GetRandomPhraseOptions { - vars?: Record; - locale?: Locale; - /** Injectable RNG for deterministic tests. Default: `Math.random`. */ - random?: () => number; -} -/** - * Translate a key against the active locale, falling back to - * `fallbackLocale` and finally the raw key when missing. - * - * Supports `{{var}}` interpolation via `opts.vars`. - */ -export declare function translate(key: DialogKey, opts?: TranslateOptions): string; -/** - * Pick a random phrase for `key`. Same fallback chain as {@link translate}. - * - * Pass `random` to make the choice deterministic in tests. - */ -export declare function getRandomPhrase(key: DialogKey, opts?: GetRandomPhraseOptions): string; -/** - * Best-effort BCP-47 negotiation. - * - * 1. exact match in `available` → return it - * 2. primary subtag match (e.g. "es-MX" → "es") → return it - * 3. otherwise → `null` - */ -export declare function matchLocale(candidate: string, available: Locale[]): Locale | null; -//# sourceMappingURL=translator.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/i18n/translator.d.ts.map b/packages/engine-core/dist/game/i18n/translator.d.ts.map deleted file mode 100644 index 933cfc5..0000000 --- a/packages/engine-core/dist/game/i18n/translator.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"translator.d.ts","sourceRoot":"","sources":["../../../src/game/i18n/translator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAIlD,MAAM,WAAW,gBAAgB;IAC/B,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,CAAC;IACvC,iEAAiE;IACjE,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,sBAAsB;IACrC,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,CAAC;IACvC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,sEAAsE;IACtE,MAAM,CAAC,EAAE,MAAM,MAAM,CAAC;CACvB;AAyBD;;;;;GAKG;AACH,wBAAgB,SAAS,CACvB,GAAG,EAAE,SAAS,EACd,IAAI,GAAE,gBAAqB,GAC1B,MAAM,CAQR;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,GAAG,EAAE,SAAS,EACd,IAAI,GAAE,sBAA2B,GAChC,MAAM,CAsBR;AAED;;;;;;GAMG;AACH,wBAAgB,WAAW,CACzB,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,EAAE,GAClB,MAAM,GAAG,IAAI,CAMf"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/i18n/translator.js b/packages/engine-core/dist/game/i18n/translator.js deleted file mode 100644 index 7d3cbf2..0000000 --- a/packages/engine-core/dist/game/i18n/translator.js +++ /dev/null @@ -1,73 +0,0 @@ -import { getI18nStore } from "../state/i18nStore"; -import { getDictionary } from "./registry"; -const INTERP_RE = /\{\{(\w+)\}\}/g; -function interpolate(template, vars) { - if (!vars) - return template; - return template.replace(INTERP_RE, (_match, name) => { - const v = vars[name]; - return v !== undefined ? String(v) : `{{${name}}}`; - }); -} -function lookupFirstPhrase(key, locale) { - const dict = getDictionary(locale); - const entry = dict?.[key]; - if (!entry || entry.phrases.length === 0) - return undefined; - return entry.phrases[0]; -} -/** - * Translate a key against the active locale, falling back to - * `fallbackLocale` and finally the raw key when missing. - * - * Supports `{{var}}` interpolation via `opts.vars`. - */ -export function translate(key, opts = {}) { - const { locale, fallbackLocale } = getI18nStore().getState(); - const active = opts.locale ?? locale; - const raw = lookupFirstPhrase(key, active) ?? - (active !== fallbackLocale ? lookupFirstPhrase(key, fallbackLocale) : undefined) ?? - key; - return interpolate(raw, opts.vars); -} -/** - * Pick a random phrase for `key`. Same fallback chain as {@link translate}. - * - * Pass `random` to make the choice deterministic in tests. - */ -export function getRandomPhrase(key, opts = {}) { - const { locale, fallbackLocale } = getI18nStore().getState(); - const active = opts.locale ?? locale; - const rng = opts.random ?? Math.random; - const dict = getDictionary(active) ?? - (active !== fallbackLocale ? getDictionary(fallbackLocale) : undefined); - const entry = dict?.[key]; - // Try fallback when active dict exists but lacks the key. - const finalEntry = entry ?? - (active !== fallbackLocale - ? getDictionary(fallbackLocale)?.[key] - : undefined); - if (!finalEntry || finalEntry.phrases.length === 0) - return key; - const idx = Math.floor(rng() * finalEntry.phrases.length); - const phrase = finalEntry.phrases[idx] ?? finalEntry.phrases[0]; - return interpolate(phrase, opts.vars); -} -/** - * Best-effort BCP-47 negotiation. - * - * 1. exact match in `available` → return it - * 2. primary subtag match (e.g. "es-MX" → "es") → return it - * 3. otherwise → `null` - */ -export function matchLocale(candidate, available) { - if (!candidate) - return null; - if (available.includes(candidate)) - return candidate; - const primary = candidate.split("-")[0]; - if (available.includes(primary)) - return primary; - return null; -} -//# sourceMappingURL=translator.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/i18n/translator.js.map b/packages/engine-core/dist/game/i18n/translator.js.map deleted file mode 100644 index f59d9d2..0000000 --- a/packages/engine-core/dist/game/i18n/translator.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"translator.js","sourceRoot":"","sources":["../../../src/game/i18n/translator.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAe3C,MAAM,SAAS,GAAG,gBAAgB,CAAC;AAEnC,SAAS,WAAW,CAClB,QAAgB,EAChB,IAAsC;IAEtC,IAAI,CAAC,IAAI;QAAE,OAAO,QAAQ,CAAC;IAC3B,OAAO,QAAQ,CAAC,OAAO,CAAC,SAAS,EAAE,CAAC,MAAM,EAAE,IAAY,EAAE,EAAE;QAC1D,MAAM,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC;QACrB,OAAO,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC;IACrD,CAAC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,iBAAiB,CACxB,GAAc,EACd,MAAc;IAEd,MAAM,IAAI,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC;IACnC,MAAM,KAAK,GAAG,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC;IAC1B,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IAC3D,OAAO,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;AAC1B,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CACvB,GAAc,EACd,OAAyB,EAAE;IAE3B,MAAM,EAAE,MAAM,EAAE,cAAc,EAAE,GAAG,YAAY,EAAE,CAAC,QAAQ,EAAE,CAAC;IAC7D,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC;IACrC,MAAM,GAAG,GACP,iBAAiB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CAAE,CAAC;IACjE,OAAO,WAAW,CAAC,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;AACxC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CACzB,SAAiB,EACjB,SAAmB;IAEnB,IAAI,CAAC,SAAS;QAAE,OAAO,IAAI,CAAC;IAC5B,IAAI,SAAS,CAAC,QAAQ,CAAC,SAAS,CAAC;QAAE,OAAO,SAAS,CAAC;IACpD,MAAM,OAAO,GAAG,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAE,CAAC;IACzC,IAAI,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC;QAAE,OAAO,OAAO,CAAC;IAChD,OAAO,IAAI,CAAC;AACd,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/index.d.ts b/packages/engine-core/dist/game/logic/index.d.ts deleted file mode 100644 index f6926ef..0000000 --- a/packages/engine-core/dist/game/logic/index.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -export { findPath } from "./pathfinding/findPath"; -export type { MovementPoint } from "./pathfinding/findPath"; -export * from "./rules"; -export * from "./transitions"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/index.d.ts.map b/packages/engine-core/dist/game/logic/index.d.ts.map deleted file mode 100644 index 2143cf8..0000000 --- a/packages/engine-core/dist/game/logic/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/game/logic/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAClD,YAAY,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAC5D,cAAc,SAAS,CAAC;AACxB,cAAc,eAAe,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/index.js b/packages/engine-core/dist/game/logic/index.js deleted file mode 100644 index ba7f952..0000000 --- a/packages/engine-core/dist/game/logic/index.js +++ /dev/null @@ -1,4 +0,0 @@ -export { findPath } from "./pathfinding/findPath"; -export * from "./rules"; -export * from "./transitions"; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/index.js.map b/packages/engine-core/dist/game/logic/index.js.map deleted file mode 100644 index c4b2b4a..0000000 --- a/packages/engine-core/dist/game/logic/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/game/logic/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAElD,cAAc,SAAS,CAAC;AACxB,cAAc,eAAe,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/pathfinding/findPath.d.ts b/packages/engine-core/dist/game/logic/pathfinding/findPath.d.ts deleted file mode 100644 index f79bfdb..0000000 --- a/packages/engine-core/dist/game/logic/pathfinding/findPath.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -import type { GameSceneGround, GameSceneInteraction, GameSceneWall } from "../../types"; -export type MovementPoint = { - x: number; - z: number; -}; -type MovementBounds = Pick; -type FindPathOptions = { - start: MovementPoint; - goal: MovementPoint; - bounds: MovementBounds; - walls: GameSceneWall[]; - interactions: GameSceneInteraction[]; - cellSize?: number; - obstaclePadding?: number; - /** - * Clearance added around collision interaction objects (pedestals, props). - * These are typically small standalone cubes that need less clearance than - * long thin walls. Defaults to 0.3 — just over the player's half-width (0.275) - * so the character still fits past them without wasting navigable space. - */ - interactionPadding?: number; - segmentSampleStep?: number; - maxIterations?: number; - /** - * When the goal is unreachable, return a partial route to the open cell - * closest to the goal instead of `null`. Default true — this keeps the - * character moving toward the destination instead of freezing in place. - */ - allowPartialPath?: boolean; -}; -export declare function findPath({ start, goal, bounds, walls, interactions, cellSize, obstaclePadding, interactionPadding, segmentSampleStep, maxIterations, allowPartialPath, }: FindPathOptions): MovementPoint[] | null; -export {}; -//# sourceMappingURL=findPath.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/pathfinding/findPath.d.ts.map b/packages/engine-core/dist/game/logic/pathfinding/findPath.d.ts.map deleted file mode 100644 index 7d07b35..0000000 --- a/packages/engine-core/dist/game/logic/pathfinding/findPath.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"findPath.d.ts","sourceRoot":"","sources":["../../../../src/game/logic/pathfinding/findPath.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,eAAe,EACf,oBAAoB,EACpB,aAAa,EAEd,MAAM,aAAa,CAAC;AAErB,MAAM,MAAM,aAAa,GAAG;IAC1B,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;CACX,CAAC;AAEF,KAAK,cAAc,GAAG,IAAI,CACxB,eAAe,EACf,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,CAClC,CAAC;AA4BF,KAAK,eAAe,GAAG;IACrB,KAAK,EAAE,aAAa,CAAC;IACrB,IAAI,EAAE,aAAa,CAAC;IACpB,MAAM,EAAE,cAAc,CAAC;IACvB,KAAK,EAAE,aAAa,EAAE,CAAC;IACvB,YAAY,EAAE,oBAAoB,EAAE,CAAC;IACrC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB;;;;;OAKG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;;OAIG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B,CAAC;AAwBF,wBAAgB,QAAQ,CAAC,EACvB,KAAK,EACL,IAAI,EACJ,MAAM,EACN,KAAK,EACL,YAAY,EACZ,QAA4B,EAC5B,eAA0C,EAC1C,kBAAgD,EAChD,iBAA+C,EAC/C,aAAa,EACb,gBAAuB,GACxB,EAAE,eAAe,GAAG,aAAa,EAAE,GAAG,IAAI,CAoM1C"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/pathfinding/findPath.js b/packages/engine-core/dist/game/logic/pathfinding/findPath.js deleted file mode 100644 index beda6ae..0000000 --- a/packages/engine-core/dist/game/logic/pathfinding/findPath.js +++ /dev/null @@ -1,363 +0,0 @@ -// Finer than the historical 0.9 so narrow passages between walls are -// represented by at least one open cell and A* can route through them. -const DEFAULT_CELL_SIZE = 0.5; -// Wall clearance: thin walls (halfZ≈0.25) need 0.6 so grid cells near the -// wall face are marked blocked and the player never clips through diagonals. -const DEFAULT_OBSTACLE_PADDING = 0.6; -// Interaction object clearance: small cubes (halfX/Z≈0.95) don't need the -// same clearance as walls. 0.3 keeps the player just clear of the surface -// while leaving narrow corridors navigable. -const DEFAULT_INTERACTION_PADDING = 0.3; -const DEFAULT_SEGMENT_SAMPLE_STEP = 0.25; -const NEIGHBOR_OFFSETS = [ - [-1, -1], - [-1, 0], - [-1, 1], - [0, -1], - [0, 1], - [1, -1], - [1, 0], - [1, 1], -]; -export function findPath({ start, goal, bounds, walls, interactions, cellSize = DEFAULT_CELL_SIZE, obstaclePadding = DEFAULT_OBSTACLE_PADDING, interactionPadding = DEFAULT_INTERACTION_PADDING, segmentSampleStep = DEFAULT_SEGMENT_SAMPLE_STEP, maxIterations, allowPartialPath = true, }) { - const obstacles = [ - ...walls.map((wall) => toObstacle(wall.position[0], wall.position[2], wall.halfSize[0], wall.halfSize[2], wall.rotationY, obstaclePadding, wall.openings)), - ...interactions - .filter((interaction) => interaction.hasCollision) - .map((interaction) => toObstacle(interaction.position[0], interaction.position[2], interaction.halfSize[0], interaction.halfSize[2], interaction.rotationY ?? 0, interactionPadding)), - ]; - if (isSegmentClear(start, goal, bounds, obstacles, segmentSampleStep)) { - return [goal]; - } - const width = Math.max(1, Math.floor((bounds.maxX - bounds.minX) / cellSize) + 1); - const height = Math.max(1, Math.floor((bounds.maxZ - bounds.minZ) / cellSize) + 1); - const cellCount = width * height; - // Generous default: each cell is expanded at most once, so the whole grid - // can be explored. Callers can still cap it explicitly. - const iterationCap = maxIterations ?? cellCount * 4; - const blocked = new Uint8Array(cellCount); - for (let gridZ = 0; gridZ < height; gridZ += 1) { - for (let gridX = 0; gridX < width; gridX += 1) { - const point = gridToPoint(gridX, gridZ, bounds, cellSize); - blocked[gridIndex(gridX, gridZ, width)] = isPointBlocked(point, bounds, obstacles) - ? 1 - : 0; - } - } - const startCell = findNearestOpenCell(pointToGrid(start, bounds, cellSize), width, height, blocked); - const goalCell = findNearestOpenCell(pointToGrid(goal, bounds, cellSize), width, height, blocked); - if (!startCell || !goalCell) { - return null; - } - const startIndex = gridIndex(startCell.x, startCell.z, width); - const goalIndex = gridIndex(goalCell.x, goalCell.z, width); - if (startIndex === goalIndex) { - // Start and goal collapse to the same cell but the direct segment was - // blocked (thin obstacle between them) — just steer toward the goal. - return [goal]; - } - const gScore = new Float64Array(cellCount).fill(Number.POSITIVE_INFINITY); - const cameFrom = new Int32Array(cellCount).fill(-1); - const closed = new Uint8Array(cellCount); - const open = new MinHeap(); - gScore[startIndex] = 0; - open.push(startIndex, heuristic(startCell, goalCell)); - // Track the open cell closest to the goal so we can return a partial route - // when the goal sits in a different connected region. - let bestIndex = startIndex; - let bestHeuristic = heuristic(startCell, goalCell); - let iterations = 0; - while (open.size > 0 && iterations < iterationCap) { - iterations += 1; - const currentIndex = open.pop(); - if (currentIndex < 0 || closed[currentIndex]) { - continue; - } - closed[currentIndex] = 1; - if (currentIndex === goalIndex) { - return buildRoute(cameFrom, currentIndex, width, bounds, cellSize, start, goal, obstacles, segmentSampleStep); - } - const currentCell = indexToGrid(currentIndex, width); - const currentHeuristic = heuristic(currentCell, goalCell); - if (currentHeuristic < bestHeuristic) { - bestHeuristic = currentHeuristic; - bestIndex = currentIndex; - } - for (const [offsetX, offsetZ] of NEIGHBOR_OFFSETS) { - const nextX = currentCell.x + offsetX; - const nextZ = currentCell.z + offsetZ; - if (nextX < 0 || nextX >= width || nextZ < 0 || nextZ >= height) { - continue; - } - const neighborIndex = gridIndex(nextX, nextZ, width); - if (blocked[neighborIndex] || closed[neighborIndex]) { - continue; - } - // Disallow cutting diagonally past a corner: both orthogonal cells must - // be open, otherwise the path would clip the obstacle. - if (offsetX !== 0 && offsetZ !== 0) { - const horizontalIndex = gridIndex(currentCell.x + offsetX, currentCell.z, width); - const verticalIndex = gridIndex(currentCell.x, currentCell.z + offsetZ, width); - if (blocked[horizontalIndex] || blocked[verticalIndex]) { - continue; - } - } - const tentativeGScore = gScore[currentIndex] + Math.hypot(offsetX, offsetZ); - if (tentativeGScore >= gScore[neighborIndex]) { - continue; - } - cameFrom[neighborIndex] = currentIndex; - gScore[neighborIndex] = tentativeGScore; - open.push(neighborIndex, tentativeGScore + heuristic({ x: nextX, z: nextZ }, goalCell)); - } - } - // Goal unreachable. Return a partial route toward the closest reachable cell - // so the character still advances (and a follow-up click can continue). - if (allowPartialPath && bestIndex !== startIndex) { - return buildRoute(cameFrom, bestIndex, width, bounds, cellSize, start, - // The partial route ends at the reachable cell, not the real goal. - gridToPoint(indexToGrid(bestIndex, width).x, indexToGrid(bestIndex, width).z, bounds, cellSize), obstacles, segmentSampleStep); - } - return null; -} -/** - * Reconstructs the grid path to `endIndex`, swaps the snapped endpoints for the - * real world start/goal, and smooths the result via line-of-sight checks. - */ -function buildRoute(cameFrom, endIndex, width, bounds, cellSize, start, goal, obstacles, segmentSampleStep) { - const gridPath = reconstructPath(cameFrom, endIndex, width); - const rawPoints = [ - start, - ...gridPath.map((cell) => gridToPoint(cell.x, cell.z, bounds, cellSize)), - goal, - ]; - return smoothPath(rawPoints, bounds, obstacles, segmentSampleStep); -} -/** - * Array-backed binary min-heap keyed by an external priority. Uses lazy - * deletion: a node may be pushed multiple times with improving priorities, - * and stale pops are skipped by the caller via a `closed` check. - */ -class MinHeap { - constructor() { - this.indices = []; - this.priorities = []; - } - get size() { - return this.indices.length; - } - push(index, priority) { - this.indices.push(index); - this.priorities.push(priority); - this.siftUp(this.indices.length - 1); - } - pop() { - const n = this.indices.length; - if (n === 0) - return -1; - const topIndex = this.indices[0]; - const lastIndex = this.indices.pop(); - const lastPriority = this.priorities.pop(); - if (n > 1) { - this.indices[0] = lastIndex; - this.priorities[0] = lastPriority; - this.siftDown(0); - } - return topIndex; - } - siftUp(i) { - while (i > 0) { - const parent = (i - 1) >> 1; - if (this.priorities[parent] <= this.priorities[i]) - break; - this.swap(i, parent); - i = parent; - } - } - siftDown(i) { - const n = this.indices.length; - for (;;) { - const left = 2 * i + 1; - const right = 2 * i + 2; - let smallest = i; - if (left < n && this.priorities[left] < this.priorities[smallest]) { - smallest = left; - } - if (right < n && this.priorities[right] < this.priorities[smallest]) { - smallest = right; - } - if (smallest === i) - break; - this.swap(i, smallest); - i = smallest; - } - } - swap(a, b) { - const ti = this.indices[a]; - this.indices[a] = this.indices[b]; - this.indices[b] = ti; - const tp = this.priorities[a]; - this.priorities[a] = this.priorities[b]; - this.priorities[b] = tp; - } -} -function toObstacle(x, z, halfX, halfZ, rotationY, padding, openings) { - return { - x, - z, - halfX, - halfZ, - rotationY: rotationY ?? 0, - padding, - openings: openings?.map((o) => ({ - centerX: o.position[0], - centerZ: o.position[2], - halfX: o.halfSize[0], - halfZ: o.halfSize[2], - })), - }; -} -function pointToGrid(point, bounds, cellSize) { - return { - x: Math.round((point.x - bounds.minX) / cellSize), - z: Math.round((point.z - bounds.minZ) / cellSize), - }; -} -function gridToPoint(gridX, gridZ, bounds, cellSize) { - return { - x: bounds.minX + gridX * cellSize, - z: bounds.minZ + gridZ * cellSize, - }; -} -function gridIndex(gridX, gridZ, width) { - return gridZ * width + gridX; -} -function indexToGrid(index, width) { - return { - x: index % width, - z: Math.floor(index / width), - }; -} -function heuristic(a, b) { - return Math.hypot(a.x - b.x, a.z - b.z); -} -function reconstructPath(cameFrom, currentIndex, width) { - const path = [indexToGrid(currentIndex, width)]; - let cursor = currentIndex; - while (cameFrom[cursor] >= 0) { - cursor = cameFrom[cursor]; - path.push(indexToGrid(cursor, width)); - } - path.reverse(); - return path.slice(1, -1); -} -function smoothPath(points, bounds, obstacles, segmentSampleStep) { - if (points.length <= 2) { - return [points[points.length - 1]]; - } - const result = []; - let anchorIndex = 0; - while (anchorIndex < points.length - 1) { - let nextIndex = points.length - 1; - while (nextIndex > anchorIndex + 1) { - if (isSegmentClear(points[anchorIndex], points[nextIndex], bounds, obstacles, segmentSampleStep)) { - break; - } - nextIndex -= 1; - } - result.push(points[nextIndex]); - anchorIndex = nextIndex; - } - return result; -} -function findNearestOpenCell(cell, width, height, blocked) { - const clampedX = clamp(cell.x, 0, width - 1); - const clampedZ = clamp(cell.z, 0, height - 1); - const startIndex = gridIndex(clampedX, clampedZ, width); - if (!blocked[startIndex]) { - return { x: clampedX, z: clampedZ }; - } - const maxRadius = Math.max(width, height); - for (let radius = 1; radius < maxRadius; radius += 1) { - for (let offsetZ = -radius; offsetZ <= radius; offsetZ += 1) { - for (let offsetX = -radius; offsetX <= radius; offsetX += 1) { - if (Math.max(Math.abs(offsetX), Math.abs(offsetZ)) !== radius) { - continue; - } - const nextX = clampedX + offsetX; - const nextZ = clampedZ + offsetZ; - if (nextX < 0 || nextX >= width || nextZ < 0 || nextZ >= height) { - continue; - } - if (!blocked[gridIndex(nextX, nextZ, width)]) { - return { x: nextX, z: nextZ }; - } - } - } - } - return null; -} -function isSegmentClear(start, goal, bounds, obstacles, segmentSampleStep) { - const distance = Math.hypot(goal.x - start.x, goal.z - start.z); - const samples = Math.max(1, Math.ceil(distance / segmentSampleStep)); - for (let index = 0; index <= samples; index += 1) { - const t = index / samples; - const point = { - x: lerp(start.x, goal.x, t), - z: lerp(start.z, goal.z, t), - }; - if (isPointBlocked(point, bounds, obstacles)) { - return false; - } - } - return true; -} -function isPointBlocked(point, bounds, obstacles) { - if (point.x < bounds.minX || - point.x > bounds.maxX || - point.z < bounds.minZ || - point.z > bounds.maxZ) { - return true; - } - return obstacles.some((obstacle) => isPointInsideObstacle(point, obstacle)); -} -function isPointInsideObstacle(point, obstacle) { - const localX = point.x - obstacle.x; - const localZ = point.z - obstacle.z; - const cos = Math.cos(-obstacle.rotationY); - const sin = Math.sin(-obstacle.rotationY); - const rotatedX = localX * cos - localZ * sin; - const rotatedZ = localX * sin + localZ * cos; - // Check if the point is inside the obstacle's solid area (with padding) - const insideWall = Math.abs(rotatedX) <= obstacle.halfX + obstacle.padding && - Math.abs(rotatedZ) <= obstacle.halfZ + obstacle.padding; - if (!insideWall) - return false; - // If the point is inside the wall, check if it is also inside an opening. - // Openings are holes that allow traversal. - // - halfX (horizontal width): subtract padding so the agent fits through - // with clearance (opening must be wide enough). - // - halfZ (wall depth/thickness): do NOT subtract padding — this dimension - // spans the wall's thickness, not the passage width. The opening is always - // set to wall.halfZ + margin, so subtracting padding would make it - // negative for thin walls (halfZ ≈ 0.25–0.30). - if (obstacle.openings && obstacle.openings.length > 0) { - for (const opening of obstacle.openings) { - const openHalfX = opening.halfX - obstacle.padding; - if (openHalfX > 0 && - Math.abs(rotatedX - opening.centerX) <= openHalfX && - Math.abs(rotatedZ - opening.centerZ) <= opening.halfZ) { - // Point is inside an opening → not blocked - return false; - } - } - } - return true; -} -function clamp(value, min, max) { - return Math.min(Math.max(value, min), max); -} -function lerp(start, end, amount) { - return start + (end - start) * amount; -} -//# sourceMappingURL=findPath.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/pathfinding/findPath.js.map b/packages/engine-core/dist/game/logic/pathfinding/findPath.js.map deleted file mode 100644 index 7a93b0f..0000000 --- a/packages/engine-core/dist/game/logic/pathfinding/findPath.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"findPath.js","sourceRoot":"","sources":["../../../../src/game/logic/pathfinding/findPath.ts"],"names":[],"mappings":"AAoEA,qEAAqE;AACrE,uEAAuE;AACvE,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,0EAA0E;AAC1E,6EAA6E;AAC7E,MAAM,wBAAwB,GAAG,GAAG,CAAC;AACrC,0EAA0E;AAC1E,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/logic/rules/audioRules.d.ts b/packages/engine-core/dist/game/logic/rules/audioRules.d.ts deleted file mode 100644 index f805a89..0000000 --- a/packages/engine-core/dist/game/logic/rules/audioRules.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type { GameEvent } from "../../events"; -import type { GameScene, ItemDefinition, GameSceneTransition, SceneMusicConfig } from "../../types"; -export interface AudioDefaultsConfig { - clickSoundUrl?: string; - pickupSoundUrl?: string; - dropSoundUrl?: string; - transitionSoundUrl?: string; - dialogSoundUrl?: string; -} -export interface AudioRulesContext { - defaults: AudioDefaultsConfig; - currentScene?: GameScene; - previousMusic?: SceneMusicConfig; - items: Record; - transitions: Record; -} -/** - * Pure resolver: dado un evento del juego, devuelve los eventos de audio derivados. - * El runtime se encarga de propagarlos al EventBus. - */ -export declare function resolveAudioEvents(event: GameEvent, ctx: AudioRulesContext): GameEvent[]; -/** Helper para el host: SFX de click manual (ej. botón de inventario). */ -export declare function clickSfxEvent(defaults: AudioDefaultsConfig, override?: string): GameEvent | null; -//# sourceMappingURL=audioRules.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/rules/audioRules.d.ts.map b/packages/engine-core/dist/game/logic/rules/audioRules.d.ts.map deleted file mode 100644 index 5f9c730..0000000 --- a/packages/engine-core/dist/game/logic/rules/audioRules.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"audioRules.d.ts","sourceRoot":"","sources":["../../../../src/game/logic/rules/audioRules.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,KAAK,EACV,SAAS,EACT,cAAc,EACd,mBAAmB,EACnB,gBAAgB,EACjB,MAAM,aAAa,CAAC;AAErB,MAAM,WAAW,mBAAmB;IAClC,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,YAAY,CAAC,EAAE,SAAS,CAAC;IACzB,aAAa,CAAC,EAAE,gBAAgB,CAAC;IACjC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IACtC,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAAC;CAClD;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,SAAS,EAChB,GAAG,EAAE,iBAAiB,GACrB,SAAS,EAAE,CAoDb;AAED,0EAA0E;AAC1E,wBAAgB,aAAa,CAC3B,QAAQ,EAAE,mBAAmB,EAC7B,QAAQ,CAAC,EAAE,MAAM,GAChB,SAAS,GAAG,IAAI,CAIlB"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/rules/audioRules.js b/packages/engine-core/dist/game/logic/rules/audioRules.js deleted file mode 100644 index 1493baf..0000000 --- a/packages/engine-core/dist/game/logic/rules/audioRules.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Pure resolver: dado un evento del juego, devuelve los eventos de audio derivados. - * El runtime se encarga de propagarlos al EventBus. - */ -export function resolveAudioEvents(event, ctx) { - switch (event.type) { - case "scene:changed": { - const music = event.scene.music; - const out = []; - if (music) { - // Cambia/inicia música - out.push({ - type: "audio:musicRequested", - trackUrl: music.trackUrl, - fadeMs: music.fadeMs ?? 800, - volume: music.volume, - loop: true, - }); - } - else if (ctx.previousMusic && !ctx.previousMusic.persistAcrossScenes) { - // La escena anterior tenía música no-persistente y la nueva no tiene → parar - out.push({ type: "audio:musicStopped", fadeMs: 600 }); - } - return out; - } - case "item:pickedUp": { - const item = ctx.items[event.itemId]; - const url = item?.pickupSoundUrl ?? ctx.defaults.pickupSoundUrl; - if (!url) - return []; - return [{ type: "audio:sfxRequested", soundUrl: url, category: "sfx" }]; - } - case "item:dropped": { - const item = ctx.items[event.itemId]; - // Prioridad: interacción específica > item > default - const url = item?.dropSoundUrl ?? ctx.defaults.dropSoundUrl; - if (!url) - return []; - return [{ type: "audio:sfxRequested", soundUrl: url, category: "sfx" }]; - } - case "transition:triggered": { - const t = ctx.transitions[event.transitionId]; - const url = t?.triggerSoundUrl ?? ctx.defaults.transitionSoundUrl; - if (!url) - return []; - return [{ type: "audio:sfxRequested", soundUrl: url, category: "sfx" }]; - } - case "dialog:triggered": { - const url = ctx.defaults.dialogSoundUrl; - if (!url) - return []; - return [{ type: "audio:sfxRequested", soundUrl: url, category: "ui" }]; - } - default: - return []; - } -} -/** Helper para el host: SFX de click manual (ej. botón de inventario). */ -export function clickSfxEvent(defaults, override) { - const url = override ?? defaults.clickSoundUrl; - if (!url) - return null; - return { type: "audio:sfxRequested", soundUrl: url, category: "ui" }; -} -//# sourceMappingURL=audioRules.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/rules/audioRules.js.map b/packages/engine-core/dist/game/logic/rules/audioRules.js.map deleted file mode 100644 index 9a3190d..0000000 --- a/packages/engine-core/dist/game/logic/rules/audioRules.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"audioRules.js","sourceRoot":"","sources":["../../../../src/game/logic/rules/audioRules.ts"],"names":[],"mappings":"AAwBA;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CAChC,KAAgB,EAChB,GAAsB;IAEtB,QAAQ,KAAK,CAAC,IAAI,EAAE,CAAC;QACnB,KAAK,eAAe,CAAC,CAAC,CAAC;YACrB,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC;YAChC,MAAM,GAAG,GAAgB,EAAE,CAAC;YAC5B,IAAI,KAAK,EAAE,CAAC;gBACV,uBAAuB;gBACvB,GAAG,CAAC,IAAI,CAAC;oBACP,IAAI,EAAE,sBAAsB;oBAC5B,QAAQ,EAAE,KAAK,CAAC,QAAQ;oBACxB,MAAM,EAAE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AAC,YAAY,CAAC,CAAC;YAC9C,MAAM,GAAG,GAAG,CAAC,EAAE,eAAe,IAAI,GAAG,CAAC,QAAQ,CAAC,kBAAkB,CAAC;YAClE,IAAI,CAAC,GAAG;gBAAE,OAAO,EAAE,CAAC;YACpB,OAAO,CAAC,EAAE,IAAI,EAAE,oBAAoB,EAAE,QAAQ,EAAE,GAAG,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,CAAC;QAC1E,CAAC;QAED,KAAK,kBAAkB,CAAC,CAAC,CAAC;YACxB,MAAM,GAAG,GAAG,GAAG,CAAC,QAAQ,CAAC,cAAc,CAAC;YACxC,IAAI,CAAC,GAAG;gBAAE,OAAO,EAAE,CAAC;YACpB,OAAO,CAAC,EAAE,IAAI,EAAE,oBAAoB,EAAE,QAAQ,EAAE,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC;QACzE,CAAC;QAED;YACE,OAAO,EAAE,CAAC;IACd,CAAC;AACH,CAAC;AAED,0EAA0E;AAC1E,MAAM,UAAU,aAAa,CAC3B,QAA6B,EAC7B,QAAiB;IAEjB,MAAM,GAAG,GAAG,QAAQ,IAAI,QAAQ,CAAC,aAAa,CAAC;IAC/C,IAAI,CAAC,GAAG;QAAE,OAAO,IAAI,CAAC;IACtB,OAAO,EAAE,IAAI,EAAE,oBAAoB,EAAE,QAAQ,EAAE,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;AACvE,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/rules/index.d.ts b/packages/engine-core/dist/game/logic/rules/index.d.ts deleted file mode 100644 index e5c6b8e..0000000 --- a/packages/engine-core/dist/game/logic/rules/index.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from "./inventoryRules"; -export * from "./transitionRules"; -export * from "./audioRules"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/rules/index.d.ts.map b/packages/engine-core/dist/game/logic/rules/index.d.ts.map deleted file mode 100644 index a50e203..0000000 --- a/packages/engine-core/dist/game/logic/rules/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/game/logic/rules/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAC;AACjC,cAAc,mBAAmB,CAAC;AAClC,cAAc,cAAc,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/rules/index.js b/packages/engine-core/dist/game/logic/rules/index.js deleted file mode 100644 index 732d069..0000000 --- a/packages/engine-core/dist/game/logic/rules/index.js +++ /dev/null @@ -1,4 +0,0 @@ -export * from "./inventoryRules"; -export * from "./transitionRules"; -export * from "./audioRules"; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/rules/index.js.map b/packages/engine-core/dist/game/logic/rules/index.js.map deleted file mode 100644 index 2282b8d..0000000 --- a/packages/engine-core/dist/game/logic/rules/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/game/logic/rules/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAC;AACjC,cAAc,mBAAmB,CAAC;AAClC,cAAc,cAAc,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/rules/inventoryRules.d.ts b/packages/engine-core/dist/game/logic/rules/inventoryRules.d.ts deleted file mode 100644 index 83b48c7..0000000 --- a/packages/engine-core/dist/game/logic/rules/inventoryRules.d.ts +++ /dev/null @@ -1,94 +0,0 @@ -import type { GameSceneInteraction, DialogKey, ItemDefinition, ItemInteractionRule, InventoryStackState, InventorySlotsState, PlacedSceneItem } from "../../types"; -export type { ItemDefinition, ItemInteractionRule, InventoryStackState, InventorySlotsState, PlacedSceneItem }; -type DraggedPayloadState = { - stack: { - id: string; - name: string; - spriteUrl: string; - }; - fromSlotIndex: number; -}; -type DropHitDecision = { - kind: "unknown-item"; - message: string; -} | { - kind: "rule-miss"; - dialogKey: DialogKey; -} | { - kind: "place"; - fromSlotIndex: number; - placedItem: PlacedSceneItem; - dialogKey: DialogKey; -} | { - kind: "consume"; - fromSlotIndex: number; - dialogKey: DialogKey; -} | { - kind: "return"; - dialogKey: DialogKey; -}; -type PickupDecision = { - kind: "ignore"; -} | { - kind: "blocked"; - dialogKey: DialogKey; -} | { - kind: "allow"; - placedItemId: string; - stack: { - id: string; - name: string; - spriteUrl: string; - }; - successDialogKey: DialogKey; -}; -export declare function removeOneFromSlot(slots: InventorySlotsState, slotIndex: number): InventorySlotsState; -export declare function addOneToInventory(slots: InventorySlotsState, stack: { - id: string; - name: string; - spriteUrl: string; -}): { - slots: InventorySlotsState; - added: boolean; -}; -type InventoryRuleContext = { - getItemDefinition: (itemId: string) => ItemDefinition | null; - resolveItemRule: (itemId: string, interactionId: string) => ItemInteractionRule | null; -}; -export declare function resolveInventoryDropHitDecision(context: InventoryRuleContext, { interaction, payload, now, }: { - interaction: GameSceneInteraction & { - dialogKeys?: Record; - id?: string; - }; - payload: DraggedPayloadState; - now: number; -}): DropHitDecision; -export declare function resolveInventoryDropMissDialogKey(context: InventoryRuleContext, { payload, interaction, sceneInteractions, }: { - payload: DraggedPayloadState; - interaction?: GameSceneInteraction & { - dialogKeys?: Record; - id?: string; - }; - sceneInteractions: (GameSceneInteraction & { - dialogKeys?: Record; - id?: string; - kind?: string; - })[]; -}): DialogKey; -export declare function resolveInventoryDropOnPlayerMessage(context: InventoryRuleContext, { payload, }: { - payload: DraggedPayloadState; -}): { - kind: "text"; - text: string; -} | { - kind: "dialog-key"; - dialogKey: DialogKey; -}; -export declare function resolvePickupPlacedItemDecision(context: InventoryRuleContext, { placedItem, }: { - placedItem: PlacedSceneItem; -}): PickupDecision; -export declare const inventoryRuleMessages: { - unknownItem: string; - inventoryFull: string; -}; -//# sourceMappingURL=inventoryRules.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/rules/inventoryRules.d.ts.map b/packages/engine-core/dist/game/logic/rules/inventoryRules.d.ts.map deleted file mode 100644 index cfe5097..0000000 --- a/packages/engine-core/dist/game/logic/rules/inventoryRules.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"inventoryRules.d.ts","sourceRoot":"","sources":["../../../../src/game/logic/rules/inventoryRules.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,oBAAoB,EACpB,SAAS,EACT,cAAc,EACd,mBAAmB,EACnB,mBAAmB,EACnB,mBAAmB,EACnB,eAAe,EAChB,MAAM,aAAa,CAAC;AAErB,YAAY,EAAE,cAAc,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,eAAe,EAAE,CAAC;AAE/G,KAAK,mBAAmB,GAAG;IACzB,KAAK,EAAE;QACL,EAAE,EAAE,MAAM,CAAC;QACX,IAAI,EAAE,MAAM,CAAC;QACb,SAAS,EAAE,MAAM,CAAC;KACnB,CAAC;IACF,aAAa,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF,KAAK,eAAe,GAChB;IACE,IAAI,EAAE,cAAc,CAAC;IACrB,OAAO,EAAE,MAAM,CAAC;CACjB,GACD;IACE,IAAI,EAAE,WAAW,CAAC;IAClB,SAAS,EAAE,SAAS,CAAC;CACtB,GACD;IACE,IAAI,EAAE,OAAO,CAAC;IACd,aAAa,EAAE,MAAM,CAAC;IACtB,UAAU,EAAE,eAAe,CAAC;IAC5B,SAAS,EAAE,SAAS,CAAC;CACtB,GACD;IACE,IAAI,EAAE,SAAS,CAAC;IAChB,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,SAAS,CAAC;CACtB,GACD;IACE,IAAI,EAAE,QAAQ,CAAC;IACf,SAAS,EAAE,SAAS,CAAC;CACtB,CAAC;AAEN,KAAK,cAAc,GACf;IACE,IAAI,EAAE,QAAQ,CAAC;CAChB,GACD;IACE,IAAI,EAAE,SAAS,CAAC;IAChB,SAAS,EAAE,SAAS,CAAC;CACtB,GACD;IACE,IAAI,EAAE,O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WAAW,CAAC,EAAE,oBAAoB,GAAG;QAAE,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;QAAC,EAAE,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAC7F,iBAAiB,EAAE,CAAC,oBAAoB,GAAG;QAAE,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;QAAC,EAAE,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,EAAE,CAAC;CACtH,GACA,SAAS,CAUX;AAED,wBAAgB,mCAAmC,CACjD,OAAO,EAAE,oBAAoB,EAC7B,EACE,OAAO,GACR,EAAE;IACD,OAAO,EAAE,mBAAmB,CAAC;CAC9B,GAEC;IACE,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;CACd,GACD;IACE,IAAI,EAAE,YAAY,CAAC;IACnB,SAAS,EAAE,SAAS,CAAC;CACtB,CAoBJ;AAED,wBAAgB,+BAA+B,CAC7C,OAAO,EAAE,oBAAoB,EAC7B,EACE,UAAU,GACX,EAAE;IACD,UAAU,EAAE,eAAe,CAAC;CAC7B,GACA,cAAc,CAyBhB;AAED,eAAO,MAAM,qBAAqB;;;CAGjC,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/rules/inventoryRules.js b/packages/engine-core/dist/game/logic/rules/inventoryRules.js deleted file mode 100644 index c4ecca9..0000000 --- a/packages/engine-core/dist/game/logic/rules/inventoryRules.js +++ /dev/null @@ -1,142 +0,0 @@ -const UNKNOWN_ITEM_MESSAGE = "No conozco este item todavía."; -const DEFAULT_DROP_MISS_DIALOG_KEY = "inventoryDropMiss"; -function getDefaultPickupDialogKey(itemId, type) { - return `item.${itemId}.pickup.${type}`; -} -export function removeOneFromSlot(slots, slotIndex) { - const slot = slots[slotIndex]; - if (!slot) - return slots; - const next = [...slots]; - if (slot.quantity <= 1) { - next[slotIndex] = null; - } - else { - next[slotIndex] = { ...slot, quantity: slot.quantity - 1 }; - } - return next; -} -export function addOneToInventory(slots, stack) { - const existingIndex = slots.findIndex((current) => current?.id === stack.id); - if (existingIndex >= 0) { - const next = [...slots]; - const existing = next[existingIndex]; - if (!existing) - return { slots, added: false }; - next[existingIndex] = { ...existing, quantity: existing.quantity + 1 }; - return { slots: next, added: true }; - } - const emptyIndex = slots.findIndex((current) => current == null); - if (emptyIndex < 0) { - return { slots, added: false }; - } - const next = [...slots]; - next[emptyIndex] = { ...stack, quantity: 1 }; - return { slots: next, added: true }; -} -export function resolveInventoryDropHitDecision(context, { interaction, payload, now, }) { - const itemDefinition = context.getItemDefinition(payload.stack.id); - if (!itemDefinition) { - return { - kind: "unknown-item", - message: UNKNOWN_ITEM_MESSAGE, - }; - } - const interactionId = interaction.id || ""; - const rule = context.resolveItemRule(itemDefinition.id, interactionId); - if (!rule) { - return { - kind: "rule-miss", - dialogKey: interaction.dialogKeys?.miss || DEFAULT_DROP_MISS_DIALOG_KEY, - }; - } - if (rule.outcome === "place") { - return { - kind: "place", - fromSlotIndex: payload.fromSlotIndex, - placedItem: { - id: `${itemDefinition.id}-${interactionId}-${now}`, - itemId: itemDefinition.id, - interactionId, - name: itemDefinition.name, - spriteUrl: itemDefinition.spriteUrl, - worldPosition: [ - interaction.position[0], - interaction.position[1] + interaction.halfSize[1] + 0.175, - interaction.position[2], - ], - canPickup: rule.placeCanPickup ?? false, - hasCollision: rule.placeHasCollision ?? false, - collisionHalfSize: rule.placeCollisionHalfSize, - pickupSuccessDialogKey: rule.pickupSuccessDialogKey, - pickupBlockedDialogKey: rule.pickupBlockedDialogKey, - }, - dialogKey: rule.hitDialogKey || interaction.dialogKeys?.hit || DEFAULT_DROP_MISS_DIALOG_KEY, - }; - } - if (rule.outcome === "consume") { - return { - kind: "consume", - fromSlotIndex: payload.fromSlotIndex, - dialogKey: rule.hitDialogKey || interaction.dialogKeys?.hit || DEFAULT_DROP_MISS_DIALOG_KEY, - }; - } - return { - kind: "return", - dialogKey: rule.hitDialogKey || rule.missDialogKey || interaction.dialogKeys?.miss || DEFAULT_DROP_MISS_DIALOG_KEY, - }; -} -export function resolveInventoryDropMissDialogKey(context, { payload, interaction, sceneInteractions, }) { - const interactionId = interaction?.id; - const itemRule = interactionId ? context.resolveItemRule(payload.stack.id, interactionId) : null; - return (itemRule?.missDialogKey || - interaction?.dialogKeys?.miss || - sceneInteractions.find((currentInteraction) => currentInteraction.kind === "drop-target")?.dialogKeys?.miss || - DEFAULT_DROP_MISS_DIALOG_KEY); -} -export function resolveInventoryDropOnPlayerMessage(context, { payload, }) { - const itemDefinition = context.getItemDefinition(payload.stack.id); - if (!itemDefinition) { - return { - kind: "text", - text: UNKNOWN_ITEM_MESSAGE, - }; - } - if (itemDefinition.descriptionDialogKey) { - return { - kind: "dialog-key", - dialogKey: itemDefinition.descriptionDialogKey, - }; - } - return { - kind: "text", - text: `Es ${itemDefinition.name}.`, - }; -} -export function resolvePickupPlacedItemDecision(context, { placedItem, }) { - const itemDefinition = context.getItemDefinition(placedItem.itemId); - if (!itemDefinition) { - return { kind: "ignore" }; - } - if (!placedItem.canPickup) { - return { - kind: "blocked", - dialogKey: placedItem.pickupBlockedDialogKey || getDefaultPickupDialogKey(placedItem.itemId, "blocked"), - }; - } - return { - kind: "allow", - placedItemId: placedItem.id, - stack: { - id: itemDefinition.id, - name: itemDefinition.name, - spriteUrl: itemDefinition.spriteUrl, - }, - successDialogKey: placedItem.pickupSuccessDialogKey || getDefaultPickupDialogKey(placedItem.itemId, "allowed"), - }; -} -export const inventoryRuleMessages = { - unknownItem: UNKNOWN_ITEM_MESSAGE, - inventoryFull: "Inventario lleno.", -}; -//# sourceMappingURL=inventoryRules.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/rules/inventoryRules.js.map b/packages/engine-core/dist/game/logic/rules/inventoryRules.js.map deleted file mode 100644 index 27917fc..0000000 --- a/packages/engine-core/dist/game/logic/rules/inventoryRules.js.map +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cAAc,GAAG,OAAO,CAAC,iBAAiB,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;IACpE,IAAI,CAAC,cAAc,EAAE,CAAC;QACpB,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;IAC5B,CAAC;IAED,IAAI,CAAC,UAAU,CAAC,SAAS,EAAE,CAAC;QAC1B,OAAO;YACL,IAAI,EAAE,SAAS;YACf,SAAS,EACP,UAAU,CAAC,sBAAsB,IAAI,yBAAyB,CAAC,UAAU,CAAC,MAAM,EAAE,SAAS,CAAC;SAC/F,CAAC;IACJ,CAAC;IAED,OAAO;QACL,IAAI,EAAE,OAAO;QACb,YAAY,EAAE,UAAU,CAAC,EAAE;QAC3B,KAAK,EAAE;YACL,EAAE,EAAE,cAAc,CAAC,EAAE;YACrB,IAAI,EAAE,cAAc,CAAC,IAAI;YACzB,SAAS,EAAE,cAAc,CAAC,SAAS;SACpC;QACD,gBAAgB,EACd,UAAU,CAAC,sBAAsB,IAAI,yBAAyB,CAAC,UAAU,CAAC,MAAM,EAAE,SAAS,CAAC;KAC/F,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,qBAAqB,GAAG;IACnC,WAAW,EAAE,oBAAoB;IACjC,aAAa,EAAE,mBAAmB;CACnC,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/rules/transitionRules.d.ts b/packages/engine-core/dist/game/logic/rules/transitionRules.d.ts deleted file mode 100644 index cf7ee51..0000000 --- a/packages/engine-core/dist/game/logic/rules/transitionRules.d.ts +++ /dev/null @@ -1,40 +0,0 @@ -import type { GameScene, GameVec3, GameSceneTransitionOnCollision, GameSceneTransition, PlacedSceneItem, InventoryStackState } from "../../types"; -import type { GameSceneTransitionOnItemDrop, GameSceneTransitionOnItemInteraction } from "../../types"; -import type { GameEvent } from "../../events/types"; -/** - * Pure resolver: given an item:dropped event and the current scene, - * returns the matching item-drop transition (if any). - * No side effects — caller is responsible for emitting events. - */ -export declare function resolveTransitionFromItemDrop(scene: GameScene, event: Extract): GameSceneTransitionOnItemDrop | null; -/** - * Pure resolver: given an item interaction event and the current scene, - * returns the matching item-interaction transition (if any). - * Used when clicking a placed item to check if it triggers a transition. - */ -export declare function resolveTransitionFromItemInteraction(scene: GameScene, itemId: string, interactionId: string): GameSceneTransitionOnItemInteraction | null; -/** - * Pure resolver: detect if a world-space click intersects a collision transition zone. - * Returns the collision transition if the point [clickX, clickZ] is inside its bounds. - */ -export declare function resolveTransitionFromClickOnCollider(scene: GameScene, clickX: number, clickZ: number): { - transition: GameSceneTransitionOnCollision; - position: GameVec3; -} | null; -/** - * Validates whether a transition can be triggered based on game state. - * - * Rules: - * - collision: always allowed - * - item-drop: allowed if no item required, OR item is NOT still placed in scene - * (if item is placed in scene, user must pick it up first before leaving) - * - item-consume: always allowed (item status is handled via game progression) - * - item-interaction: allowed if required item exists (in inventory or placed in scene) - * - * Key insight: if an item is placed in the scene (not taken), it blocks departure. - * If the item is in inventory OR gone from the scene, departure is allowed. - */ -export declare function canTransitionBeTriggered(transition: GameSceneTransition, inventoryItems: (InventoryStackState | null)[], sceneItems: PlacedSceneItem[]): boolean; -//# sourceMappingURL=transitionRules.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/rules/transitionRules.d.ts.map b/packages/engine-core/dist/game/logic/rules/transitionRules.d.ts.map deleted file mode 100644 index a342a05..0000000 --- a/packages/engine-core/dist/game/logic/rules/transitionRules.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transitionRules.d.ts","sourceRoot":"","sources":["../../../../src/game/logic/rules/transitionRules.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,SAAS,EACT,QAAQ,EACR,8BAA8B,EAC9B,mBAAmB,EACnB,eAAe,EACf,mBAAmB,EACpB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,6BAA6B,EAAE,oCAAoC,EAAE,MAAM,aAAa,CAAC;AACvG,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAEpD;;;;GAIG;AACH,wBAAgB,6BAA6B,CAC3C,KAAK,EAAE,SAAS,EAChB,KAAK,EAAE,OAAO,CAAC,SAAS,EAAE;IAAE,IAAI,EAAE,cAAc,CAAA;CAAE,CAAC,GAClD,6BAA6B,GAAG,IAAI,CAWtC;AAED;;;;GAIG;AACH,wBAAgB,oCAAoC,CAClD,KAAK,EAAE,SAAS,EAChB,MAAM,EAAE,MAAM,EACd,aAAa,EAAE,MAAM,GACpB,oCAAoC,GAAG,IAAI,CAW7C;AAED;;;GAGG;AACH,wBAAgB,oCAAoC,CAClD,KAAK,EAAE,SAAS,EAChB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,GACb;IAAE,UAAU,EAAE,8BAA8B,CAAC;IAAC,QAAQ,EAAE,QAAQ,CAAA;CAAE,GAAG,IAAI,CAgB3E;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,wBAAwB,CACtC,UAAU,EAAE,mBAAmB,EAC/B,cAAc,EAAE,CAAC,mBAAmB,GAAG,IAAI,CAAC,EAAE,EAC9C,UAAU,EAAE,eAAe,EAAE,GAC5B,OAAO,CA6BT"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/rules/transitionRules.js b/packages/engine-core/dist/game/logic/rules/transitionRules.js deleted file mode 100644 index 781915a..0000000 --- a/packages/engine-core/dist/game/logic/rules/transitionRules.js +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Pure resolver: given an item:dropped event and the current scene, - * returns the matching item-drop transition (if any). - * No side effects — caller is responsible for emitting events. - */ -export function resolveTransitionFromItemDrop(scene, event) { - if (!scene.transitions) - return null; - return (scene.transitions.find((t) => t.kind === "item-drop" && - t.id === event.interactionId && - (!t.requiresItemId || t.requiresItemId === event.itemId)) ?? null); -} -/** - * Pure resolver: given an item interaction event and the current scene, - * returns the matching item-interaction transition (if any). - * Used when clicking a placed item to check if it triggers a transition. - */ -export function resolveTransitionFromItemInteraction(scene, itemId, interactionId) { - if (!scene.transitions) - return null; - return (scene.transitions.find((t) => t.kind === "item-interaction" && - t.requiresItemId === itemId && - (!t.requiresInteractionId || t.requiresInteractionId === interactionId)) ?? null); -} -/** - * Pure resolver: detect if a world-space click intersects a collision transition zone. - * Returns the collision transition if the point [clickX, clickZ] is inside its bounds. - */ -export function resolveTransitionFromClickOnCollider(scene, clickX, clickZ) { - if (!scene.transitions) - return null; - const found = scene.transitions.find((t) => t.kind === "collision" && - Math.abs(clickX - t.position[0]) <= t.halfSize[0] && - Math.abs(clickZ - t.position[2]) <= t.halfSize[2]); - if (!found) - return null; - return { - transition: found, - position: found.position, - }; -} -/** - * Validates whether a transition can be triggered based on game state. - * - * Rules: - * - collision: always allowed - * - item-drop: allowed if no item required, OR item is NOT still placed in scene - * (if item is placed in scene, user must pick it up first before leaving) - * - item-consume: always allowed (item status is handled via game progression) - * - item-interaction: allowed if required item exists (in inventory or placed in scene) - * - * Key insight: if an item is placed in the scene (not taken), it blocks departure. - * If the item is in inventory OR gone from the scene, departure is allowed. - */ -export function canTransitionBeTriggered(transition, inventoryItems, sceneItems) { - if (transition.kind === "collision") { - return true; - } - if (transition.kind === "item-drop") { - if (!transition.requiresItemId) - return true; - // Block if the required item is still placed in this scene (not taken) - const itemStillInScene = sceneItems.some((item) => item.itemId === transition.requiresItemId); - return !itemStillInScene; - } - if (transition.kind === "item-consume") { - // Consumption transitions don't block — the item state is managed elsewhere - return true; - } - if (transition.kind === "item-interaction") { - const requiredItemInInventory = inventoryItems.some((stack) => stack?.id === transition.requiresItemId); - const requiredItemInScene = sceneItems.some((item) => item.itemId === transition.requiresItemId); - // Item must be available (in inventory or placed in scene) to interact with it - return requiredItemInInventory || requiredItemInScene; - } - return false; -} -//# sourceMappingURL=transitionRules.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/rules/transitionRules.js.map b/packages/engine-core/dist/game/logic/rules/transitionRules.js.map deleted file mode 100644 index b6dee03..0000000 --- a/packages/engine-core/dist/game/logic/rules/transitionRules.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transitionRules.js","sourceRoot":"","sources":["../../../../src/game/logic/rules/transitionRules.ts"],"names":[],"mappings":"AAWA;;;;GAIG;AACH,MAAM,UAAU,6BAA6B,CAC3C,KAAgB,EAChB,KAAmD;IAEnD,IAAI,CAAC,KAAK,CAAC,WAAW;QAAE,OAAO,IAAI,CAAC;IAEpC,OAAO,CACL,KAAK,CAAC,WAAW,CAAC,IAAI,CACpB,CAAC,CAAC,EAAsC,EAAE,CACxC,CAAC,CAAC,IAAI,KAAK,WAAW;QACtB,CAAC,CAAC,EAAE,KAAK,KAAK,CAAC,aAAa;QAC5B,CAAC,CAAC,CAAC,CAAC,cAAc,IAAI,CAAC,CAAC,cAAc,KAAK,KAAK,CAAC,MAAM,CAAC,CAC3D,IAAI,IAAI,CACV,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,oCAAoC,CAClD,KAAgB,EAChB,MAAc,EACd,aAAqB;IAErB,IAAI,CAAC,KAAK,CAAC,WAAW;QAAE,OAAO,IAAI,CAAC;IAEpC,OAAO,CACL,KAAK,CAAC,WAAW,CAAC,IAAI,CACpB,CAAC,CAAC,EAA6C,EAAE,CAC/C,CAAC,CAAC,IAAI,KAAK,kBAAkB;QAC7B,CAAC,CAAC,cAAc,KAAK,MAAM;QAC3B,CAAC,CAAC,CAAC,CAAC,qBAAqB,IAAI,CAAC,CAAC,qBAAqB,KAAK,aAAa,CAAC,CAC1E,IAAI,IAAI,CACV,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,oCAAoC,CAClD,KAAgB,EAChB,MAAc,EACd,MAAc;IAEd,IAAI,CAAC,KAAK,CAAC,WAAW;QAAE,OAAO,IAAI,CAAC;IAEpC,MAAM,KAAK,GAAG,KAAK,CAAC,WAAW,CAAC,IAAI,CAClC,CAAC,CAAC,EAAuC,EAAE,CACzC,CAAC,CAAC,IAAI,KAAK,WAAW;QACtB,IA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AAI,CACzC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,KAAK,UAAU,CAAC,cAAc,CACpD,CAAC;QACF,+EAA+E;QAC/E,OAAO,uBAAuB,IAAI,mBAAmB,CAAC;IACxD,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/transitions.d.ts b/packages/engine-core/dist/game/logic/transitions.d.ts deleted file mode 100644 index 7bfff04..0000000 --- a/packages/engine-core/dist/game/logic/transitions.d.ts +++ /dev/null @@ -1,56 +0,0 @@ -import type { GameVec3, DialogKey, GameSceneTransitionOnCollision, GameSceneTransitionOnItemDrop, GameSceneTransitionOnItemConsume, GameSceneTransitionOnItemInteraction } from "../types"; -export declare function sceneTransitionOnCollision(opts: { - id: string; - targetSceneId: string; - position: GameVec3; - halfSize: GameVec3; - rotationY?: number; - spawnPosition?: GameVec3; - targetPosition?: GameVec3; - preTransitionDialogKey?: DialogKey; - postTransitionDialogKey?: DialogKey; -}): GameSceneTransitionOnCollision; -export declare function sceneTransitionOnItemDrop(opts: { - id: string; - targetSceneId: string; - position: GameVec3; - halfSize: GameVec3; - rotationY?: number; - spawnPosition?: GameVec3; - targetPosition?: GameVec3; - requiresItemId?: string; - consumeItem?: boolean; - hintDialogKeys?: { - empty?: DialogKey; - occupied?: DialogKey; - }; - preTransitionDialogKey?: DialogKey; - postTransitionDialogKey?: DialogKey; -}): GameSceneTransitionOnItemDrop; -export declare function sceneTransitionOnItemConsume(opts: { - id: string; - targetSceneId: string; - position: GameVec3; - halfSize: GameVec3; - rotationY?: number; - spawnPosition?: GameVec3; - targetPosition?: GameVec3; - requiresItemId: string; - preConsumptionDialogKey?: DialogKey; - preTransitionDialogKey?: DialogKey; - postTransitionDialogKey?: DialogKey; -}): GameSceneTransitionOnItemConsume; -export declare function sceneTransitionOnItemInteraction(opts: { - id: string; - targetSceneId: string; - position: GameVec3; - halfSize: GameVec3; - rotationY?: number; - spawnPosition?: GameVec3; - targetPosition?: GameVec3; - requiresItemId: string; - requiresInteractionId?: string; - preTransitionDialogKey?: DialogKey; - postTransitionDialogKey?: DialogKey; -}): GameSceneTransitionOnItemInteraction; -//# sourceMappingURL=transitions.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/transitions.d.ts.map b/packages/engine-core/dist/game/logic/transitions.d.ts.map deleted file mode 100644 index f7bdb0b..0000000 --- a/packages/engine-core/dist/game/logic/transitions.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transitions.d.ts","sourceRoot":"","sources":["../../../src/game/logic/transitions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,QAAQ,EACR,SAAS,EACT,8BAA8B,EAC9B,6BAA6B,EAC7B,gCAAgC,EAChC,oCAAoC,EACrC,MAAM,UAAU,CAAC;AAElB,wBAAgB,0BAA0B,CAAC,IAAI,EAAE;IAC/C,EAAE,EAAE,MAAM,CAAC;IACX,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,QAAQ,CAAC;IACnB,QAAQ,EAAE,QAAQ,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,QAAQ,CAAC;IACzB,cAAc,CAAC,EAAE,QAAQ,CAAC;IAC1B,sBAAsB,CAAC,EAAE,SAAS,CAAC;IACnC,uBAAuB,CAAC,EAAE,SAAS,CAAC;CACrC,GAAG,8BAA8B,CAEjC;AAED,wBAAgB,yBAAyB,CAAC,IAAI,EAAE;IAC9C,EAAE,EAAE,MAAM,CAAC;IACX,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,QAAQ,CAAC;IACnB,QAAQ,EAAE,QAAQ,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,QAAQ,CAAC;IACzB,cAAc,CAAC,EAAE,QAAQ,CAAC;IAC1B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,cAAc,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,SAAS,CAAC;QAAC,QAAQ,CAAC,EAAE,SAAS,CAAA;KAAE,CAAC;IAC7D,sBAAsB,CAAC,EAAE,SAAS,CAAC;IACnC,uBAAuB,CAAC,EAAE,SAAS,CAAC;CACrC,GAAG,6BAA6B,CAEhC;AAED,wBAAgB,4BAA4B,CAAC,IAAI,EAAE;IACjD,EAAE,EAAE,MAAM,CAAC;IACX,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,QAAQ,CAAC;IACnB,QAAQ,EAAE,QAAQ,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,QAAQ,CAAC;IACzB,cAAc,CAAC,EAAE,QAAQ,CAAC;IAC1B,cAAc,EAAE,MAAM,CAAC;IACvB,uBAAuB,CAAC,EAAE,SAAS,CAAC;IACpC,sBAAsB,CAAC,EAAE,SAAS,CAAC;IACnC,uBAAuB,CAAC,EAAE,SAAS,CAAC;CACrC,GAAG,gCAAgC,CAEnC;AAED,wBAAgB,gCAAgC,CAAC,IAAI,EAAE;IACrD,EAAE,EAAE,MAAM,CAAC;IACX,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,QAAQ,CAAC;IACnB,QAAQ,EAAE,QAAQ,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,QAAQ,CAAC;IACzB,cAAc,CAAC,EAAE,QAAQ,CAAC;IAC1B,cAAc,EAAE,MAAM,CAAC;IACvB,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,sBAAsB,CAAC,EAAE,SAAS,CAAC;IACnC,uBAAuB,CAAC,EAAE,SAAS,CAAC;CACrC,GAAG,oCAAoC,CAEvC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/transitions.js b/packages/engine-core/dist/game/logic/transitions.js deleted file mode 100644 index abc93bf..0000000 --- a/packages/engine-core/dist/game/logic/transitions.js +++ /dev/null @@ -1,13 +0,0 @@ -export function sceneTransitionOnCollision(opts) { - return { kind: "collision", ...opts }; -} -export function sceneTransitionOnItemDrop(opts) { - return { kind: "item-drop", ...opts }; -} -export function sceneTransitionOnItemConsume(opts) { - return { kind: "item-consume", ...opts }; -} -export function sceneTransitionOnItemInteraction(opts) { - return { kind: "item-interaction", ...opts }; -} -//# sourceMappingURL=transitions.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/logic/transitions.js.map b/packages/engine-core/dist/game/logic/transitions.js.map deleted file mode 100644 index 155424a..0000000 --- a/packages/engine-core/dist/game/logic/transitions.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transitions.js","sourceRoot":"","sources":["../../../src/game/logic/transitions.ts"],"names":[],"mappings":"AASA,MAAM,UAAU,0BAA0B,CAAC,IAU1C;IACC,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,GAAG,IAAI,EAAE,CAAC;AACxC,CAAC;AAED,MAAM,UAAU,yBAAyB,CAAC,IAazC;IACC,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,GAAG,IAAI,EAAE,CAAC;AACxC,CAAC;AAED,MAAM,UAAU,4BAA4B,CAAC,IAY5C;IACC,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,GAAG,IAAI,EAAE,CAAC;AAC3C,CAAC;AAED,MAAM,UAAU,gCAAgC,CAAC,IAYhD;IACC,OAAO,EAAE,IAAI,EAAE,kBAAkB,EAAE,GAAG,IAAI,EAAE,CAAC;AAC/C,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/audioSettingsStore.d.ts b/packages/engine-core/dist/game/state/audioSettingsStore.d.ts deleted file mode 100644 index 5294a7d..0000000 --- a/packages/engine-core/dist/game/state/audioSettingsStore.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { type AudioSettings, type SoundCategory } from "../types"; -type Listener = (settings: AudioSettings) => void; -type MuteTarget = "master" | SoundCategory; -interface MinimalStorage { - getItem(key: string): string | null; - setItem(key: string, value: string): void; -} -export declare const AUDIO_SETTINGS_STORAGE_KEY = "audio-settings"; -export interface AudioSettingsStore { - getState(): AudioSettings; - subscribe(listener: Listener): () => void; - setMasterMuted(muted: boolean): void; - setMusicMuted(muted: boolean): void; - setSfxMuted(muted: boolean): void; - setMasterVolume(volume: number): void; - setMusicVolume(volume: number): void; - setSfxVolume(volume: number): void; - setCurrentMusicTrackUrl(url: string | undefined): void; - setMuted(target: MuteTarget, muted: boolean): void; - setVolume(target: MuteTarget, volume: number): void; - getEffectiveVolume(category: SoundCategory): number; - hydrate(settings: Partial): void; - reset(): void; -} -export declare function createAudioSettingsStore(initial?: AudioSettings): AudioSettingsStore; -export declare function loadAudioSettings(storage: MinimalStorage): Partial | null; -export declare function saveAudioSettings(storage: MinimalStorage, settings: AudioSettings): void; -export {}; -//# sourceMappingURL=audioSettingsStore.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/audioSettingsStore.d.ts.map b/packages/engine-core/dist/game/state/audioSettingsStore.d.ts.map deleted file mode 100644 index 65b390b..0000000 --- a/packages/engine-core/dist/game/state/audioSettingsStore.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"audioSettingsStore.d.ts","sourceRoot":"","sources":["../../../src/game/state/audioSettingsStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,aAAa,EAClB,KAAK,aAAa,EACnB,MAAM,UAAU,CAAC;AAElB,KAAK,QAAQ,GAAG,CAAC,QAAQ,EAAE,aAAa,KAAK,IAAI,CAAC;AAClD,KAAK,UAAU,GAAG,QAAQ,GAAG,aAAa,CAAC;AAE3C,UAAU,cAAc;IACtB,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;IACpC,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3C;AAED,eAAO,MAAM,0BAA0B,mBAAmB,CAAC;AAI3D,MAAM,WAAW,kBAAkB;IACjC,QAAQ,IAAI,aAAa,CAAC;IAC1B,SAAS,CAAC,QAAQ,EAAE,QAAQ,GAAG,MAAM,IAAI,CAAC;IAC1C,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAAC;IACrC,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAAC;IACpC,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAAC;IAClC,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtC,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACrC,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACnC,uBAAuB,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAAC;IACvD,QAAQ,CAAC,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,CAAC;IACnD,SAAS,CAAC,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACpD,kBAAkB,CAAC,QAAQ,EAAE,aAAa,GAAG,MAAM,CAAC;IACpD,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,aAAa,CAAC,GAAG,IAAI,CAAC;IAChD,KAAK,IAAI,IAAI,CAAC;CACf;AAED,wBAAgB,wBAAwB,CACtC,OAAO,GAAE,aAAsC,GAC9C,kBAAkB,CAgEpB;AAID,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,cAAc,GACtB,OAAO,CAAC,aAAa,CAAC,GAAG,IAAI,CAS/B;AAED,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,cAAc,EACvB,QAAQ,EAAE,aAAa,GACtB,IAAI,CAEN"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/audioSettingsStore.js b/packages/engine-core/dist/game/state/audioSettingsStore.js deleted file mode 100644 index 9bcaed2..0000000 --- a/packages/engine-core/dist/game/state/audioSettingsStore.js +++ /dev/null @@ -1,88 +0,0 @@ -import { DEFAULT_AUDIO_SETTINGS, } from "../types"; -export const AUDIO_SETTINGS_STORAGE_KEY = "audio-settings"; -const clamp01 = (n) => Math.max(0, Math.min(1, n)); -export function createAudioSettingsStore(initial = DEFAULT_AUDIO_SETTINGS) { - let state = { ...initial }; - const listeners = new Set(); - const emit = () => listeners.forEach((l) => l(state)); - const update = (patch) => { - state = { ...state, ...patch }; - emit(); - }; - const isCategoryMuted = (category) => { - if (state.masterMuted) - return true; - if (category === "music" && state.musicMuted) - return true; - if ((category === "sfx" || category === "ui" || category === "ambient") && - state.sfxMuted) - return true; - return false; - }; - return { - getState: () => state, - subscribe(listener) { - listeners.add(listener); - return () => listeners.delete(listener); - }, - setMasterMuted: (m) => update({ masterMuted: m }), - setMusicMuted: (m) => update({ musicMuted: m }), - setSfxMuted: (m) => update({ sfxMuted: m }), - setMasterVolume: (v) => update({ masterVolume: clamp01(v) }), - setMusicVolume: (v) => update({ musicVolume: clamp01(v) }), - setSfxVolume: (v) => update({ sfxVolume: clamp01(v) }), - setCurrentMusicTrackUrl: (url) => update({ currentMusicTrackUrl: url }), - setMuted(target, muted) { - if (target === "master") - update({ masterMuted: muted }); - else if (target === "music") - update({ musicMuted: muted }); - else - update({ sfxMuted: muted }); - }, - setVolume(target, volume) { - const v = clamp01(volume); - if (target === "master") - update({ masterVolume: v }); - else if (target === "music") - update({ musicVolume: v }); - else - update({ sfxVolume: v }); - }, - getEffectiveVolume(category) { - if (isCategoryMuted(category)) - return 0; - const base = category === "music" ? state.musicVolume : state.sfxVolume; - return clamp01(base * state.masterVolume); - }, - hydrate(patch) { - const merged = { ...state, ...patch }; - merged.masterVolume = clamp01(merged.masterVolume); - merged.musicVolume = clamp01(merged.musicVolume); - merged.sfxVolume = clamp01(merged.sfxVolume); - state = merged; - emit(); - }, - reset() { - state = { ...DEFAULT_AUDIO_SETTINGS }; - emit(); - }, - }; -} -// --- Persistencia (helpers puros) --- -export function loadAudioSettings(storage) { - const raw = storage.getItem(AUDIO_SETTINGS_STORAGE_KEY); - if (!raw) - return null; - try { - const parsed = JSON.parse(raw); - return parsed; - } - catch { - return null; - } -} -export function saveAudioSettings(storage, settings) { - storage.setItem(AUDIO_SETTINGS_STORAGE_KEY, JSON.stringify(settings)); -} -//# sourceMappingURL=audioSettingsStore.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/audioSettingsStore.js.map b/packages/engine-core/dist/game/state/audioSettingsStore.js.map deleted file mode 100644 index ec00dad..0000000 --- a/packages/engine-core/dist/game/state/audioSettingsStore.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"audioSettingsStore.js","sourceRoot":"","sources":["../../../src/game/state/audioSettingsStore.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,GAGvB,MAAM,UAAU,CAAC;AAUlB,MAAM,CAAC,MAAM,0BAA0B,GAAG,gBAAgB,CAAC;AAE3D,MAAM,OAAO,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AAmB3D,MAAM,UAAU,wBAAwB,CACtC,UAAyB,sBAAsB;IAE/C,IAAI,KAAK,GAAkB,EAAE,GAAG,OAAO,EAAE,CAAC;IAC1C,MAAM,SAAS,GAAG,IAAI,GAAG,EAAY,CAAC;IACtC,MAAM,IAAI,GAAG,GAAG,EAAE,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;IAEtD,MAAM,MAAM,GAAG,CAAC,KAA6B,EAAE,EAAE;QAC/C,KAAK,GAAG,EAAE,GAAG,KAAK,EAAE,GAAG,KAAK,EAAE,CAAC;QAC/B,IAAI,EAAE,CAAC;IACT,CAAC,CAAC;IAEF,MAAM,eAAe,GAAG,CAA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AAC;YACjD,MAAM,CAAC,SAAS,GAAG,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;YAC7C,KAAK,GAAG,MAAM,CAAC;YACf,IAAI,EAAE,CAAC;QACT,CAAC;QACD,KAAK;YACH,KAAK,GAAG,EAAE,GAAG,sBAAsB,EAAE,CAAC;YACtC,IAAI,EAAE,CAAC;QACT,CAAC;KACF,CAAC;AACJ,CAAC;AAED,uCAAuC;AAEvC,MAAM,UAAU,iBAAiB,CAC/B,OAAuB;IAEvB,MAAM,GAAG,GAAG,OAAO,CAAC,OAAO,CAAC,0BAA0B,CAAC,CAAC;IACxD,IAAI,CAAC,GAAG;QAAE,OAAO,IAAI,CAAC;IACtB,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAA2B,CAAC;QACzD,OAAO,MAAM,CAAC;IAChB,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,MAAM,UAAU,iBAAiB,CAC/B,OAAuB,EACvB,QAAuB;IAEvB,OAAO,CAAC,OAAO,CAAC,0BAA0B,EAAE,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC;AACxE,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/i18nStore.d.ts b/packages/engine-core/dist/game/state/i18nStore.d.ts deleted file mode 100644 index f81e047..0000000 --- a/packages/engine-core/dist/game/state/i18nStore.d.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { type I18nConfig, type I18nState, type Locale } from "../types"; -import type { GameEvent } from "../events/types"; -import type { I18nPort } from "../../ports/i18n"; -type Listener = (state: I18nState) => void; -type StoreEmitter = (event: GameEvent) => void; -/** - * Inject the runtime's event emitter. Mirrors `setSceneStoreEmitter`. When - * unset (the default), the store runs in zero-event mode. - */ -export declare function setI18nStoreEmitter(emitter: StoreEmitter | null): void; -export interface I18nStore { - getState(): I18nState; - subscribe(listener: Listener): () => void; - setLocale(locale: Locale): void; - setAvailableLocales(locales: Locale[]): void; - setFallbackLocale(locale: Locale): void; - hydrate(state: Partial): void; - reset(): void; - /** - * Connect the store to an {@link I18nPort}: hydrate `locale` from - * `port.detectLocale()` once, then persist every subsequent change via - * `port.persistLocale`. Returns an unsubscribe function. - */ - bindPort(port: I18nPort): () => void; -} -export declare function createI18nStore(config?: I18nConfig): I18nStore; -export declare function getI18nStore(): I18nStore; -export declare function resetI18nStore(config?: I18nConfig): void; -/** Non-React helper: subscribe to the singleton store. */ -export declare function subscribeI18n(listener: Listener): () => void; -export {}; -//# sourceMappingURL=i18nStore.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/i18nStore.d.ts.map b/packages/engine-core/dist/game/state/i18nStore.d.ts.map deleted file mode 100644 index 5ff35bc..0000000 --- a/packages/engine-core/dist/game/state/i18nStore.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"i18nStore.d.ts","sourceRoot":"","sources":["../../../src/game/state/i18nStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,UAAU,EACf,KAAK,SAAS,EACd,KAAK,MAAM,EACZ,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAEjD,KAAK,QAAQ,GAAG,CAAC,KAAK,EAAE,SAAS,KAAK,IAAI,CAAC;AAC3C,KAAK,YAAY,GAAG,CAAC,KAAK,EAAE,SAAS,KAAK,IAAI,CAAC;AAI/C;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,GAAG,IAAI,CAEtE;AAMD,MAAM,WAAW,SAAS;IACxB,QAAQ,IAAI,SAAS,CAAC;IACtB,SAAS,CAAC,QAAQ,EAAE,QAAQ,GAAG,MAAM,IAAI,CAAC;IAC1C,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,mBAAmB,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IAC7C,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACxC,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,SAAS,CAAC,GAAG,IAAI,CAAC;IACzC,KAAK,IAAI,IAAI,CAAC;IACd;;;;OAIG;IACH,QAAQ,CAAC,IAAI,EAAE,QAAQ,GAAG,MAAM,IAAI,CAAC;CACtC;AAUD,wBAAgB,eAAe,CAC7B,MAAM,GAAE,UAAgC,GACvC,SAAS,CAmEX;AAQD,wBAAgB,YAAY,IAAI,SAAS,CAGxC;AAED,wBAAgB,cAAc,CAAC,MAAM,GAAE,UAAgC,GAAG,IAAI,CAE7E;AAED,0DAA0D;AAC1D,wBAAgB,aAAa,CAAC,QAAQ,EAAE,QAAQ,GAAG,MAAM,IAAI,CAE5D"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/i18nStore.js b/packages/engine-core/dist/game/state/i18nStore.js deleted file mode 100644 index f410f5e..0000000 --- a/packages/engine-core/dist/game/state/i18nStore.js +++ /dev/null @@ -1,102 +0,0 @@ -import { DEFAULT_I18N_CONFIG, } from "../types"; -let _emitter = null; -/** - * Inject the runtime's event emitter. Mirrors `setSceneStoreEmitter`. When - * unset (the default), the store runs in zero-event mode. - */ -export function setI18nStoreEmitter(emitter) { - _emitter = emitter; -} -function emitGameEvent(event) { - if (_emitter) - _emitter(event); -} -const SHOULD_WARN = (() => { - try { - return typeof process !== "undefined" && process.env?.NODE_ENV !== "production"; - } - catch { - return false; - } -})(); -export function createI18nStore(config = DEFAULT_I18N_CONFIG) { - let state = { - locale: config.defaultLocale, - availableLocales: [...config.availableLocales], - fallbackLocale: config.fallbackLocale, - }; - const listeners = new Set(); - const emit = () => listeners.forEach((l) => l(state)); - const update = (patch) => { - state = { ...state, ...patch }; - emit(); - }; - const resolveSafeLocale = (next) => { - if (state.availableLocales.includes(next)) - return next; - const safe = state.availableLocales[0] ?? state.fallbackLocale; - if (SHOULD_WARN && typeof console !== "undefined") { - console.warn(`[i18nStore] locale "${next}" not in availableLocales [${state.availableLocales.join(",")}]. Falling back to "${safe}".`); - } - return safe; - }; - const store = { - getState: () => state, - subscribe(listener) { - listeners.add(listener); - return () => { - listeners.delete(listener); - }; - }, - setLocale(locale) { - const safe = resolveSafeLocale(locale); - if (safe === state.locale) - return; - const previous = state.locale; - update({ locale: safe }); - emitGameEvent({ type: "i18n:localeChanged", locale: safe, previous }); - }, - setAvailableLocales(locales) { - update({ availableLocales: [...locales] }); - }, - setFallbackLocale(locale) { - update({ fallbackLocale: locale }); - }, - hydrate(patch) { - state = { ...state, ...patch }; - emit(); - }, - reset() { - state = { - locale: config.defaultLocale, - availableLocales: [...config.availableLocales], - fallbackLocale: config.fallbackLocale, - }; - emit(); - }, - bindPort(port) { - const detected = port.detectLocale(); - if (detected) - store.setLocale(detected); - return store.subscribe((next) => port.persistLocale(next.locale)); - }, - }; - return store; -} -// --------------------------------------------------------------------------- -// Singleton convenience -// --------------------------------------------------------------------------- -let _singleton = null; -export function getI18nStore() { - if (!_singleton) - _singleton = createI18nStore(DEFAULT_I18N_CONFIG); - return _singleton; -} -export function resetI18nStore(config = DEFAULT_I18N_CONFIG) { - _singleton = createI18nStore(config); -} -/** Non-React helper: subscribe to the singleton store. */ -export function subscribeI18n(listener) { - return getI18nStore().subscribe(listener); -} -//# sourceMappingURL=i18nStore.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/i18nStore.js.map b/packages/engine-core/dist/game/state/i18nStore.js.map deleted file mode 100644 index 1ff4ac2..0000000 --- a/packages/engine-core/dist/game/state/i18nStore.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"i18nStore.js","sourceRoot":"","sources":["../../../src/game/state/i18nStore.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,GAIpB,MAAM,UAAU,CAAC;AAOlB,IAAI,QAAQ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AAG;gBACN,MAAM,EAAE,MAAM,CAAC,aAAa;gBAC5B,gBAAgB,EAAE,CAAC,GAAG,MAAM,CAAC,gBAAgB,CAAC;gBAC9C,cAAc,EAAE,MAAM,CAAC,cAAc;aACtC,CAAC;YACF,IAAI,EAAE,CAAC;QACT,CAAC;QACD,QAAQ,CAAC,IAAI;YACX,MAAM,QAAQ,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;YACrC,IAAI,QAAQ;gBAAE,KAAK,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;YACxC,OAAO,KAAK,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;QACpE,CAAC;KACF,CAAC;IAEF,OAAO,KAAK,CAAC;AACf,CAAC;AAED,8EAA8E;AAC9E,wBAAwB;AACxB,8EAA8E;AAE9E,IAAI,UAAU,GAAqB,IAAI,CAAC;AAExC,MAAM,UAAU,YAAY;IAC1B,IAAI,CAAC,UAAU;QAAE,UAAU,GAAG,eAAe,CAAC,mBAAmB,CAAC,CAAC;IACnE,OAAO,UAAU,CAAC;AACpB,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,SAAqB,mBAAmB;IACrE,UAAU,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC;AACvC,CAAC;AAED,0DAA0D;AAC1D,MAAM,UAAU,aAAa,CAAC,QAAkB;IAC9C,OAAO,YAAY,EAAE,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;AAC5C,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/index.d.ts b/packages/engine-core/dist/game/state/index.d.ts deleted file mode 100644 index caab0c8..0000000 --- a/packages/engine-core/dist/game/state/index.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -export { useSceneStore, getSceneState, subscribeSceneState, setSceneStoreEmitter, setSceneStoreLogger, } from "./sceneStore"; -export type { InventorySlotsStore } from "./inventorySlotsStore"; -export { createInventorySlotsStore } from "./inventorySlotsStore"; -export type { PlacedItemsStore } from "./placedItemsStore"; -export { createPlacedItemsStore } from "./placedItemsStore"; -export { AUDIO_SETTINGS_STORAGE_KEY, createAudioSettingsStore, loadAudioSettings, saveAudioSettings, type AudioSettingsStore, } from "./audioSettingsStore"; -export { createI18nStore, getI18nStore, resetI18nStore, subscribeI18n, setI18nStoreEmitter, type I18nStore, } from "./i18nStore"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/index.d.ts.map b/packages/engine-core/dist/game/state/index.d.ts.map deleted file mode 100644 index 1e07006..0000000 --- a/packages/engine-core/dist/game/state/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/game/state/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,EACb,aAAa,EACb,mBAAmB,EACnB,oBAAoB,EACpB,mBAAmB,GACpB,MAAM,cAAc,CAAC;AACtB,YAAY,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AACjE,OAAO,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AAClE,YAAY,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EACL,0BAA0B,EAC1B,wBAAwB,EACxB,iBAAiB,EACjB,iBAAiB,EACjB,KAAK,kBAAkB,GACxB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,eAAe,EACf,YAAY,EACZ,cAAc,EACd,aAAa,EACb,mBAAmB,EACnB,KAAK,SAAS,GACf,MAAM,aAAa,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/index.js b/packages/engine-core/dist/game/state/index.js deleted file mode 100644 index 1703567..0000000 --- a/packages/engine-core/dist/game/state/index.js +++ /dev/null @@ -1,6 +0,0 @@ -export { useSceneStore, getSceneState, subscribeSceneState, setSceneStoreEmitter, setSceneStoreLogger, } from "./sceneStore"; -export { createInventorySlotsStore } from "./inventorySlotsStore"; -export { createPlacedItemsStore } from "./placedItemsStore"; -export { AUDIO_SETTINGS_STORAGE_KEY, createAudioSettingsStore, loadAudioSettings, saveAudioSettings, } from "./audioSettingsStore"; -export { createI18nStore, getI18nStore, resetI18nStore, subscribeI18n, setI18nStoreEmitter, } from "./i18nStore"; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/index.js.map b/packages/engine-core/dist/game/state/index.js.map deleted file mode 100644 index d53a850..0000000 --- a/packages/engine-core/dist/game/state/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/game/state/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,EACb,aAAa,EACb,mBAAmB,EACnB,oBAAoB,EACpB,mBAAmB,GACpB,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AAElE,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EACL,0BAA0B,EAC1B,wBAAwB,EACxB,iBAAiB,EACjB,iBAAiB,GAElB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,eAAe,EACf,YAAY,EACZ,cAAc,EACd,aAAa,EACb,mBAAmB,GAEpB,MAAM,aAAa,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/inventorySlotsStore.d.ts b/packages/engine-core/dist/game/state/inventorySlotsStore.d.ts deleted file mode 100644 index 3bfeacb..0000000 --- a/packages/engine-core/dist/game/state/inventorySlotsStore.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { InventorySlotsState } from "../types"; -export type InventorySlotsStore = { - getSlots: () => InventorySlotsState; - setSlots: (slots: InventorySlotsState) => void; - reset: () => void; -}; -/** - * Create an agnostic inventory slots store. - * Tracks the current inventory state with add/remove operations. - */ -export declare function createInventorySlotsStore(): InventorySlotsStore; -//# sourceMappingURL=inventorySlotsStore.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/inventorySlotsStore.d.ts.map b/packages/engine-core/dist/game/state/inventorySlotsStore.d.ts.map deleted file mode 100644 index 4dea057..0000000 --- a/packages/engine-core/dist/game/state/inventorySlotsStore.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"inventorySlotsStore.d.ts","sourceRoot":"","sources":["../../../src/game/state/inventorySlotsStore.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAuB,MAAM,UAAU,CAAC;AAEzE,MAAM,MAAM,mBAAmB,GAAG;IAChC,QAAQ,EAAE,MAAM,mBAAmB,CAAC;IACpC,QAAQ,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,IAAI,CAAC;IAC/C,KAAK,EAAE,MAAM,IAAI,CAAC;CACnB,CAAC;AAEF;;;GAGG;AACH,wBAAgB,yBAAyB,IAAI,mBAAmB,CAY/D"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/inventorySlotsStore.js b/packages/engine-core/dist/game/state/inventorySlotsStore.js deleted file mode 100644 index 37a5391..0000000 --- a/packages/engine-core/dist/game/state/inventorySlotsStore.js +++ /dev/null @@ -1,17 +0,0 @@ -/** - * Create an agnostic inventory slots store. - * Tracks the current inventory state with add/remove operations. - */ -export function createInventorySlotsStore() { - let slots = []; - return { - getSlots: () => [...slots], - setSlots: (newSlots) => { - slots = [...newSlots]; - }, - reset: () => { - slots = []; - }, - }; -} -//# sourceMappingURL=inventorySlotsStore.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/inventorySlotsStore.js.map b/packages/engine-core/dist/game/state/inventorySlotsStore.js.map deleted file mode 100644 index 03a7e0e..0000000 --- a/packages/engine-core/dist/game/state/inventorySlotsStore.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"inventorySlotsStore.js","sourceRoot":"","sources":["../../../src/game/state/inventorySlotsStore.ts"],"names":[],"mappings":"AAQA;;;GAGG;AACH,MAAM,UAAU,yBAAyB;IACvC,IAAI,KAAK,GAAwB,EAAE,CAAC;IAEpC,OAAO;QACL,QAAQ,EAAE,GAAG,EAAE,CAAC,CAAC,GAAG,KAAK,CAAC;QAC1B,QAAQ,EAAE,CAAC,QAA6B,EAAE,EAAE;YAC1C,KAAK,GAAG,CAAC,GAAG,QAAQ,CAAC,CAAC;QACxB,CAAC;QACD,KAAK,EAAE,GAAG,EAAE;YACV,KAAK,GAAG,EAAE,CAAC;QACb,CAAC;KACF,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/placedItemsStore.d.ts b/packages/engine-core/dist/game/state/placedItemsStore.d.ts deleted file mode 100644 index cfc908f..0000000 --- a/packages/engine-core/dist/game/state/placedItemsStore.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { PlacedSceneItem } from "../types"; -export type PlacedItemsStore = { - getItems: () => PlacedSceneItem[]; - setItems: (items: PlacedSceneItem[]) => void; - addItem: (item: PlacedSceneItem) => void; - removeItem: (itemId: string) => void; - reset: () => void; -}; -/** - * Create an agnostic placed items store. - * Tracks items placed in scenes with granular add/remove operations. - */ -export declare function createPlacedItemsStore(): PlacedItemsStore; -//# sourceMappingURL=placedItemsStore.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/placedItemsStore.d.ts.map b/packages/engine-core/dist/game/state/placedItemsStore.d.ts.map deleted file mode 100644 index e09b97c..0000000 --- a/packages/engine-core/dist/game/state/placedItemsStore.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"placedItemsStore.d.ts","sourceRoot":"","sources":["../../../src/game/state/placedItemsStore.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAEhD,MAAM,MAAM,gBAAgB,GAAG;IAC7B,QAAQ,EAAE,MAAM,eAAe,EAAE,CAAC;IAClC,QAAQ,EAAE,CAAC,KAAK,EAAE,eAAe,EAAE,KAAK,IAAI,CAAC;IAC7C,OAAO,EAAE,CAAC,IAAI,EAAE,eAAe,KAAK,IAAI,CAAC;IACzC,UAAU,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;IACrC,KAAK,EAAE,MAAM,IAAI,CAAC;CACnB,CAAC;AAEF;;;GAGG;AACH,wBAAgB,sBAAsB,IAAI,gBAAgB,CAkBzD"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/placedItemsStore.js b/packages/engine-core/dist/game/state/placedItemsStore.js deleted file mode 100644 index e78cc3d..0000000 --- a/packages/engine-core/dist/game/state/placedItemsStore.js +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Create an agnostic placed items store. - * Tracks items placed in scenes with granular add/remove operations. - */ -export function createPlacedItemsStore() { - let items = []; - return { - getItems: () => [...items], - setItems: (newItems) => { - items = [...newItems]; - }, - addItem: (item) => { - items = [...items, item]; - }, - removeItem: (itemId) => { - items = items.filter((item) => item.id !== itemId); - }, - reset: () => { - items = []; - }, - }; -} -//# sourceMappingURL=placedItemsStore.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/placedItemsStore.js.map b/packages/engine-core/dist/game/state/placedItemsStore.js.map deleted file mode 100644 index 1284302..0000000 --- a/packages/engine-core/dist/game/state/placedItemsStore.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"placedItemsStore.js","sourceRoot":"","sources":["../../../src/game/state/placedItemsStore.ts"],"names":[],"mappings":"AAUA;;;GAGG;AACH,MAAM,UAAU,sBAAsB;IACpC,IAAI,KAAK,GAAsB,EAAE,CAAC;IAElC,OAAO;QACL,QAAQ,EAAE,GAAG,EAAE,CAAC,CAAC,GAAG,KAAK,CAAC;QAC1B,QAAQ,EAAE,CAAC,QAA2B,EAAE,EAAE;YACxC,KAAK,GAAG,CAAC,GAAG,QAAQ,CAAC,CAAC;QACxB,CAAC;QACD,OAAO,EAAE,CAAC,IAAqB,EAAE,EAAE;YACjC,KAAK,GAAG,CAAC,GAAG,KAAK,EAAE,IAAI,CAAC,CAAC;QAC3B,CAAC;QACD,UAAU,EAAE,CAAC,MAAc,EAAE,EAAE;YAC7B,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE,KAAK,MAAM,CAAC,CAAC;QACrD,CAAC;QACD,KAAK,EAAE,GAAG,EAAE;YACV,KAAK,GAAG,EAAE,CAAC;QACb,CAAC;KACF,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/sceneStore.d.ts b/packages/engine-core/dist/game/state/sceneStore.d.ts deleted file mode 100644 index 33746e7..0000000 --- a/packages/engine-core/dist/game/state/sceneStore.d.ts +++ /dev/null @@ -1,55 +0,0 @@ -import type { GameScene, GameSceneWall, GameSceneInteractionFull, GameVec3, TransitionState, PlayerWalkingState } from "../types"; -import type { GameEvent } from "../events/types"; -type StoreEmitter = (event: GameEvent) => void; -/** - * Inyecta el emisor de eventos del runtime. Llamado por `createGameRuntime` - * al inicializar el bus. Si no se llama, el store funciona en zero-event mode. - */ -export declare function setSceneStoreEmitter(emitter: StoreEmitter | null): void; -type SceneStoreLogger = (event: string, payload: Record) => void; -/** - * Inyecta un logger custom para debug de scene-store (p.ej. window.__gameTrace en browser). - * Si no se llama, el store usa console.info en desarrollo. - * Pasar null para deshabilitar el logger completamente. - */ -export declare function setSceneStoreLogger(logger: SceneStoreLogger | null): void; -/** - * sceneStore – estado runtime de la escena activa. - * - * Invariantes de ownership: - * - Propietario de: sceneId, scene (datos runtime), playerPosition, respawnSignal. - * - NO gestiona estado de editor (selección de muros, etc). Ver sceneEditorStore. - * - appendWall / removeWall / updateWall son helpers de mutación que el editor - * puede invocar vía sceneEditorStore sin acoplar stores en sentido contrario. - */ -type SceneStore = { - sceneId: string; - scene: GameScene; - playerPosition: GameVec3; - respawnSignal: number; - transitionStates: Record; - playerWalkingState: PlayerWalkingState | null; - setScene: (id: string, scene: GameScene, spawnPosition?: GameVec3) => void; - updateInteraction: (id: string, updater: (interaction: GameSceneInteractionFull) => GameSceneInteractionFull) => void; - resetInteractionsFromSceneConfig: () => void; - setPlayerPosition: (position: GameVec3) => void; - requestRespawn: () => void; - setTransitionAvailable: (id: string, available: boolean) => void; - setTransitionItemOccupying: (id: string, itemId: string | undefined) => void; - setPlayerWalkingState: (state: PlayerWalkingState | null) => void; - updateWalkProgress: (progress: number) => void; - updateGround: (updater: (ground: GameScene["ground"]) => GameScene["ground"]) => void; - appendWall: (wall: GameSceneWall) => void; - removeWall: (index: number) => void; - updateWall: (index: number, updater: (wall: GameSceneWall) => GameSceneWall) => void; - updateTransition: (id: string, updater: (transition: import("../types").GameSceneTransition) => import("../types").GameSceneTransition) => void; - addTransition: (transition: import("../types").GameSceneTransition) => void; - removeTransition: (id: string) => void; -}; -export declare const useSceneStore: import("zustand").UseBoundStore>; -/** Read state without React (for use from other renderers or tests) */ -export declare function getSceneState(): SceneStore; -/** Subscribe to state changes without React */ -export declare function subscribeSceneState(listener: (state: ReturnType) => void): () => void; -export {}; -//# sourceMappingURL=sceneStore.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/sceneStore.d.ts.map b/packages/engine-core/dist/game/state/sceneStore.d.ts.map deleted file mode 100644 index 1355a9a..0000000 --- a/packages/engine-core/dist/game/state/sceneStore.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"sceneStore.d.ts","sourceRoot":"","sources":["../../../src/game/state/sceneStore.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,SAAS,EACT,aAAa,EACb,wBAAwB,EACxB,QAAQ,EACR,eAAe,EACf,kBAAkB,EACnB,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAMjD,KAAK,YAAY,GAAG,CAAC,KAAK,EAAE,SAAS,KAAK,IAAI,CAAC;AAI/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,kBAAkB,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;IAG/C,YAAY,EAAE,CAAC,OAAO,EAAE,CAAC,MAAM,EAAE,SAAS,CAAC,QAAQ,CAAC,KAAK,SAAS,CAAC,QAAQ,CAAC,KAAK,IAAI,CAAC;IACtF,UAAU,EAAE,CAAC,IAAI,EAAE,aAAa,KAAK,IAAI,CAAC;IAC1C,UAAU,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IACpC,UAAU,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,IAAI,EAAE,aAAa,KAAK,aAAa,KAAK,IAAI,CAAC;IACrF,gBAAgB,EAAE,CAChB,EAAE,EAAE,MAAM,EACV,OAAO,EAAE,CAAC,UAAU,EAAE,OAAO,UAAU,EAAE,mBAAmB,KAAK,OAAO,UAAU,EAAE,mBAAmB,KACpG,IAAI,CAAC;IACV,aAAa,EAAE,CAAC,UAAU,EAAE,OAAO,UAAU,EAAE,mBAAmB,KAAK,IAAI,CAAC;IAC5E,gBAAgB,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,CAAC;CACxC,CAAC;AAEF,eAAO,MAAM,aAAa,yEAuJvB,CAAC;AAEJ,uEAAuE;AACvE,wBAAgB,aAAa,eAE5B;AAED,+CAA+C;AAC/C,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,CAAC,KAAK,EAAE,UAAU,CAAC,OAAO,aAAa,CAAC,QAAQ,CAAC,KAAK,IAAI,cAGrE"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/sceneStore.js b/packages/engine-core/dist/game/state/sceneStore.js deleted file mode 100644 index baa6a9f..0000000 --- a/packages/engine-core/dist/game/state/sceneStore.js +++ /dev/null @@ -1,224 +0,0 @@ -import { create } from "zustand"; -let _emitter = null; -/** - * Inyecta el emisor de eventos del runtime. Llamado por `createGameRuntime` - * al inicializar el bus. Si no se llama, el store funciona en zero-event mode. - */ -export function setSceneStoreEmitter(emitter) { - _emitter = emitter; -} -function emit(event) { - if (_emitter) - _emitter(event); -} -const SHOULD_LOG_STATE_TRANSITIONS = process.env.NODE_ENV !== "production"; -let _logger = null; -/** - * Inyecta un logger custom para debug de scene-store (p.ej. window.__gameTrace en browser). - * Si no se llama, el store usa console.info en desarrollo. - * Pasar null para deshabilitar el logger completamente. - */ -export function setSceneStoreLogger(logger) { - _logger = logger; -} -function logSceneStore(event, payload) { - if (!SHOULD_LOG_STATE_TRANSITIONS) - return; - if (_logger) { - _logger(event, payload); - } - else { - console.info(`[scene-store] ${event}`, payload); - } -} -function cloneWall(wall) { - return { - position: [...wall.position], - rotationY: wall.rotationY, - halfSize: [...wall.halfSize], - openings: wall.openings - ? wall.openings.map((opening) => ({ - id: opening.id, - position: [...opening.position], - halfSize: [...opening.halfSize], - })) - : undefined, - textureUrl: wall.textureUrl, - texturePosition: wall.texturePosition - ? [...wall.texturePosition] - : undefined, - }; -} -function cloneInteraction(interaction) { - return { - ...interaction, - position: [...interaction.position], - halfSize: [...interaction.halfSize], - acceptsItemIds: interaction.acceptsItemIds - ? [...interaction.acceptsItemIds] - : undefined, - dialogKeys: { ...interaction.dialogKeys }, - }; -} -function cloneScene(scene) { - return { - ...scene, - playerSpawn: [...scene.playerSpawn], - ground: { ...scene.ground }, - walls: scene.walls.map(cloneWall), - interactions: scene.interactions.map(cloneInteraction), - transitions: scene.transitions - ? scene.transitions.map((t) => ({ ...t, position: [...t.position], halfSize: [...t.halfSize] })) - : undefined, - }; -} -export const useSceneStore = create((set, get) => ({ - sceneId: "", - scene: { - id: "", - label: "", - background: "", - playerSpawn: [0, 0, 0], - ground: { minX: 0, maxX: 0, minZ: 0, maxZ: 0, y: 0 }, - walls: [], - interactions: [], - }, - playerPosition: [0, 0, 0], - respawnSignal: 0, - transitionStates: {}, - playerWalkingState: null, - setScene: (id, scene, spawnPosition) => { - const clonedScene = cloneScene(scene); - const finalSpawnPosition = spawnPosition ?? clonedScene.playerSpawn; - logSceneStore("set-scene", { - fromSceneId: get().sceneId, - toSceneId: id, - spawn: finalSpawnPosition, - }); - // Preserve playerWalkingState during scene changes so walk animation continues - const prevWalkingState = get().playerWalkingState; - set({ - sceneId: id, - scene: clonedScene, - playerPosition: [...finalSpawnPosition], - playerWalkingState: prevWalkingState, - }); - emit({ type: "scene:changed", sceneId: id, scene: clonedScene }); - }, - updateGround: (updater) => set((state) => ({ - scene: { - ...state.scene, - ground: updater({ ...state.scene.ground }), - }, - })), - appendWall: (wall) => set((state) => ({ - scene: { - ...state.scene, - walls: [...state.scene.walls, cloneWall(wall)], - }, - })), - removeWall: (index) => set((state) => ({ - scene: { - ...state.scene, - walls: state.scene.walls.filter((_, i) => i !== index), - }, - })), - updateWall: (index, updater) => set((state) => ({ - scene: { - ...state.scene, - walls: state.scene.walls.map((wall, i) => i !== index ? wall : updater(cloneWall(wall))), - }, - })), - updateInteraction: (id, updater) => set((state) => ({ - scene: { - ...state.scene, - interactions: state.scene.interactions.map((interaction) => { - if (interaction.id !== id) - return interaction; - return updater(cloneInteraction(interaction)); - }), - }, - })), - resetInteractionsFromSceneConfig: () => set((state) => { - logSceneStore("reset-interactions", { - sceneId: state.sceneId, - interactionCount: state.scene.interactions.length, - }); - return { - scene: { - ...state.scene, - interactions: state.scene.interactions.map(cloneInteraction), - }, - }; - }), - setPlayerPosition: (position) => set({ playerPosition: position }), - setTransitionAvailable: (id, available) => set((state) => ({ - transitionStates: { - ...state.transitionStates, - [id]: { ...state.transitionStates[id], isAvailable: available }, - }, - })), - setTransitionItemOccupying: (id, itemId) => set((state) => ({ - transitionStates: { - ...state.transitionStates, - [id]: { ...state.transitionStates[id], itemIdOccupying: itemId }, - }, - })), - requestRespawn: () => { - const state = get(); - const nextRespawnSignal = state.respawnSignal + 1; - logSceneStore("request-respawn", { - sceneId: state.sceneId, - previousRespawnSignal: state.respawnSignal, - nextRespawnSignal, - currentPlayerPosition: state.playerPosition, - }); - set({ respawnSignal: nextRespawnSignal }); - emit({ type: "scene:respawnRequested", sceneId: state.sceneId }); - }, - updateTransition: (id, updater) => set((state) => ({ - scene: { - ...state.scene, - transitions: (state.scene.transitions || []).map((transition) => { - if (transition.id !== id) - return transition; - return updater(transition); - }), - }, - })), - addTransition: (transition) => set((state) => ({ - scene: { - ...state.scene, - transitions: [...(state.scene.transitions || []), transition], - }, - })), - removeTransition: (id) => set((state) => ({ - scene: { - ...state.scene, - transitions: (state.scene.transitions || []).filter((t) => t.id !== id), - }, - })), - setPlayerWalkingState: (state) => { - // console.log(`[sceneStore] setPlayerWalkingState:`, state?.isActive ? `active, pathPoints=${state.pathPoints.length}` : "cleared"); - set({ playerWalkingState: state }); - }, - updateWalkProgress: (progress) => set((state) => { - if (!state.playerWalkingState) - return state; - return { - playerWalkingState: { - ...state.playerWalkingState, - progress, - }, - }; - }), -})); -/** Read state without React (for use from other renderers or tests) */ -export function getSceneState() { - return useSceneStore.getState(); -} -/** Subscribe to state changes without React */ -export function subscribeSceneState(listener) { - return useSceneStore.subscribe(listener); -} -//# sourceMappingURL=sceneStore.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/state/sceneStore.js.map b/packages/engine-core/dist/game/state/sceneStore.js.map deleted file mode 100644 index 1467c10..0000000 --- a/packages/engine-core/dist/game/state/sceneStore.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"sceneStore.js","sourceRoot":"","sources":["../../../src/game/state/sceneStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAiBjC,IAAI,QAAQ,GAAwB,IAAI,CAAC;AAEzC;;;GAGG;AACH,MAAM,UAAU,oBAAoB,CAAC,OAA4B;IAC/D,QAAQ,GAAG,OAAO,CAAC;AACrB,CAAC;AAED,SAAS,IAAI,CAAC,KAAgB;IAC5B,IAAI,QAAQ;QAAE,QAAQ,CAAC,KAAK,CAAC,CAAC;AAChC,CAAC;AAED,MAAM,4BAA4B,GAAG,OAAO,CAAC,GAAG,CA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CAAC;QACd,KAAK,EAAE;YACL,GAAG,KAAK,CAAC,KAAK;YACd,WAAW,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,WAAW,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC;SACxE;KACF,CAAC,CAAC;IACL,qBAAqB,EAAE,CAAC,KAAK,EAAE,EAAE;QAC/B,qIAAqI;QACrI,GAAG,CAAC,EAAE,kBAAkB,EAAE,KAAK,EAAE,CAAC,CAAC;IACrC,CAAC;IACD,kBAAkB,EAAE,CAAC,QAAQ,EAAE,EAAE,CAC/B,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE;QACZ,IAAI,CAAC,KAAK,CAAC,kBAAkB;YAAE,OAAO,KAAK,CAAC;QAC5C,OAAO;YACL,kBAAkB,EAAE;gBAClB,GAAG,KAAK,CAAC,kBAAkB;gBAC3B,QAAQ;aACT;SACF,CAAC;IACJ,CAAC,CAAC;CACL,CAAC,CAAC,CAAC;AAEJ,uEAAuE;AACvE,MAAM,UAAU,aAAa;IAC3B,OAAO,aAAa,CAAC,QAAQ,EAAE,CAAC;AAClC,CAAC;AAED,+CAA+C;AAC/C,MAAM,UAAU,mBAAmB,CACjC,QAAoE;IAEpE,OAAO,aAAa,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;AAC3C,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/types/index.d.ts b/packages/engine-core/dist/game/types/index.d.ts deleted file mode 100644 index 13753e6..0000000 --- a/packages/engine-core/dist/game/types/index.d.ts +++ /dev/null @@ -1,271 +0,0 @@ -export type GameVec3 = [x: number, y: number, z: number]; -export type GameVec2 = [x: number, y: number]; -export interface GameSceneGround { - minX: number; - maxX: number; - minZ: number; - maxZ: number; - y: number; -} -/** - * An opening (door/window) in a wall. - * Position and halfSize are relative to the wall's local coordinate space - * (wall center = origin, axes aligned with wall before rotation). - */ -export interface GameSceneWallOpening { - /** Unique identifier for this opening. */ - id: string; - /** Center of the opening relative to the wall's local center. */ - position: GameVec3; - /** Half-dimensions of the opening (width/2, height/2, depth/2). */ - halfSize: GameVec3; -} -export interface GameSceneWall { - position: GameVec3; - halfSize: GameVec3; - rotationY: number; - /** - * Array of openings (doors/windows) in this wall. - * Empty array or undefined = solid wall (backward compatible). - */ - openings?: GameSceneWallOpening[]; - /** - * URL to the wall's texture image. - * Should point to /public/assets/wall-textures/* or similar. - * Undefined = no texture (backward compatible). - */ - textureUrl?: string; - /** - * World-space offset applied to the texture plane position. - * Used for fine-grained alignment with the background image. - * Defaults to [0, 0, 0]. - */ - texturePosition?: GameVec3; -} -export interface GameSceneInteraction { - position: GameVec3; - halfSize: GameVec3; - rotationY?: number; - hasCollision?: boolean; -} -export type PlacedSceneItem = { - id: string; - itemId: string; - interactionId: string; - name: string; - spriteUrl: string; - worldPosition: GameVec3; - canPickup: boolean; - hasCollision?: boolean; - collisionHalfSize?: GameVec3; - pickupSuccessDialogKey?: string; - pickupBlockedDialogKey?: string; - sceneId?: string; -}; -export type ItemInteractionRule = { - outcome: "place" | "consume" | "return"; - hitDialogKey?: DialogKey; - missDialogKey?: DialogKey; - placeCanPickup?: boolean; - placeHasCollision?: boolean; - placeCollisionHalfSize?: GameVec3; - pickupSuccessDialogKey?: DialogKey; - pickupBlockedDialogKey?: DialogKey; - /** Override del SFX por defecto al hacer drop en esta interacción concreta. */ - dropSoundUrl?: string; -}; -export type ItemDefinition = { - id: string; - name: string; - spriteUrl: string; - descriptionDialogKey?: string; - interactionRules: Record; - defaultRule: ItemInteractionRule; - /** Override del SFX por defecto al recoger este ítem. */ - pickupSoundUrl?: string; - /** Override del SFX por defecto al soltar este ítem. */ - dropSoundUrl?: string; -}; -export type InventoryStackState = { - id: string; - name: string; - spriteUrl: string; - quantity: number; -}; -export type InventorySlotsState = Array; -export type DialogKey = string; -export interface GameSceneInteractionDialogKeys { - hit: DialogKey; - miss: DialogKey; -} -export interface GameSceneInteractionHintDialogKeys { - empty: DialogKey; - occupied: DialogKey; -} -export interface GameSceneInteractionFull extends GameSceneInteraction { - id: string; - kind: "drop-target"; - hasCollision?: boolean; - acceptsItemIds?: string[]; - dialogKeys: GameSceneInteractionDialogKeys; - hintDialogKeys?: GameSceneInteractionHintDialogKeys; - label: string; -} -export interface BaseSceneTransition { - id: string; - targetSceneId: string; - position: GameVec3; - halfSize: GameVec3; - rotationY?: number; - /** Optional spawn position in target scene. If omitted, uses scene's playerSpawn. */ - spawnPosition?: GameVec3; - /** Optional walk target position after spawning. If omitted, no walk animation. */ - targetPosition?: GameVec3; - preTransitionDialogKey?: DialogKey; - postTransitionDialogKey?: DialogKey; - /** Override del SFX por defecto al disparar esta transición. */ - triggerSoundUrl?: string; -} -export interface GameSceneTransitionOnCollision extends BaseSceneTransition { - kind: "collision"; -} -export interface GameSceneTransitionOnItemDrop extends BaseSceneTransition { - kind: "item-drop"; - requiresItemId?: string; - consumeItem?: boolean; - hintDialogKeys?: { - empty?: DialogKey; - occupied?: DialogKey; - }; -} -export interface GameSceneTransitionOnItemConsume extends BaseSceneTransition { - kind: "item-consume"; - requiresItemId: string; - preConsumptionDialogKey?: DialogKey; -} -export interface GameSceneTransitionOnItemInteraction extends BaseSceneTransition { - kind: "item-interaction"; - requiresItemId: string; - requiresInteractionId?: string; -} -export type GameSceneTransition = GameSceneTransitionOnCollision | GameSceneTransitionOnItemDrop | GameSceneTransitionOnItemConsume | GameSceneTransitionOnItemInteraction; -export interface TransitionState { - /** Source scene recorded when the transition was last triggered. */ - lastVisitedSceneId?: string; - /** For item-drop transitions: item currently occupying the zone. */ - itemIdOccupying?: string; - /** Whether this transition can be triggered. Default true. */ - isAvailable: boolean; -} -export interface PlayerWalkingState { - /** Target position to walk towards. */ - targetPosition: GameVec3; - /** Path points to follow (calculated via pathfinding). */ - pathPoints: GameVec3[]; - /** Walk progress: 0 = start, 1 = complete. */ - progress: number; - /** Whether walk is currently active. */ - isActive: boolean; -} -export interface GameScene { - id: string; - label: string; - background: string; - playerSpawn: GameVec3; - ground: GameSceneGround; - walls: GameSceneWall[]; - interactions: GameSceneInteractionFull[]; - /** Declarative scene exit/transition zones. */ - transitions?: GameSceneTransition[]; - /** Music optional associated to this scene. */ - music?: SceneMusicConfig; -} -export type WallToolMode = "manual" | "points"; -export type DebugEditorMode = "walls" | "ground" | "items" | "targets"; -export type SoundCategory = "music" | "sfx" | "ui" | "ambient"; -export interface SoundDefinition { - id: string; - url: string; - /** 0..1, default 1. */ - volume?: number; - /** Default false para SFX, true implícito para música. */ - loop?: boolean; - category: SoundCategory; -} -export interface SceneMusicConfig { - trackUrl: string; - /** Si true, no se reinicia al cambiar de escena hasta entrar a otra con música distinta. */ - persistAcrossScenes?: boolean; - /** 0..1, default 1. */ - volume?: number; - /** Crossfade en ms al entrar/salir. Default 800. */ - fadeMs?: number; -} -export interface AudioSettings { - masterMuted: boolean; - musicMuted: boolean; - sfxMuted: boolean; - /** 0..1 cada uno. */ - masterVolume: number; - musicVolume: number; - sfxVolume: number; - /** Track actualmente sonando (para restaurar tras unmute / reload). */ - currentMusicTrackUrl?: string; -} -export declare const DEFAULT_AUDIO_SETTINGS: AudioSettings; -export type RuntimeMoveEvent = { - type: "onMove"; - position: GameVec3; - action: "idle" | "north" | "south" | "west" | "east"; -}; -export type RuntimeCollideEvent = { - type: "onCollide"; - reason: "boundary" | "stuck" | "pathblocked"; - position: GameVec3; -}; -export type RuntimeDropEvent = { - type: "onDrop"; - outcome: "place" | "consume" | "return" | "rule-miss" | "unknown-item" | "on-player" | "pickup-blocked" | "pickup-success" | "item-interact"; - itemId: string; - interactionId?: string; -}; -export type RuntimeDialogEvent = { - type: "onDialog"; - text: string; - dialogKey?: string; - source: "boundary" | "inventory" | "debug"; -}; -export type RuntimeEvent = RuntimeMoveEvent | RuntimeCollideEvent | RuntimeDropEvent | RuntimeDialogEvent; -export type RuntimeEventHandler = (event: RuntimeEvent) => void; -/** - * BCP-47 language tag (e.g. "es", "en", "es-MX", "pt-BR"). - * Intentionally a plain string — not a union — so consumers can register - * any locale without modifying engine types. - */ -export type Locale = string; -/** A single dialog entry: one or more phrases. If >1, the translator picks one at random. */ -export interface DialogEntry { - phrases: string[]; -} -/** Map of dialog key → entry, for a single locale. */ -export type DialogDictionary = Record; -/** Map of locale → dictionary. Used by `registerDictionaries`. */ -export type LocaleDictionaries = Record; -/** Engine-wide i18n configuration. */ -export interface I18nConfig { - /** Locale used at boot when no detection / persistence applies. */ - defaultLocale: Locale; - /** Locale consulted when a key is missing in the active locale. */ - fallbackLocale: Locale; - /** Whitelist of locales the user may switch to. */ - availableLocales: Locale[]; -} -/** Reactive state held by `i18nStore`. */ -export interface I18nState { - locale: Locale; - availableLocales: Locale[]; - fallbackLocale: Locale; -} -/** Conservative defaults. Hosts should override via `createI18nStore` / `resetI18nStore`. */ -export declare const DEFAULT_I18N_CONFIG: I18nConfig; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/types/index.d.ts.map b/packages/engine-core/dist/game/types/index.d.ts.map deleted file mode 100644 index 412ed09..0000000 --- a/packages/engine-core/dist/game/types/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/game/types/index.ts"],"names":[],"mappings":"AAIA,MAAM,MAAM,QAAQ,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC;AACzD,MAAM,MAAM,QAAQ,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC;AAG9C,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,CAAC,EAAE,MAAM,CAAC;CACX;AAED;;;;GAIG;AACH,MAAM,WAAW,oBAAoB;I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EAAE,UAAU,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,UAAU,GAAG,WAAW,GAAG,OAAO,CAAC;CAC5C,CAAC;AAEF,MAAM,MAAM,YAAY,GACpB,gBAAgB,GAChB,mBAAmB,GACnB,gBAAgB,GAChB,kBAAkB,CAAC;AAEvB,MAAM,MAAM,mBAAmB,GAAG,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,CAAC;AAMhE;;;;GAIG;AACH,MAAM,MAAM,MAAM,GAAG,MAAM,CAAC;AAE5B,6FAA6F;AAC7F,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,MAAM,EAAE,CAAC;CACnB;AAED,sDAAsD;AACtD,MAAM,MAAM,gBAAgB,GAAG,MAAM,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;AAE9D,kEAAkE;AAClE,MAAM,MAAM,kBAAkB,GAAG,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;AAElE,sCAAsC;AACtC,MAAM,WAAW,UAAU;IACzB,mEAAmE;IACnE,aAAa,EAAE,MAAM,CAAC;IACtB,mEAAmE;IACnE,cAAc,EAAE,MAAM,CAAC;IACvB,mDAAmD;IACnD,gBAAgB,EAAE,MAAM,EAAE,CAAC;CAC5B;AAED,0CAA0C;AAC1C,MAAM,WAAW,SAAS;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,gBAAgB,EAAE,MAAM,EAAE,CAAC;IAC3B,cAAc,EAAE,MAAM,CAAC;CACxB;AAED,6FAA6F;AAC7F,eAAO,MAAM,mBAAmB,EAAE,UAIjC,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/types/index.js b/packages/engine-core/dist/game/types/index.js deleted file mode 100644 index ad8be89..0000000 --- a/packages/engine-core/dist/game/types/index.js +++ /dev/null @@ -1,17 +0,0 @@ -// Core types for point-and-click game engine -// Framework-agnostic definitions -export const DEFAULT_AUDIO_SETTINGS = { - masterMuted: false, - musicMuted: false, - sfxMuted: false, - masterVolume: 0.8, - musicVolume: 0.6, - sfxVolume: 0.8, -}; -/** Conservative defaults. Hosts should override via `createI18nStore` / `resetI18nStore`. */ -export const DEFAULT_I18N_CONFIG = { - defaultLocale: "en", - fallbackLocale: "en", - availableLocales: ["en"], -}; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/types/index.js.map b/packages/engine-core/dist/game/types/index.js.map deleted file mode 100644 index 2b6c014..0000000 --- a/packages/engine-core/dist/game/types/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/game/types/index.ts"],"names":[],"mappings":"AAAA,6CAA6C;AAC7C,iCAAiC;AAwQjC,MAAM,CAAC,MAAM,sBAAsB,GAAkB;IACnD,WAAW,EAAE,KAAK;IAClB,UAAU,EAAE,KAAK;IACjB,QAAQ,EAAE,KAAK;IACf,YAAY,EAAE,GAAG;IACjB,WAAW,EAAE,GAAG;IAChB,SAAS,EAAE,GAAG;CACf,CAAC;AAqFF,6FAA6F;AAC7F,MAAM,CAAC,MAAM,mBAAmB,GAAe;IAC7C,aAAa,EAAE,IAAI;IACnB,cAAc,EAAE,IAAI;IACpB,gBAAgB,EAAE,CAAC,IAAI,CAAC;CACzB,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/utils/validation.d.ts b/packages/engine-core/dist/game/utils/validation.d.ts deleted file mode 100644 index 18eac69..0000000 --- a/packages/engine-core/dist/game/utils/validation.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type { GameScene, GameVec3 } from "../types"; -/** - * Validates that an entry position is within valid scene bounds and not blocked by walls. - * Used to verify entry positions in scene transitions are accessible. - */ -export declare function validateEntryPosition(position: GameVec3, scene: GameScene): { - valid: boolean; - reason?: string; -}; -/** - * Validates that a walk path from source to destination is reachable. - * Uses A* pathfinding to check connectivity. - * Returns the calculated path if reachable. - */ -export declare function validateWalkPath(from: GameVec3, to: GameVec3, scene: GameScene): { - reachable: boolean; - path?: GameVec3[]; -}; -//# sourceMappingURL=validation.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/utils/validation.d.ts.map b/packages/engine-core/dist/game/utils/validation.d.ts.map deleted file mode 100644 index 0d90068..0000000 --- a/packages/engine-core/dist/game/utils/validation.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../../../src/game/utils/validation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEpD;;;GAGG;AACH,wBAAgB,qBAAqB,CACnC,QAAQ,EAAE,QAAQ,EAClB,KAAK,EAAE,SAAS,GACf;IAAE,KAAK,EAAE,OAAO,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,CA6CrC;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,QAAQ,EACd,EAAE,EAAE,QAAQ,EACZ,KAAK,EAAE,SAAS,GACf;IAAE,SAAS,EAAE,OAAO,CAAC;IAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,CAAA;CAAE,CAkB3C"} \ No newline at end of file diff --git a/packages/engine-core/dist/game/utils/validation.js b/packages/engine-core/dist/game/utils/validation.js deleted file mode 100644 index 102fa7b..0000000 --- a/packages/engine-core/dist/game/utils/validation.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Validates that an entry position is within valid scene bounds and not blocked by walls. - * Used to verify entry positions in scene transitions are accessible. - */ -export function validateEntryPosition(position, scene) { - const [x, y, z] = position; - const { ground, walls } = scene; - // Check position is within ground bounds - if (x < ground.minX || x > ground.maxX) { - return { valid: false, reason: "outside ground bounds (X)" }; - } - if (z < ground.minZ || z > ground.maxZ) { - return { valid: false, reason: "outside ground bounds (Z)" }; - } - // Check position Y matches ground - if (Math.abs(y - ground.y) > 0.01) { - return { valid: false, reason: `Y mismatch: expected ~${ground.y}, got ${y}` }; - } - // Check position not inside any wall - // Simplified check: see if position intersects with any wall's AABB - // (Note: walls can be rotated, so this is conservative but safe) - for (const wall of walls) { - const [wx, wy, wz] = wall.position; - const [hwx, hwy, hwz] = wall.halfSize; - // Conservative AABB check (doesn't account for rotation) - // Real collision would use SAT, but this is good enough for validation - const wallMinX = wx - hwx; - const wallMaxX = wx + hwx; - const wallMinZ = wz - hwz; - const wallMaxZ = wz + hwz; - // Add small buffer to account for player collision radius - const buffer = 0.5; - if (x > wallMinX - buffer && - x < wallMaxX + buffer && - z > wallMinZ - buffer && - z < wallMaxZ + buffer) { - return { valid: false, reason: `position inside wall at [${wx}, ${wy}, ${wz}]` }; - } - } - return { valid: true }; -} -/** - * Validates that a walk path from source to destination is reachable. - * Uses A* pathfinding to check connectivity. - * Returns the calculated path if reachable. - */ -export function validateWalkPath(from, to, scene) { - // Validate both endpoints first - const fromValid = validateEntryPosition(from, scene); - const toValid = validateEntryPosition(to, scene); - if (!fromValid.valid) { - return { reachable: false }; - } - if (!toValid.valid) { - return { reachable: false }; - } - // Simple pathfinding: straight-line check (no obstacles) - // In a full implementation, this would use A* or similar - // For now, accept if both are valid (assuming pathfinding handled elsewhere) - const path = [from, to]; - return { reachable: true, path }; -} -//# sourceMappingURL=validation.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/game/utils/validation.js.map b/packages/engine-core/dist/game/utils/validation.js.map deleted file mode 100644 index a3d7b0c..0000000 --- a/packages/engine-core/dist/game/utils/validation.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"validation.js","sourceRoot":"","sources":["../../../src/game/utils/validation.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,MAAM,UAAU,qBAAqB,CACnC,QAAkB,EAClB,KAAgB;IAEhB,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,GAAG,QAAQ,CAAC;IAC3B,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,KAAK,CAAC;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B,CAAC,GAAG,QAAQ,GAAG,MAAM;YACrB,CAAC,GAAG,QAAQ,GAAG,MAAM,EACrB,CAAC;YACD,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,4BAA4B,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC;QACnF,CAAC;IACH,CAAC;IAED,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;AACzB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,gBAAgB,CAC9B,IAAc,EACd,EAAY,EACZ,KAAgB;IAEhB,gCAAgC;IAChC,MAAM,SAAS,GAAG,qBAAqB,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IACrD,MAAM,OAAO,GAAG,qBAAqB,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;IAEjD,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC;QACrB,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;IACD,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACnB,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;IAC9B,CAAC;IAED,yDAAyD;IACzD,yDAAyD;IACzD,6EAA6E;IAC7E,MAAM,IAAI,GAAe,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;IAEpC,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;AACnC,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/index.d.ts b/packages/engine-core/dist/index.d.ts deleted file mode 100644 index 04c9a60..0000000 --- a/packages/engine-core/dist/index.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -export * from "./game/types"; -export * from "./game/logic"; -export * from "./game/state"; -export * from "./game/commands"; -export * from "./game/events"; -export * from "./game/i18n"; -export * from "./events"; -export * from "./ports"; -export declare const VERSION = "0.4.0"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/index.d.ts.map b/packages/engine-core/dist/index.d.ts.map deleted file mode 100644 index 2737960..0000000 --- a/packages/engine-core/dist/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,cAAc,CAAC;AAC7B,cAAc,cAAc,CAAC;AAC7B,cAAc,cAAc,CAAC;AAC7B,cAAc,iBAAiB,CAAC;AAChC,cAAc,eAAe,CAAC;AAC9B,cAAc,aAAa,CAAC;AAC5B,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC;AAExB,eAAO,MAAM,OAAO,UAAU,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/index.js b/packages/engine-core/dist/index.js deleted file mode 100644 index a31b0fe..0000000 --- a/packages/engine-core/dist/index.js +++ /dev/null @@ -1,10 +0,0 @@ -export * from "./game/types"; -export * from "./game/logic"; -export * from "./game/state"; -export * from "./game/commands"; -export * from "./game/events"; -export * from "./game/i18n"; -export * from "./events"; -export * from "./ports"; -export const VERSION = "0.4.0"; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/index.js.map b/packages/engine-core/dist/index.js.map deleted file mode 100644 index 183441b..0000000 --- a/packages/engine-core/dist/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,cAAc,CAAC;AAC7B,cAAc,cAAc,CAAC;AAC7B,cAAc,cAAc,CAAC;AAC7B,cAAc,iBAAiB,CAAC;AAChC,cAAc,eAAe,CAAC;AAC9B,cAAc,aAAa,CAAC;AAC5B,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC;AAExB,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/ports/audio.d.ts b/packages/engine-core/dist/ports/audio.d.ts deleted file mode 100644 index 3428af4..0000000 --- a/packages/engine-core/dist/ports/audio.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type { SoundCategory, SoundDefinition } from "../game/types"; -export type AudioMuteTarget = "master" | SoundCategory; -export interface AudioPlayOptions { - /** Override de volumen 0..1 para esta reproducción concreta. */ - volume?: number; -} -export interface AudioMusicOptions { - fadeMs?: number; - volume?: number; -} -/** - * Port abstracto para reproducción de audio. - * El adapter web (HTMLAudio/Howler/WebAudio) lo implementa fuera de core. - */ -export interface AudioPort { - playSound(def: SoundDefinition, opts?: AudioPlayOptions): void; - playMusic(def: SoundDefinition, opts?: AudioMusicOptions): void; - stopMusic(opts?: AudioMusicOptions): void; - setMuted(target: AudioMuteTarget, muted: boolean): void; - setVolume(target: AudioMuteTarget, volume: number): void; - preload(urls: string[]): Promise; - dispose(): void; -} -//# sourceMappingURL=audio.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/ports/audio.d.ts.map b/packages/engine-core/dist/ports/audio.d.ts.map deleted file mode 100644 index 7331e7a..0000000 --- a/packages/engine-core/dist/ports/audio.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"audio.d.ts","sourceRoot":"","sources":["../../src/ports/audio.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAEpE,MAAM,MAAM,eAAe,GAAG,QAAQ,GAAG,aAAa,CAAC;AAEvD,MAAM,WAAW,gBAAgB;IAC/B,gEAAgE;IAChE,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,iBAAiB;IAChC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;GAGG;AACH,MAAM,WAAW,SAAS;IACxB,SAAS,CAAC,GAAG,EAAE,eAAe,EAAE,IAAI,CAAC,EAAE,gBAAgB,GAAG,IAAI,CAAC;IAC/D,SAAS,CAAC,GAAG,EAAE,eAAe,EAAE,IAAI,CAAC,EAAE,iBAAiB,GAAG,IAAI,CAAC;IAChE,SAAS,CAAC,IAAI,CAAC,EAAE,iBAAiB,GAAG,IAAI,CAAC;IAC1C,QAAQ,CAAC,MAAM,EAAE,eAAe,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,CAAC;IACxD,SAAS,CAAC,MAAM,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACzD,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACvC,OAAO,IAAI,IAAI,CAAC;CACjB"} \ No newline at end of file diff --git a/packages/engine-core/dist/ports/audio.js b/packages/engine-core/dist/ports/audio.js deleted file mode 100644 index 7fcb6a5..0000000 --- a/packages/engine-core/dist/ports/audio.js +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=audio.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/ports/audio.js.map b/packages/engine-core/dist/ports/audio.js.map deleted file mode 100644 index 48202ea..0000000 --- a/packages/engine-core/dist/ports/audio.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"audio.js","sourceRoot":"","sources":["../../src/ports/audio.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/engine-core/dist/ports/gameLoop.d.ts b/packages/engine-core/dist/ports/gameLoop.d.ts deleted file mode 100644 index a25ecb6..0000000 --- a/packages/engine-core/dist/ports/gameLoop.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -/** Callback invoked each frame with delta time in seconds. */ -export type GameLoopCallback = (deltaSeconds: number) => void; -/** Function returned by subscribe to remove the callback. */ -export type Unsubscribe = () => void; -/** - * Game loop abstraction. Renderer-agnostic contract. - * - * Implementations: - * - R3F: wrap `useFrame((state, delta) => callback(delta))` - * - Canvas2D: requestAnimationFrame loop - * - Headless: manual tick via `HeadlessGameLoop.step(delta)` for tests - */ -export interface GameLoopPort { - /** Subscribe a callback to be called each frame. Returns unsubscribe fn. */ - subscribe(callback: GameLoopCallback): Unsubscribe; - /** Optional: pause/resume the loop. Some impls may noop. */ - pause?(): void; - resume?(): void; -} -//# sourceMappingURL=gameLoop.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/ports/gameLoop.d.ts.map b/packages/engine-core/dist/ports/gameLoop.d.ts.map deleted file mode 100644 index c2cbdf7..0000000 --- a/packages/engine-core/dist/ports/gameLoop.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"gameLoop.d.ts","sourceRoot":"","sources":["../../src/ports/gameLoop.ts"],"names":[],"mappings":"AAAA,8DAA8D;AAC9D,MAAM,MAAM,gBAAgB,GAAG,CAAC,YAAY,EAAE,MAAM,KAAK,IAAI,CAAC;AAE9D,6DAA6D;AAC7D,MAAM,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC;AAErC;;;;;;;GAOG;AACH,MAAM,WAAW,YAAY;IAC3B,4EAA4E;IAC5E,SAAS,CAAC,QAAQ,EAAE,gBAAgB,GAAG,WAAW,CAAC;IAEnD,4DAA4D;IAC5D,KAAK,CAAC,IAAI,IAAI,CAAC;IACf,MAAM,CAAC,IAAI,IAAI,CAAC;CACjB"} \ No newline at end of file diff --git a/packages/engine-core/dist/ports/gameLoop.js b/packages/engine-core/dist/ports/gameLoop.js deleted file mode 100644 index 7adf71a..0000000 --- a/packages/engine-core/dist/ports/gameLoop.js +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=gameLoop.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/ports/gameLoop.js.map b/packages/engine-core/dist/ports/gameLoop.js.map deleted file mode 100644 index 9a1eabb..0000000 --- a/packages/engine-core/dist/ports/gameLoop.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"gameLoop.js","sourceRoot":"","sources":["../../src/ports/gameLoop.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/engine-core/dist/ports/headlessAudio.d.ts b/packages/engine-core/dist/ports/headlessAudio.d.ts deleted file mode 100644 index 35ab7ba..0000000 --- a/packages/engine-core/dist/ports/headlessAudio.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -import type { AudioMuteTarget, AudioMusicOptions, AudioPlayOptions, AudioPort } from "./audio"; -import type { SoundDefinition } from "../game/types"; -export type HeadlessAudioCall = { - type: "playSound"; - def: SoundDefinition; - opts?: AudioPlayOptions; -} | { - type: "playMusic"; - def: SoundDefinition; - opts?: AudioMusicOptions; -} | { - type: "stopMusic"; - opts?: AudioMusicOptions; -} | { - type: "setMuted"; - target: AudioMuteTarget; - muted: boolean; -} | { - type: "setVolume"; - target: AudioMuteTarget; - volume: number; -} | { - type: "preload"; - urls: string[]; -} | { - type: "dispose"; -}; -export declare class HeadlessAudioAdapter implements AudioPort { - readonly calls: HeadlessAudioCall[]; - playSound(def: SoundDefinition, opts?: AudioPlayOptions): void; - playMusic(def: SoundDefinition, opts?: AudioMusicOptions): void; - stopMusic(opts?: AudioMusicOptions): void; - setMuted(target: AudioMuteTarget, muted: boolean): void; - setVolume(target: AudioMuteTarget, volume: number): void; - preload(urls: string[]): Promise; - dispose(): void; - reset(): void; -} -//# sourceMappingURL=headlessAudio.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/ports/headlessAudio.d.ts.map b/packages/engine-core/dist/ports/headlessAudio.d.ts.map deleted file mode 100644 index 5ba6ee3..0000000 --- a/packages/engine-core/dist/ports/headlessAudio.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"headlessAudio.d.ts","sourceRoot":"","sources":["../../src/ports/headlessAudio.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,eAAe,EACf,iBAAiB,EACjB,gBAAgB,EAChB,SAAS,EACV,MAAM,SAAS,CAAC;AACjB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAErD,MAAM,MAAM,iBAAiB,GACzB;IAAE,IAAI,EAAE,WAAW,CAAC;IAAC,GAAG,EAAE,eAAe,CAAC;IAAC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100644 index 69882cb..0000000 --- a/packages/engine-core/dist/ports/headlessAudio.js +++ /dev/null @@ -1,30 +0,0 @@ -export class HeadlessAudioAdapter { - constructor() { - this.calls = []; - } - playSound(def, opts) { - this.calls.push({ type: "playSound", def, opts }); - } - playMusic(def, opts) { - this.calls.push({ type: "playMusic", def, opts }); - } - stopMusic(opts) { - this.calls.push({ type: "stopMusic", opts }); - } - setMuted(target, muted) { - this.calls.push({ type: "setMuted", target, muted }); - } - setVolume(target, volume) { - this.calls.push({ type: "setVolume", target, volume }); - } - async preload(urls) { - this.calls.push({ type: "preload", urls }); - } - dispose() { - this.calls.push({ type: "dispose" }); - } - reset() { - this.calls.length = 0; - } -} -//# sourceMappingURL=headlessAudio.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/ports/headlessAudio.js.map b/packages/engine-core/dist/ports/headlessAudio.js.map deleted file mode 100644 index 7e3b9ad..0000000 --- a/packages/engine-core/dist/ports/headlessAudio.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"headlessAudio.js","sourceRoot":"","sources":["../../src/ports/headlessAudio.ts"],"names":[],"mappings":"AAiBA,MAAM,OAAO,oBAAoB;IAAjC;QACW,UAAK,GAAwB,EAAE,CAAC;IA2B3C,CAAC;IAzBC,SAAS,CAAC,GAAoB,EAAE,IAAuB;QACrD,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC;IACpD,CAAC;IACD,SAAS,CAAC,GAAoB,EAAE,IAAwB;QACtD,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC;IACpD,CAAC;IACD,SAAS,CAAC,IAAwB;QAChC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC;IAC/C,CAAC;IACD,QAAQ,CAAC,MAAuB,EAAE,KAAc;QAC9C,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;IACvD,CAAC;IACD,SAAS,CAAC,MAAuB,EAAE,MAAc;QAC/C,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IACzD,CAAC;IACD,KAAK,CAAC,OAAO,CAAC,IAAc;QAC1B,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7C,CAAC;IACD,OAAO;QACL,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,CAAC;IACvC,CAAC;IAED,KAAK;QACH,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;IACxB,CAAC;CACF"} \ No newline at end of file diff --git a/packages/engine-core/dist/ports/headlessGameLoop.d.ts b/packages/engine-core/dist/ports/headlessGameLoop.d.ts deleted file mode 100644 index 2b7d477..0000000 --- a/packages/engine-core/dist/ports/headlessGameLoop.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { GameLoopCallback, GameLoopPort, Unsubscribe } from "./gameLoop"; -/** - * Headless GameLoop for tests: tick manually via `step(delta)`. - * No renderer dependency — suitable for unit tests. - */ -export declare class HeadlessGameLoop implements GameLoopPort { - private callbacks; - subscribe(callback: GameLoopCallback): Unsubscribe; - /** Manually advance one frame. Call this in tests to drive logic. */ - step(deltaSeconds: number): void; -} -//# sourceMappingURL=headlessGameLoop.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/ports/headlessGameLoop.d.ts.map b/packages/engine-core/dist/ports/headlessGameLoop.d.ts.map deleted file mode 100644 index 63955b6..0000000 --- a/packages/engine-core/dist/ports/headlessGameLoop.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"headlessGameLoop.d.ts","sourceRoot":"","sources":["../../src/ports/headlessGameLoop.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9E;;;GAGG;AACH,qBAAa,gBAAiB,YAAW,YAAY;IACnD,OAAO,CAAC,SAAS,CAA+B;IAEhD,SAAS,CAAC,QAAQ,EAAE,gBAAgB,GAAG,WAAW;IAKlD,qEAAqE;IACrE,IAAI,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI;CAGjC"} \ No newline at end of file diff --git a/packages/engine-core/dist/ports/headlessGameLoop.js b/packages/engine-core/dist/ports/headlessGameLoop.js deleted file mode 100644 index 8254112..0000000 --- a/packages/engine-core/dist/ports/headlessGameLoop.js +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Headless GameLoop for tests: tick manually via `step(delta)`. - * No renderer dependency — suitable for unit tests. - */ -export class HeadlessGameLoop { - constructor() { - this.callbacks = new Set(); - } - subscribe(callback) { - this.callbacks.add(callback); - return () => this.callbacks.delete(callback); - } - /** Manually advance one frame. Call this in tests to drive logic. */ - step(deltaSeconds) { - for (const cb of this.callbacks) - cb(deltaSeconds); - } -} -//# sourceMappingURL=headlessGameLoop.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/ports/headlessGameLoop.js.map b/packages/engine-core/dist/ports/headlessGameLoop.js.map deleted file mode 100644 index ac99fba..0000000 --- a/packages/engine-core/dist/ports/headlessGameLoop.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"headlessGameLoop.js","sourceRoot":"","sources":["../../src/ports/headlessGameLoop.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,MAAM,OAAO,gBAAgB;IAA7B;QACU,cAAS,GAAG,IAAI,GAAG,EAAoB,CAAC;IAWlD,CAAC;IATC,SAAS,CAAC,QAA0B;QAClC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAC7B,OAAO,GAAG,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IAC/C,CAAC;IAED,qEAAqE;IACrE,IAAI,CAAC,YAAoB;QACvB,KAAK,MAAM,EAAE,IAAI,IAAI,CAAC,SAAS;YAAE,EAAE,CAAC,YAAY,CAAC,CAAC;IACpD,CAAC;CACF"} \ No newline at end of file diff --git a/packages/engine-core/dist/ports/headlessI18n.d.ts b/packages/engine-core/dist/ports/headlessI18n.d.ts deleted file mode 100644 index b9aab54..0000000 --- a/packages/engine-core/dist/ports/headlessI18n.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -import type { Locale } from "../game/types"; -import type { I18nPort } from "./i18n"; -export type HeadlessI18nCall = { - type: "detect"; -} | { - type: "persist"; - locale: Locale; -} | { - type: "clear"; -}; -/** - * Test / SSR-friendly implementation of {@link I18nPort}. Records every call - * and stores the persisted locale in memory. - */ -export declare class HeadlessI18nAdapter implements I18nPort { - readonly calls: HeadlessI18nCall[]; - private stored; - constructor(initial?: Locale | null); - detectLocale(): Locale | null; - persistLocale(locale: Locale): void; - clearLocale(): void; - /** Reset call log and stored value. */ - reset(initial?: Locale | null): void; -} -//# sourceMappingURL=headlessI18n.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/ports/headlessI18n.d.ts.map b/packages/engine-core/dist/ports/headlessI18n.d.ts.map deleted file mode 100644 index 531418d..0000000 --- a/packages/engine-core/dist/ports/headlessI18n.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"headlessI18n.d.ts","sourceRoot":"","sources":["../../src/ports/headlessI18n.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAEvC,MAAM,MAAM,gBAAgB,GACxB;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,GAClB;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GACnC;IAAE,IAAI,EAAE,OAAO,CAAA;CAAE,CAAC;AAEtB;;;GAGG;AACH,qBAAa,mBAAoB,YAAW,QAAQ;IAClD,QAAQ,CAAC,KAAK,EAAE,gBAAgB,EAAE,CAAM;IACxC,OAAO,CAAC,MAAM,CAAgB;gBAElB,OAAO,GAAE,MAAM,GAAG,IAAW;IAIzC,YAAY,IAAI,MAAM,GAAG,IAAI;IAK7B,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAKnC,WAAW,IAAI,IAAI;IAKnB,uCAAuC;IACvC,KAAK,CAAC,OAAO,GAAE,MAAM,GAAG,IAAW,GAAG,IAAI;CAI3C"} \ No newline at end of file diff --git a/packages/engine-core/dist/ports/headlessI18n.js b/packages/engine-core/dist/ports/headlessI18n.js deleted file mode 100644 index 9bbe923..0000000 --- a/packages/engine-core/dist/ports/headlessI18n.js +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Test / SSR-friendly implementation of {@link I18nPort}. Records every call - * and stores the persisted locale in memory. - */ -export class HeadlessI18nAdapter { - constructor(initial = null) { - this.calls = []; - this.stored = initial; - } - detectLocale() { - this.calls.push({ type: "detect" }); - return this.stored; - } - persistLocale(locale) { - this.calls.push({ type: "persist", locale }); - this.stored = locale; - } - clearLocale() { - this.calls.push({ type: "clear" }); - this.stored = null; - } - /** Reset call log and stored value. */ - reset(initial = null) { - this.calls.length = 0; - this.stored = initial; - } -} -//# sourceMappingURL=headlessI18n.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/ports/headlessI18n.js.map b/packages/engine-core/dist/ports/headlessI18n.js.map deleted file mode 100644 index 4428373..0000000 --- a/packages/engine-core/dist/ports/headlessI18n.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"headlessI18n.js","sourceRoot":"","sources":["../../src/ports/headlessI18n.ts"],"names":[],"mappings":"AAQA;;;GAGG;AACH,MAAM,OAAO,mBAAmB;IAI9B,YAAY,UAAyB,IAAI;QAHhC,UAAK,GAAuB,EAAE,CAAC;QAItC,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC;IACxB,CAAC;IAED,YAAY;QACV,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC;QACpC,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED,aAAa,CAAC,MAAc;QAC1B,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC;QAC7C,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAED,WAAW;QACT,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC;QACnC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;IACrB,CAAC;IAED,uCAAuC;IACvC,KAAK,CAAC,UAAyB,IAAI;QACjC,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;QACtB,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC;IACxB,CAAC;CACF"} \ No newline at end of file diff --git a/packages/engine-core/dist/ports/headlessInput.d.ts b/packages/engine-core/dist/ports/headlessInput.d.ts deleted file mode 100644 index f0642b1..0000000 --- a/packages/engine-core/dist/ports/headlessInput.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type { DirectionListener, InputDirection, InputPort, InputPointerEvent, InputUnsubscribe, PointerListener } from "./input"; -/** - * Headless InputPort for tests. Call `pushDirection` and `pushPointer` - * to simulate input. No DOM dependency. - */ -export declare class HeadlessInput implements InputPort { - private direction; - private dirListeners; - private ptrListeners; - onDirection(l: DirectionListener): InputUnsubscribe; - onPointer(l: PointerListener): InputUnsubscribe; - getDirection(): InputDirection; - /** Simulate a direction input event. */ - pushDirection(dir: InputDirection): void; - /** Simulate a pointer/click event. */ - pushPointer(event: InputPointerEvent): void; -} -//# sourceMappingURL=headlessInput.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/ports/headlessInput.d.ts.map b/packages/engine-core/dist/ports/headlessInput.d.ts.map deleted file mode 100644 index 89e3b28..0000000 --- a/packages/engine-core/dist/ports/headlessInput.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"headlessInput.d.ts","sourceRoot":"","sources":["../../src/ports/headlessInput.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iBAAiB,EACjB,cAAc,EACd,SAAS,EACT,iBAAiB,EACjB,gBAAgB,EAChB,eAAe,EAChB,MAAM,SAAS,CAAC;AAEjB;;;GAGG;AACH,qBAAa,aAAc,YAAW,SAAS;IAC7C,OAAO,CAAC,SAAS,CAAkD;IACnE,OAAO,CAAC,YAAY,CAAgC;IACpD,OAAO,CAAC,YAAY,CAA8B;IAElD,WAAW,CAAC,CAAC,EAAE,iBAAiB,GAAG,gBAAgB;IAKnD,SAAS,CAAC,CAAC,EAAE,eAAe,GAAG,gBAAgB;IAK/C,YAAY,IAAI,cAAc;IAI9B,wCAAwC;IACxC,aAAa,CAAC,GAAG,EAAE,cAAc,GAAG,IAAI;IAKxC,sCAAsC;IACtC,WAAW,CAAC,KAAK,EAAE,iBAAiB,GAAG,IAAI;CAG5C"} \ No newline at end of file diff --git a/packages/engine-core/dist/ports/headlessInput.js b/packages/engine-core/dist/ports/headlessInput.js deleted file mode 100644 index 1b029f9..0000000 --- a/packages/engine-core/dist/ports/headlessInput.js +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Headless InputPort for tests. Call `pushDirection` and `pushPointer` - * to simulate input. No DOM dependency. - */ -export class HeadlessInput { - constructor() { - this.direction = { horizontal: 0, vertical: 0 }; - this.dirListeners = new Set(); - this.ptrListeners = new Set(); - } - onDirection(l) { - this.dirListeners.add(l); - return () => this.dirListeners.delete(l); - } - onPointer(l) { - this.ptrListeners.add(l); - return () => this.ptrListeners.delete(l); - } - getDirection() { - return this.direction; - } - /** Simulate a direction input event. */ - pushDirection(dir) { - this.direction = dir; - for (const l of this.dirListeners) - l(dir); - } - /** Simulate a pointer/click event. */ - pushPointer(event) { - for (const l of this.ptrListeners) - l(event); - } -} -//# sourceMappingURL=headlessInput.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/ports/headlessInput.js.map b/packages/engine-core/dist/ports/headlessInput.js.map deleted file mode 100644 index dd5ae3c..0000000 --- a/packages/engine-core/dist/ports/headlessInput.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"headlessInput.js","sourceRoot":"","sources":["../../src/ports/headlessInput.ts"],"names":[],"mappings":"AASA;;;GAGG;AACH,MAAM,OAAO,aAAa;IAA1B;QACU,cAAS,GAAmB,EAAE,UAAU,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC;QAC3D,iBAAY,GAAG,IAAI,GAAG,EAAqB,CAAC;QAC5C,iBAAY,GAAG,IAAI,GAAG,EAAmB,CAAC;IA0BpD,CAAC;IAxBC,WAAW,CAAC,CAAoB;QAC9B,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QACzB,OAAO,GAAG,EAAE,CAAC,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IAC3C,CAAC;IAED,SAAS,CAAC,CAAkB;QAC1B,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QACzB,OAAO,GAAG,EAAE,CAAC,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IAC3C,CAAC;IAED,YAAY;QACV,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAED,wCAAwC;IACxC,aAAa,CAAC,GAAmB;QAC/B,IAAI,CAAC,SAAS,GAAG,GAAG,CAAC;QACrB,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,YAAY;YAAE,CAAC,CAAC,GAAG,CAAC,CAAC;IAC5C,CAAC;IAED,sCAAsC;IACtC,WAAW,CAAC,KAAwB;QAClC,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,YAAY;YAAE,CAAC,CAAC,KAAK,CAAC,CAAC;IAC9C,CAAC;CACF"} \ No newline at end of file diff --git a/packages/engine-core/dist/ports/i18n.d.ts b/packages/engine-core/dist/ports/i18n.d.ts deleted file mode 100644 index 4d96ce9..0000000 --- a/packages/engine-core/dist/ports/i18n.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -import type { Locale } from "../game/types"; -/** - * Port abstracting how the engine reads / writes the user's preferred locale. - * - * Platform adapters (web, native, server) implement this. Core never reads - * `navigator`, `localStorage`, cookies or framework routing directly. - */ -export interface I18nPort { - /** - * Locale to use at boot. Implementations typically check persisted storage - * first, then fall back to browser / OS hints. Return `null` when no - * preference is detectable so the store keeps `defaultLocale`. - */ - detectLocale(): Locale | null; - /** Persist the user's choice for subsequent sessions. */ - persistLocale(locale: Locale): void; - /** Clear any persistence. Useful for logout / settings reset. */ - clearLocale?(): void; -} -//# sourceMappingURL=i18n.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/ports/i18n.d.ts.map b/packages/engine-core/dist/ports/i18n.d.ts.map deleted file mode 100644 index d4da411..0000000 --- a/packages/engine-core/dist/ports/i18n.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"i18n.d.ts","sourceRoot":"","sources":["../../src/ports/i18n.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAE5C;;;;;GAKG;AACH,MAAM,WAAW,QAAQ;IACvB;;;;OAIG;IACH,YAAY,IAAI,MAAM,GAAG,IAAI,CAAC;IAE9B,yDAAyD;IACzD,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IAEpC,iEAAiE;IACjE,WAAW,CAAC,IAAI,IAAI,CAAC;CACtB"} \ No newline at end of file diff --git a/packages/engine-core/dist/ports/i18n.js b/packages/engine-core/dist/ports/i18n.js deleted file mode 100644 index e94adb9..0000000 --- a/packages/engine-core/dist/ports/i18n.js +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=i18n.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/ports/i18n.js.map b/packages/engine-core/dist/ports/i18n.js.map deleted file mode 100644 index e90effd..0000000 --- a/packages/engine-core/dist/ports/i18n.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"i18n.js","sourceRoot":"","sources":["../../src/ports/i18n.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/engine-core/dist/ports/index.d.ts b/packages/engine-core/dist/ports/index.d.ts deleted file mode 100644 index 775501a..0000000 --- a/packages/engine-core/dist/ports/index.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -export type { GameLoopCallback, GameLoopPort, Unsubscribe, } from "./gameLoop"; -export type { InputDirection, InputPointerEvent, DirectionListener, PointerListener, InputUnsubscribe, InputPort, } from "./input"; -export type { ViewportPort } from "./viewport"; -export type { AudioMuteTarget, AudioMusicOptions, AudioPlayOptions, AudioPort, } from "./audio"; -export { HeadlessGameLoop } from "./headlessGameLoop"; -export { HeadlessInput } from "./headlessInput"; -export { HeadlessAudioAdapter, type HeadlessAudioCall } from "./headlessAudio"; -export type { I18nPort } from "./i18n"; -export { HeadlessI18nAdapter, type HeadlessI18nCall } from "./headlessI18n"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/ports/index.d.ts.map b/packages/engine-core/dist/ports/index.d.ts.map deleted file mode 100644 index 20dc153..0000000 --- a/packages/engine-core/dist/ports/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/ports/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,gBAAgB,EAChB,YAAY,EACZ,WAAW,GACZ,MAAM,YAAY,CAAC;AAEpB,YAAY,EACV,cAAc,EACd,iBAAiB,EACjB,iBAAiB,EACjB,eAAe,EACf,gBAAgB,EAChB,SAAS,GACV,MAAM,SAAS,CAAC;AAEjB,YAAY,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE/C,YAAY,EACV,eAAe,EACf,iBAAiB,EACjB,gBAAgB,EAChB,SAAS,GACV,MAAM,SAAS,CAAC;AAEjB,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,oBAAoB,EAAE,KAAK,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAE/E,YAAY,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,mBAAmB,EAAE,KAAK,gBAAgB,EAAE,MAAM,gBAAgB,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/ports/index.js b/packages/engine-core/dist/ports/index.js deleted file mode 100644 index cca10ce..0000000 --- a/packages/engine-core/dist/ports/index.js +++ /dev/null @@ -1,5 +0,0 @@ -export { HeadlessGameLoop } from "./headlessGameLoop"; -export { HeadlessInput } from "./headlessInput"; -export { HeadlessAudioAdapter } from "./headlessAudio"; -export { HeadlessI18nAdapter } from "./headlessI18n"; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/ports/index.js.map b/packages/engine-core/dist/ports/index.js.map deleted file mode 100644 index 3262b86..0000000 --- a/packages/engine-core/dist/ports/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/ports/index.ts"],"names":[],"mappings":"AAwBA,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,oBAAoB,EAA0B,MAAM,iBAAiB,CAAC;AAG/E,OAAO,EAAE,mBAAmB,EAAyB,MAAM,gBAAgB,CAAC"} \ No newline at end of file diff --git a/packages/engine-core/dist/ports/input.d.ts b/packages/engine-core/dist/ports/input.d.ts deleted file mode 100644 index 72ee3b4..0000000 --- a/packages/engine-core/dist/ports/input.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -/** Direction vector from input (e.g. keyboard arrows, joystick). */ -export interface InputDirection { - horizontal: number; - vertical: number; -} -/** Pointer/click event in world coordinates (already converted by renderer). */ -export interface InputPointerEvent { - worldX: number; - worldZ: number; - button: "primary" | "secondary"; -} -export type DirectionListener = (dir: InputDirection) => void; -export type PointerListener = (event: InputPointerEvent) => void; -export type InputUnsubscribe = () => void; -/** - * Input abstraction. Renderer-agnostic contract. - * - * The renderer is responsible for converting framework-specific events - * (KeyboardEvent, PointerEvent) into these neutral shapes before pushing - * them through the port. - */ -export interface InputPort { - /** Subscribe to continuous direction input (keyboard, joystick). */ - onDirection(listener: DirectionListener): InputUnsubscribe; - /** Subscribe to pointer/click events in world space. */ - onPointer(listener: PointerListener): InputUnsubscribe; - /** Read current direction snapshot (for polling in game loop). */ - getDirection(): InputDirection; -} -//# sourceMappingURL=input.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/ports/input.d.ts.map b/packages/engine-core/dist/ports/input.d.ts.map deleted file mode 100644 index a55bd9a..0000000 --- a/packages/engine-core/dist/ports/input.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"input.d.ts","sourceRoot":"","sources":["../../src/ports/input.ts"],"names":[],"mappings":"AAAA,oEAAoE;AACpE,MAAM,WAAW,cAAc;IAC7B,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,gFAAgF;AAChF,MAAM,WAAW,iBAAiB;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,SAAS,GAAG,WAAW,CAAC;CACjC;AAED,MAAM,MAAM,iBAAiB,GAAG,CAAC,GAAG,EAAE,cAAc,KAAK,IAAI,CAAC;AAC9D,MAAM,MAAM,eAAe,GAAG,CAAC,KAAK,EAAE,iBAAiB,KAAK,IAAI,CAAC;AACjE,MAAM,MAAM,gBAAgB,GAAG,MAAM,IAAI,CAAC;AAE1C;;;;;;GAMG;AACH,MAAM,WAAW,SAAS;IACxB,oEAAoE;IACpE,WAAW,CAAC,QAAQ,EAAE,iBAAiB,GAAG,gBAAgB,CAAC;IAE3D,wDAAwD;IACxD,SAAS,CAAC,QAAQ,EAAE,eAAe,GAAG,gBAAgB,CAAC;IAEvD,kEAAkE;IAClE,YAAY,IAAI,cAAc,CAAC;CAChC"} \ No newline at end of file diff --git a/packages/engine-core/dist/ports/input.js b/packages/engine-core/dist/ports/input.js deleted file mode 100644 index fab5677..0000000 --- a/packages/engine-core/dist/ports/input.js +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=input.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/ports/input.js.map b/packages/engine-core/dist/ports/input.js.map deleted file mode 100644 index 0eefadd..0000000 --- a/packages/engine-core/dist/ports/input.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"input.js","sourceRoot":"","sources":["../../src/ports/input.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/engine-core/dist/ports/viewport.d.ts b/packages/engine-core/dist/ports/viewport.d.ts deleted file mode 100644 index 599c9bc..0000000 --- a/packages/engine-core/dist/ports/viewport.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Viewport abstraction. Renderer-agnostic contract. - * - * Provides dimensions and world-to-screen coordinate mapping so that - * non-renderer code (UI overlays, positioning logic) can work independently - * of the rendering technology used. - * - * Note: Full R3F implementation deferred to Phase 4. This is the interface - * definition only (as per ADR-0005). - */ -export interface ViewportPort { - /** Returns the current viewport width in CSS pixels. */ - getWidth(): number; - /** Returns the current viewport height in CSS pixels. */ - getHeight(): number; - /** - * Maps a world-space coordinate to screen space (CSS pixels). - * Returns null if the position is outside the view frustum. - */ - worldToScreen(worldX: number, worldY: number, worldZ: number): { - x: number; - y: number; - } | null; -} -//# sourceMappingURL=viewport.d.ts.map \ No newline at end of file diff --git a/packages/engine-core/dist/ports/viewport.d.ts.map b/packages/engine-core/dist/ports/viewport.d.ts.map deleted file mode 100644 index 9c7f0e5..0000000 --- a/packages/engine-core/dist/ports/viewport.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"viewport.d.ts","sourceRoot":"","sources":["../../src/ports/viewport.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,WAAW,YAAY;IAC3B,wDAAwD;IACxD,QAAQ,IAAI,MAAM,CAAC;IAEnB,yDAAyD;IACzD,SAAS,IAAI,MAAM,CAAC;IAEpB;;;OAGG;IACH,aAAa,CACX,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,GACb;QAAE,CAAC,EAAE,MAAM,CAAC;QAAC,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;CACpC"} \ No newline at end of file diff --git a/packages/engine-core/dist/ports/viewport.js b/packages/engine-core/dist/ports/viewport.js deleted file mode 100644 index f9c648a..0000000 --- a/packages/engine-core/dist/ports/viewport.js +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=viewport.js.map \ No newline at end of file diff --git a/packages/engine-core/dist/ports/viewport.js.map b/packages/engine-core/dist/ports/viewport.js.map deleted file mode 100644 index 2cab061..0000000 --- a/packages/engine-core/dist/ports/viewport.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"viewport.js","sourceRoot":"","sources":["../../src/ports/viewport.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/engine-core/package.json b/packages/engine-core/package.json index e879058..34774c8 100644 --- a/packages/engine-core/package.json +++ b/packages/engine-core/package.json @@ -1,6 +1,6 @@ { "name": "@pointclick-engine/engine-core", - "version": "0.4.0", + "version": "0.6.0", "description": "Framework-agnostic core for Point & Click Game Engine", "type": "module", "main": "dist/index.js", @@ -29,6 +29,10 @@ "./state": { "import": "./dist/game/state/index.js", "types": "./dist/game/state/index.d.ts" + }, + "./testing": { + "import": "./dist/testing/index.js", + "types": "./dist/testing/index.d.ts" } }, "sideEffects": false, @@ -37,13 +41,17 @@ "src", "README.md", "LICENSE", - "CHANGELOG.md" + "CHANGELOG.md", + "!src/**/__tests__", + "!src/**/*.test.ts", + "!src/**/*.test.tsx" ], "scripts": { "test": "vitest run", "test:watch": "vitest", "build": "tsc", - "clean": "rm -rf dist" + "clean": "rm -rf dist", + "prepublishOnly": "npm run build" }, "dependencies": { "zustand": "^5.0.13" diff --git a/packages/engine-core/src/__tests__/audioRules.test.ts b/packages/engine-core/src/__tests__/audioRules.test.ts index cd3de3f..0ea0faf 100644 --- a/packages/engine-core/src/__tests__/audioRules.test.ts +++ b/packages/engine-core/src/__tests__/audioRules.test.ts @@ -178,6 +178,36 @@ describe("audioRules", () => { expect(sfxEvent.soundUrl).toBe("/sounds/custom-drop.ogg"); }); + describe("item:dropped por outcome", () => { + const dropCtx: AudioRulesContext = { + defaults: { dropSoundUrl: "/sounds/drop.ogg", pickupSoundUrl: "/sounds/pickup.ogg" }, + items: {}, + transitions: {}, + }; + const dropped = (outcome: string): GameEvent => + ({ type: "item:dropped", itemId: "item1", outcome }) as unknown as GameEvent; + + it("place suena con el sonido de soltar", () => { + const result = resolveAudioEvents(dropped("place"), dropCtx); + expect(result).toEqual([ + { type: "audio:sfxRequested", soundUrl: "/sounds/drop.ogg", category: "sfx" }, + ]); + }); + + it.each([ + "return", + "consume", + "rule-miss", + "on-player", + "pickup-blocked", + "item-interact", + "unknown-item", + "pickup-success", + ])("%s es silencioso", (outcome) => { + expect(resolveAudioEvents(dropped(outcome), dropCtx)).toEqual([]); + }); + }); + it("transition:triggered with override uses override", () => { const ctx: AudioRulesContext = { defaults: { transitionSoundUrl: "/sounds/door-default.ogg" }, diff --git a/packages/engine-core/src/__tests__/clockPort.test.ts b/packages/engine-core/src/__tests__/clockPort.test.ts new file mode 100644 index 0000000..3e8772d --- /dev/null +++ b/packages/engine-core/src/__tests__/clockPort.test.ts @@ -0,0 +1,229 @@ +import { describe, it, expect, vi } from "vitest"; +import { systemClock, HeadlessClock } from "../ports"; + +describe("ClockPort", () => { + describe("HeadlessClock", () => { + it("should initialize with time 0", () => { + const clock = new HeadlessClock(); + expect(clock.now()).toBe(0); + }); + + it("should fire timers in order of due time", () => { + const clock = new HeadlessClock(); + const events: number[] = []; + + clock.setTimeout(() => events.push(1), 100); + clock.setTimeout(() => events.push(2), 50); + clock.setTimeout(() => events.push(3), 150); + + clock.advance(200); + + expect(events).toEqual([2, 1, 3]); + }); + + it("should allow canceling a timer", () => { + const clock = new HeadlessClock(); + const events: string[] = []; + + const cancel = clock.setTimeout(() => events.push("should-not-run"), 100); + clock.setTimeout(() => events.push("should-run"), 200); + + cancel(); + clock.advance(300); + + expect(events).toEqual(["should-run"]); + }); + + it("should handle nested timers scheduled during advance", () => { + const clock = new HeadlessClock(); + const events: number[] = []; + + clock.setTimeout(() => { + events.push(1); + clock.setTimeout(() => events.push(2), 50); + }, 100); + + clock.advance(200); + + expect(events).toEqual([1, 2]); + }); + + it("should advance(0) execute nothing", () => { + const clock = new HeadlessClock(); + const events: string[] = []; + + clock.setTimeout(() => events.push("fired"), 100); + clock.advance(0); + + expect(events).toEqual([]); + expect(clock.pending()).toBe(1); + }); + + it("should report pending timer count", () => { + const clock = new HeadlessClock(); + + expect(clock.pending()).toBe(0); + + const cancel1 = clock.setTimeout(() => {}, 100); + expect(clock.pending()).toBe(1); + + const cancel2 = clock.setTimeout(() => {}, 200); + expect(clock.pending()).toBe(2); + + cancel1(); + expect(clock.pending()).toBe(1); + + clock.advance(300); + expect(clock.pending()).toBe(0); + }); + + it("should handle multiple advance calls correctly", () => { + const clock = new HeadlessClock(); + const events: number[] = []; + + clock.setTimeout(() => events.push(1), 50); + clock.setTimeout(() => events.push(2), 150); + + clock.advance(100); + expect(events).toEqual([1]); + expect(clock.now()).toBe(100); + + clock.advance(100); + expect(events).toEqual([1, 2]); + expect(clock.now()).toBe(200); + }); + + it("should handle timers scheduled in the same millisecond", () => { + const clock = new HeadlessClock(); + const events: number[] = []; + + clock.setTimeout(() => events.push(1), 100); + clock.setTimeout(() => events.push(2), 100); + clock.setTimeout(() => events.push(3), 100); + + clock.advance(100); + + expect(events.length).toBe(3); + expect(events.sort()).toEqual([1, 2, 3]); + }); + + it("should update now() when advancing", () => { + const clock = new HeadlessClock(); + + expect(clock.now()).toBe(0); + clock.advance(50); + expect(clock.now()).toBe(50); + clock.advance(30); + expect(clock.now()).toBe(80); + }); + }); + + describe("HeadlessClock: zero-delay and ordering", () => { + it("fires a zero-delay timer on advance(0)", () => { + const clock = new HeadlessClock(); + const events: string[] = []; + clock.setTimeout(() => events.push("now"), 0); + clock.advance(0); + expect(events).toEqual(["now"]); + expect(clock.pending()).toBe(0); + }); + + it("fires a zero-delay timer scheduled inside a callback", () => { + const clock = new HeadlessClock(); + const events: string[] = []; + clock.setTimeout(() => { + events.push("first"); + clock.setTimeout(() => events.push("chained"), 0); + }, 10); + clock.advance(10); + expect(events).toEqual(["first", "chained"]); + }); + + it("fires timers with the same due time in scheduling order", () => { + const clock = new HeadlessClock(); + const events: number[] = []; + clock.setTimeout(() => events.push(1), 20); + clock.setTimeout(() => events.push(2), 20); + clock.setTimeout(() => events.push(3), 20); + clock.advance(20); + expect(events).toEqual([1, 2, 3]); + }); + + it("reports the due time, not the target, to a callback", () => { + const clock = new HeadlessClock(); + const seen: number[] = []; + clock.setTimeout(() => seen.push(clock.now()), 30); + clock.advance(100); + expect(seen).toEqual([30]); + expect(clock.now()).toBe(100); + }); + + it("does not fire a timer cancelled by an earlier callback", () => { + const clock = new HeadlessClock(); + const events: string[] = []; + let cancelLater = () => {}; + clock.setTimeout(() => { + events.push("first"); + cancelLater(); + }, 10); + cancelLater = clock.setTimeout(() => events.push("later"), 20); + clock.advance(50); + expect(events).toEqual(["first"]); + }); + }); + + describe("systemClock", () => { + it("should return current time with now()", () => { + const before = Date.now(); + const time = systemClock.now(); + const after = Date.now(); + + expect(time).toBeGreaterThanOrEqual(before); + expect(time).toBeLessThanOrEqual(after); + }); + + it("should schedule a callback with setTimeout", async () => { + return new Promise((resolve) => { + const startTime = systemClock.now(); + const called: number[] = []; + + systemClock.setTimeout(() => { + called.push(systemClock.now()); + expect(called[0] - startTime).toBeGreaterThanOrEqual(50); + resolve(); + }, 50); + }); + }); + + it("should allow canceling a scheduled callback", async () => { + return new Promise((resolve) => { + let called = false; + + const cancel = systemClock.setTimeout(() => { + called = true; + }, 100); + + cancel(); + + systemClock.setTimeout(() => { + expect(called).toBe(false); + resolve(); + }, 150); + }); + }); + }); + + describe("ClockPort interface compliance", () => { + it("should work with HeadlessClock and systemClock interchangeably", () => { + const headless = new HeadlessClock(); + const events: string[] = []; + + headless.setTimeout(() => events.push("a"), 100); + headless.setTimeout(() => events.push("b"), 50); + + headless.advance(200); + + expect(events).toEqual(["b", "a"]); + }); + }); +}); diff --git a/packages/engine-core/src/__tests__/conditions.test.ts b/packages/engine-core/src/__tests__/conditions.test.ts new file mode 100644 index 0000000..67448d8 --- /dev/null +++ b/packages/engine-core/src/__tests__/conditions.test.ts @@ -0,0 +1,200 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { + cond, + evaluateCondition as ev, + getConditionContext, + getWorldState, + getInventoryState, + getPlacedItemsState, + useSceneStore, + type Condition, + type ConditionContext, + type PlacedSceneItem, +} from "../index"; + +const stack = (id: string, quantity: number) => ({ id, name: id, spriteUrl: "", quantity }); +const placed = (itemId: string, sceneId: string | undefined, interactionId: string): PlacedSceneItem => ({ + id: `${itemId}-${interactionId}`, itemId, interactionId, name: itemId, spriteUrl: "", + worldPosition: [0, 0, 0], canPickup: false, sceneId, +}); +const ctx = (over: Partial = {}): ConditionContext => ({ + flags: {}, + inventory: [], + placedItems: [], + sceneId: "room", + visitedSceneIds: [], + ...over, +}); + +describe("evaluateCondition: flag", () => { + it("undefined es verdadero", () => expect(ev(undefined, ctx())).toBe(true)); + it("flag inexistente es falso", () => expect(ev(cond.flag("x"), ctx())).toBe(false)); + it("true / numero != 0 / cadena no vacia son verdaderos", () => { + expect(ev(cond.flag("x"), ctx({ flags: { x: true } }))).toBe(true); + expect(ev(cond.flag("x"), ctx({ flags: { x: 2 } }))).toBe(true); + expect(ev(cond.flag("x"), ctx({ flags: { x: "a" } }))).toBe(true); + }); + it("false / 0 / cadena vacia son falsos", () => { + for (const v of [false, 0, ""]) expect(ev(cond.flag("x"), ctx({ flags: { x: v } }))).toBe(false); + }); + it("equals compara estrictamente", () => { + const c = ctx({ flags: { x: 3, s: "a" } }); + expect(ev(cond.flag("x", { equals: 3 }), c)).toBe(true); + expect(ev(cond.flag("x", { equals: "3" }), c)).toBe(false); + expect(ev(cond.flag("s", { equals: "a" }), c)).toBe(true); + }); + it("equals contra undefined con flag inexistente", () => { + expect(ev({ flag: "x", equals: undefined }, ctx())).toBe(true); + expect(ev(cond.flag("x", { equals: false }), ctx())).toBe(false); + }); + it("gte / lte", () => { + const c = ctx({ flags: { n: 3 } }); + expect(ev(cond.flag("n", { gte: 3 }), c)).toBe(true); + expect(ev(cond.flag("n", { gte: 4 }), c)).toBe(false); + expect(ev(cond.flag("n", { lte: 3 }), c)).toBe(true); + expect(ev(cond.flag("n", { lte: 2 }), c)).toBe(false); + }); + it("gte / lte son falsos si el valor no es numero", () => { + const c = ctx({ flags: { s: "5", b: true } }); + expect(ev(cond.flag("s", { gte: 0 }), c)).toBe(false); + expect(ev(cond.flag("b", { lte: 10 }), c)).toBe(false); + expect(ev(cond.flag("none", { gte: 0 }), c)).toBe(false); + }); + it("varios operadores deben cumplirse todos", () => { + const c = ctx({ flags: { n: 5 } }); + expect(ev(cond.flag("n", { gte: 3, lte: 7 }), c)).toBe(true); + expect(ev(cond.flag("n", { gte: 3, lte: 4 }), c)).toBe(false); + expect(ev(cond.flag("n", { equals: 5, gte: 6 }), c)).toBe(false); + }); + it("flag con valor string 'false' es verdadero (cadena no vacia)", () => { + expect(ev(cond.flag("x"), ctx({ flags: { x: "false" } }))).toBe(true); + }); + it("nombres tipo prototipo no se heredan", () => { + expect(ev(cond.flag("toString"), ctx())).toBe(false); + }); +}); + +describe("evaluateCondition: inventario, items, escenas", () => { + const inv = [stack("key", 1), null, stack("coin", 2), stack("coin", 3)]; + it("hasItem por defecto equivale a atLeast 1", () => { + expect(ev(cond.hasItem("key"), ctx({ inventory: inv }))).toBe(true); + expect(ev(cond.hasItem("gem"), ctx({ inventory: inv }))).toBe(false); + expect(ev(cond.hasItem("key"), ctx())).toBe(false); + }); + it("hasItem ignora cantidades de otros ids y atLeast 0 es verdadero", () => { + expect(ev(cond.hasItem("key", { atLeast: 2 }), ctx({ inventory: inv }))).toBe(false); + expect(ev(cond.hasItem("gem", { atLeast: 0 }), ctx({ inventory: inv }))).toBe(true); + }); + it("hasItem atLeast suma cantidades de todos los slots", () => { + expect(ev(cond.hasItem("coin", { atLeast: 5 }), ctx({ inventory: inv }))).toBe(true); + expect(ev(cond.hasItem("coin", { atLeast: 6 }), ctx({ inventory: inv }))).toBe(false); + }); + const items = [placed("trophy", "room", "shelf"), placed("vase", undefined, "table")]; + it("itemPlaced sin restricciones: en cualquier escena", () => { + expect(ev(cond.itemPlaced("trophy"), ctx({ placedItems: items }))).toBe(true); + expect(ev(cond.itemPlaced("vase"), ctx({ placedItems: items }))).toBe(true); + expect(ev(cond.itemPlaced("nope"), ctx({ placedItems: items }))).toBe(false); + }); + it("itemPlaced inScene / at, combinados con Y", () => { + const c = ctx({ placedItems: items }); + expect(ev(cond.itemPlaced("trophy", { inScene: "room" }), c)).toBe(true); + expect(ev(cond.itemPlaced("trophy", { inScene: "town" }), c)).toBe(false); + expect(ev(cond.itemPlaced("trophy", { at: "shelf" }), c)).toBe(true); + expect(ev(cond.itemPlaced("trophy", { at: "table" }), c)).toBe(false); + expect(ev(cond.itemPlaced("trophy", { inScene: "room", at: "shelf" }), c)).toBe(true); + expect(ev(cond.itemPlaced("trophy", { inScene: "town", at: "shelf" }), c)).toBe(false); + expect(ev(cond.itemPlaced("vase", { inScene: "room" }), c)).toBe(false); + }); + it("inScene y visited", () => { + const c = ctx({ visitedSceneIds: ["town"] }); + expect(ev(cond.inScene("room"), c)).toBe(true); + expect(ev(cond.inScene("town"), c)).toBe(false); + expect(ev(cond.visited("town"), c)).toBe(true); + expect(ev(cond.visited("cave"), c)).toBe(false); + }); +}); + +describe("evaluateCondition: combinadores", () => { + const c = ctx({ flags: { a: true, n: 2 }, visitedSceneIds: ["town"] }); + it("all vacio es verdadero, any vacio es falso", () => { + expect(ev(cond.all(), c)).toBe(true); + expect(ev(cond.any(), c)).toBe(false); + }); + it("all / any / not", () => { + expect(ev(cond.all(cond.flag("a"), cond.visited("town")), c)).toBe(true); + expect(ev(cond.all(cond.flag("a"), cond.visited("cave")), c)).toBe(false); + expect(ev(cond.any(cond.flag("zz"), cond.visited("town")), c)).toBe(true); + expect(ev(cond.any(cond.flag("zz"), cond.visited("cave")), c)).toBe(false); + expect(ev(cond.not(cond.flag("zz")), c)).toBe(true); + expect(ev(cond.not(cond.flag("a")), c)).toBe(false); + }); + it("anidamiento", () => { + const nested = cond.all( + cond.not(cond.any(cond.flag("zz"), cond.visited("cave"))), + cond.any(cond.flag("n", { gte: 2 }), cond.inScene("x")), + ); + expect(ev(nested, c)).toBe(true); + expect(ev(cond.not(nested), c)).toBe(false); + }); + it("all / any con hijos desconocidos no lanzan", () => { + const bad = { zzz: 1 } as unknown as Condition; + vi.spyOn(console, "warn").mockImplementation(() => {}); + expect(ev(cond.all(bad), c)).toBe(false); + expect(ev(cond.any(bad, cond.flag("a")), c)).toBe(true); + }); + it("not de undefined (verdadero) es falso", () => { + expect(ev({ not: undefined as unknown as Condition }, c)).toBe(false); + }); +}); + +describe("constructores", () => { + it("producen objetos planos esperados", () => { + expect(cond.flag("x")).toEqual({ flag: "x" }); + expect(cond.flag("n", { gte: 3 })).toEqual({ flag: "n", gte: 3 }); + expect(cond.hasItem("key")).toEqual({ hasItem: "key" }); + expect(cond.hasItem("coin", { atLeast: 2 })).toEqual({ hasItem: "coin", atLeast: 2 }); + expect(cond.itemPlaced("trophy", { inScene: "room" })).toEqual({ itemPlaced: "trophy", inScene: "room" }); + expect(cond.inScene("room")).toEqual({ inScene: "room" }); + expect(cond.visited("town")).toEqual({ visited: "town" }); + expect(cond.all(cond.flag("a"), cond.flag("b"))).toEqual({ all: [{ flag: "a" }, { flag: "b" }] }); + expect(cond.any(cond.flag("a"))).toEqual({ any: [{ flag: "a" }] }); + expect(cond.not(cond.flag("a"))).toEqual({ not: { flag: "a" } }); + }); + it("son serializables a JSON", () => { + const c = cond.all(cond.flag("n", { gte: 1 }), cond.not(cond.visited("x"))); + expect(JSON.parse(JSON.stringify(c))).toEqual(c); + }); +}); +describe("forma desconocida", () => { + afterEach(() => vi.restoreAllMocks()); + it("evalua a false y avisa una sola vez sin lanzar", async () => { + vi.resetModules(); + const mod = await import("../game/narrative/conditions"); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + expect(mod.evaluateCondition({ foo: 1 } as unknown as Condition, ctx())).toBe(false); + expect(mod.evaluateCondition({ bar: 2 } as unknown as Condition, ctx())).toBe(false); + expect(mod.evaluateCondition(null as unknown as Condition, ctx())).toBe(false); + expect(warn).toHaveBeenCalledTimes(1); + }); +}); + +describe("getConditionContext", () => { + beforeEach(() => { + getWorldState().reset(); + getInventoryState().reset(); + getPlacedItemsState().reset(); + useSceneStore.setState({ sceneId: "" }); + }); + it("lee los stores actuales", () => { + getWorldState().setFlag("seen", true); + getWorldState().markSceneVisited("town"); + getPlacedItemsState().addItem(placed("trophy", "room", "shelf")); + useSceneStore.setState({ sceneId: "room" }); + getInventoryState().addItem({ id: "key", name: "key", spriteUrl: "" }); + const c = getConditionContext(); + expect(c.flags).toEqual({ seen: true }); + expect(c.visitedSceneIds).toEqual(["town"]); + expect(c.sceneId).toBe("room"); + expect(ev(cond.all(cond.flag("seen"), cond.hasItem("key"), cond.itemPlaced("trophy", { at: "shelf" })), c)).toBe(true); + }); +}); diff --git a/packages/engine-core/src/__tests__/coreAgnosticism.test.ts b/packages/engine-core/src/__tests__/coreAgnosticism.test.ts new file mode 100644 index 0000000..11f43a2 --- /dev/null +++ b/packages/engine-core/src/__tests__/coreAgnosticism.test.ts @@ -0,0 +1,154 @@ +import { describe, it, expect } from "vitest"; +import { readFileSync, readdirSync } from "node:fs"; +import { join, relative } from "node:path"; + +/** + * Core agnosticism guard: ensures the core never imports framework-specific + * code (React, R3F, Three.js, Next.js) and doesn't use browser APIs directly + * without proper guards. + */ +describe("core agnosticism", () => { + const coreDir = join(__dirname, ".."); + const forbiddenImports = [ + /\bimport\s+.*\bfrom\s+["']react["']/, + /\bimport\s+.*\bfrom\s+["']react-dom["']/, + /\bimport\s+.*\bfrom\s+["']three["']/, + /\bimport\s+.*\bfrom\s+["']next["']/, + /\bimport\s+.*\bfrom\s+["']@react-three\//, + ]; + + const browserApiPatterns = [ + { pattern: /\bwindow\./, name: "window." }, + { pattern: /\bdocument\./, name: "document." }, + { pattern: /\blocalStorage/, name: "localStorage" }, + { pattern: /\bnavigator\./, name: "navigator." }, + ]; + + function isComment(line: string): boolean { + const trimmed = line.trim(); + return ( + trimmed.startsWith("//") || + trimmed.startsWith("*") || + trimmed.startsWith("/*") + ); + } + + function scanFiles(dir: string): Array<{ file: string; path: string }> { + const files: Array<{ file: string; path: string }> = []; + + function scan(currentDir: string) { + const entries = readdirSync(currentDir, { withFileTypes: true }); + for (const entry of entries) { + const fullPath = join(currentDir, entry.name); + if (entry.isDirectory()) { + // Skip __tests__ directory + if (entry.name !== "__tests__") { + scan(fullPath); + } + } else if ( + entry.name.endsWith(".ts") && + !entry.name.endsWith(".test.ts") + ) { + files.push({ + file: entry.name, + path: fullPath, + }); + } + } + } + + scan(dir); + return files; + } + + it("should not import framework-specific code", () => { + const files = scanFiles(coreDir); + const violations: string[] = []; + + for (const { path } of files) { + const content = readFileSync(path, "utf-8"); + const lines = content.split("\n"); + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + for (const pattern of forbiddenImports) { + if (pattern.test(line)) { + const relPath = relative( + join(coreDir, ".."), + path, + ); + violations.push(`${relPath}:${i + 1}`); + } + } + } + } + + expect(violations, violations.join("\n")).toHaveLength(0); + }); + + it("should not use browser APIs without guards", () => { + const files = scanFiles(coreDir); + const violations: string[] = []; + + for (const { path } of files) { + const content = readFileSync(path, "utf-8"); + const lines = content.split("\n"); + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + + // Skip comments + if (isComment(line)) { + continue; + } + + for (const { pattern, name } of browserApiPatterns) { + if (pattern.test(line)) { + const relPath = relative( + join(coreDir, ".."), + path, + ); + violations.push( + `${relPath}:${i + 1} (${name})`, + ); + } + } + } + } + + expect(violations, violations.join("\n")).toHaveLength(0); + }); + + it("should guard process.env with typeof check", () => { + const files = scanFiles(coreDir); + const violations: string[] = []; + + for (const { path } of files) { + const content = readFileSync(path, "utf-8"); + const lines = content.split("\n"); + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + + // Skip comments + if (isComment(line)) { + continue; + } + + // Check if line contains process.env + if (line.includes("process.env")) { + // Check if the same line also has typeof process guard + if (!line.includes("typeof process")) { + const relPath = relative( + join(coreDir, ".."), + path, + ); + violations.push(`${relPath}:${i + 1}`); + } + } + } + } + + expect(violations, violations.join("\n")).toHaveLength(0); + }); +}); diff --git a/packages/engine-core/src/__tests__/dialogueTrees.test.ts b/packages/engine-core/src/__tests__/dialogueTrees.test.ts new file mode 100644 index 0000000..9a90d55 --- /dev/null +++ b/packages/engine-core/src/__tests__/dialogueTrees.test.ts @@ -0,0 +1,700 @@ +import { describe, it, expect, vi, afterEach, beforeEach } from "vitest"; +import { + act, + cond, + createGameRuntime, + dialogue, + getDialogueState, + getInputLockState, + getInventoryState, + getWorldState, + useDialogStore, + useDialogueStore, + type DialogueDefinition, + type DialogueNode, + type GameEvent, + type GameRuntime, +} from "../index"; +import { HeadlessClock } from "../ports/headlessClock"; +import { flush, makeItem, makeScene, resetStores } from "./sequencerHarness"; + +let rt: GameRuntime; +let clock: HeadlessClock; +let events: GameEvent[]; + +function boot(defs: DialogueDefinition[]) { + clock = new HeadlessClock(); + rt = createGameRuntime({ + scenes: [makeScene("dt-a")], + items: [makeItem("dt-key")], + dialogues: defs, + clock, + instantWalk: true, + }); + rt.executeCommand({ type: "scene:set", sceneId: "dt-a" }); + events = []; + for (const t of [ + "dialogue:started", + "dialogue:nodeEntered", + "dialogue:choiceMade", + "dialogue:ended", + "dialog:triggered", + "dialog:dismissed", + "input:lockChanged", + "custom", + ] as const) + rt.on(t, (e) => events.push(e as GameEvent)); +} + +const def = (id: string, start: string, ...nodes: DialogueNode[]) => + dialogue.define(id, start, ...nodes); +const n = dialogue.node; +const c = dialogue.choice; + +const start = async (id: string) => { + rt.executeCommand({ type: "dialogue:start", dialogueId: id }); + await flush(); +}; +const choose = async (index: number) => { + rt.executeCommand({ type: "dialogue:choose", index }); + await flush(); +}; +const dismiss = async () => { + rt.executeCommand({ type: "dialog:dismiss" }); + await flush(); +}; +const ofType = (t: string) => events.filter((e) => e.type === t); +const ended = () => ofType("dialogue:ended") as Array<{ dialogueId: string; reason: string }>; +const nodesEntered = () => + ofType("dialogue:nodeEntered").map((e) => (e as { nodeId: string }).nodeId); +const customNames = () => ofType("custom").map((e) => (e as { name: string }).name); +const store = () => getDialogueState(); +const idx = () => store().choices.map((x) => x.index); +const quiet = () => vi.spyOn(console, "warn").mockImplementation(() => {}); + +beforeEach(() => { + resetStores(); + useDialogueStore.getState().clear(); +}); +afterEach(() => { + rt?.dispose(); + resetStores(); + useDialogueStore.getState().clear(); + vi.restoreAllMocks(); +}); + +describe("dialogos lineales", () => { + const linear = def( + "lin", + "a", + n("a", { line: "l.a", speaker: "npc", next: "b" }), + n("b", { line: "l.b", next: "c" }), + n("c", { line: "l.c" }), + ); + + it("recorre 3 nodos avanzando con dialog:dismiss y termina con finished", async () => { + boot([linear]); + await start("lin"); + expect(store().activeDialogueId).toBe("lin"); + expect(store().nodeId).toBe("a"); + expect(useDialogStore.getState().key).toBe("l.a"); + await dismiss(); + expect(store().nodeId).toBe("b"); + expect(useDialogStore.getState().key).toBe("l.b"); + await dismiss(); + expect(store().nodeId).toBe("c"); + await dismiss(); + expect(store().activeDialogueId).toBeNull(); + expect(nodesEntered()).toEqual(["a", "b", "c"]); + expect(ended()).toEqual([{ type: "dialogue:ended", dialogueId: "lin", reason: "finished" }]); + }); + + it("emite started antes que nodeEntered y el speaker llega al bocadillo", async () => { + boot([linear]); + await start("lin"); + expect(events.map((e) => e.type).slice(0, 2)).toEqual([ + "dialogue:started", + "input:lockChanged", + ]); + expect(nodesEntered()).toEqual(["a"]); + expect(useDialogStore.getState().speaker).toBe("npc"); + expect(store().speaker).toBe("npc"); + expect(store().lineKey).toBe("l.a"); + const trig = ofType("dialog:triggered")[0] as { speaker?: string }; + expect(trig.speaker).toBe("npc"); + }); + + it("fin por falta de next: el ultimo cierre termina el dialogo y deja el store limpio", async () => { + boot([def("one", "x", n("x", { line: "l.x" }))]); + await start("one"); + expect(store().activeDialogueId).toBe("one"); + await dismiss(); + expect(store()).toMatchObject({ activeDialogueId: null, nodeId: null, choices: [] }); + }); + + it("dialogue:advance en nodo sin opciones equivale a cerrar el bocadillo", async () => { + boot([linear]); + await start("lin"); + rt.executeCommand({ type: "dialogue:advance" }); + await flush(); + expect(store().nodeId).toBe("b"); + expect(ofType("dialog:dismissed")).toHaveLength(1); + }); + + it("nodo solo-do: ejecuta efectos y encadena sin esperar al jugador", async () => { + boot([ + def( + "doonly", + "a", + n("a", { do: [act.setFlag("f1")], next: "b" }), + n("b", { do: [act.emit("hecho")] }), + ), + ]); + await start("doonly"); + expect(getWorldState().flags.f1).toBe(true); + expect(customNames()).toEqual(["hecho"]); + expect(ended()[0]!.reason).toBe("finished"); + expect(store().activeDialogueId).toBeNull(); + }); +}); + +describe("opciones", () => { + const branched = def( + "br", + "q", + n("q", { + line: "q.line", + choices: [c("c.yes", { next: "yes" }), c("c.no", { next: "no" })], + }), + n("yes", { line: "yes.line" }), + n("no", { line: "no.line" }), + ); + + it("ramificado: elige una opcion y sigue por su next", async () => { + boot([branched]); + await start("br"); + expect(store().choices).toEqual([ + { index: 0, textKey: "c.yes" }, + { index: 1, textKey: "c.no" }, + ]); + await choose(1); + expect(store().nodeId).toBe("no"); + expect(useDialogStore.getState().key).toBe("no.line"); + expect(ofType("dialogue:choiceMade")).toEqual([ + { type: "dialogue:choiceMade", dialogueId: "br", nodeId: "q", index: 1 }, + ]); + await dismiss(); + expect(ended()[0]!.reason).toBe("finished"); + }); + + it("con opciones pendientes NO avanza solo", async () => { + boot([branched]); + await start("br"); + await flush(); + expect(store().nodeId).toBe("q"); + expect(ended()).toHaveLength(0); + }); + + it("cerrar el bocadillo con opciones pendientes no avanza", async () => { + boot([branched]); + await start("br"); + await dismiss(); + expect(store().nodeId).toBe("q"); + expect(store().choices).toHaveLength(2); + expect(ended()).toHaveLength(0); + await choose(0); + expect(store().nodeId).toBe("yes"); + }); + + it("opcion con when: oculta si no se cumple, visible si se cumple", async () => { + const d = def( + "wh", + "q", + n("q", { choices: [c("c.a"), c("c.secret", { when: cond.flag("know") })] }), + ); + boot([d]); + await start("wh"); + expect(idx()).toEqual([0]); + rt.executeCommand({ type: "dialogue:end" }); + await flush(); + getWorldState().setFlag("know", true); + await start("wh"); + expect(idx()).toEqual([0, 1]); + }); + + it("el index es estable (posicion original) aunque se oculte una anterior", async () => { + const d = def( + "st", + "q", + n("q", { + choices: [c("c.hidden", { when: cond.flag("nope") }), c("c.b", { next: "b" }), c("c.c")], + }), + n("b", { do: [act.emit("fue-b")] }), + ); + boot([d]); + await start("st"); + expect(store().choices).toEqual([ + { index: 1, textKey: "c.b" }, + { index: 2, textKey: "c.c" }, + ]); + await choose(1); + expect(customNames()).toEqual(["fue-b"]); + }); + + it("choose con indice oculto, inexistente o no numerico avisa y no hace nada", async () => { + const warn = quiet(); + boot([def("iv", "q", n("q", { choices: [c("c.h", { when: cond.flag("nope") }), c("c.ok")] }))]); + await start("iv"); + await choose(0); + await choose(7); + await choose(-1); + await choose(Number.NaN); + expect(warn).toHaveBeenCalledTimes(4); + expect(store().nodeId).toBe("q"); + expect(ofType("dialogue:choiceMade")).toHaveLength(0); + await choose(1); + expect(ended()[0]!.reason).toBe("finished"); + }); + + it("choose sin dialogo activo avisa y no hace nada", async () => { + const warn = quiet(); + boot([]); + await choose(0); + expect(warn).toHaveBeenCalled(); + expect(events).toHaveLength(0); + }); + + it("choose en un nodo sin opciones (esperando cierre) se ignora", async () => { + const warn = quiet(); + boot([def("nc", "a", n("a", { line: "l.a", next: "b" }), n("b", { line: "l.b" }))]); + await start("nc"); + await choose(0); + expect(warn).toHaveBeenCalled(); + expect(store().nodeId).toBe("a"); + }); + + it("dialogue:advance en un nodo con opciones no hace nada", async () => { + boot([branched]); + await start("br"); + rt.executeCommand({ type: "dialogue:advance" }); + await flush(); + expect(store().nodeId).toBe("q"); + expect(ofType("dialog:dismissed")).toHaveLength(0); + expect(useDialogStore.getState().visible).toBe(true); + }); + + it("dialogue:advance sin dialogo activo no hace nada", async () => { + boot([]); + rt.executeCommand({ type: "dialogue:advance" }); + await flush(); + expect(events).toHaveLength(0); + }); + + it("opcion sin next termina el dialogo", async () => { + boot([def("nn", "q", n("q", { choices: [c("c.bye")] }))]); + await start("nn"); + await choose(0); + expect(ended()[0]!.reason).toBe("finished"); + expect(store().activeDialogueId).toBeNull(); + }); + + it("nodo cuyas opciones quedan todas ocultas se trata como nodo sin opciones", async () => { + boot([ + def( + "ah", + "q", + n("q", { line: "l.q", choices: [c("c.h", { when: cond.flag("nope") })], next: "z" }), + n("z", { line: "l.z" }), + ), + ]); + await start("ah"); + expect(store().choices).toEqual([]); + await dismiss(); + expect(store().nodeId).toBe("z"); + }); +}); + +describe("once", () => { + const onceDef = def( + "on", + "q", + n("q", { + choices: [c("c.once", { once: true, next: "q" }), c("c.always", { next: "q" }), c("c.out")], + }), + ); + + it("desaparece al volver al nodo y deja el flag reservado en el estado de mundo", async () => { + boot([onceDef]); + await start("on"); + expect(idx()).toEqual([0, 1, 2]); + await choose(0); + expect(getWorldState().flags["dlg.on.q.0"]).toBe(true); + expect(store().nodeId).toBe("q"); + expect(idx()).toEqual([1, 2]); + await choose(1); + expect(idx()).toEqual([1, 2]); + }); + + it("sigue oculta en una conversacion posterior (el flag persiste)", async () => { + boot([onceDef]); + await start("on"); + await choose(0); + await choose(2); + expect(ended()).toHaveLength(1); + await start("on"); + expect(idx()).toEqual([1, 2]); + }); + + it("la opcion sin once se puede repetir y no deja flag", async () => { + boot([onceDef]); + await start("on"); + await choose(1); + await choose(1); + expect(ofType("dialogue:choiceMade")).toHaveLength(2); + expect(Object.keys(getWorldState().flags)).toEqual([]); + }); +}); + +describe("efectos (do)", () => { + it("do de nodo y de opcion aplican flag e item", async () => { + boot([ + def( + "fx", + "a", + n("a", { + do: [act.setFlag("nodo")], + choices: [ + c("c.take", { do: [act.giveItem("dt-key"), act.setFlag("opcion")], next: "z" }), + ], + }), + n("z", { line: "l.z" }), + ), + ]); + await start("fx"); + expect(getWorldState().flags.nodo).toBe(true); + expect(getWorldState().flags.opcion).toBeUndefined(); + await choose(0); + expect(getWorldState().flags.opcion).toBe(true); + expect(getInventoryState().slots.some((s) => s?.id === "dt-key")).toBe(true); + expect(store().nodeId).toBe("z"); + }); + + it("el do del nodo se ejecuta antes de evaluar las opciones", async () => { + boot([ + def( + "ord", + "a", + n("a", { + do: [act.setFlag("abre")], + choices: [c("c.cond", { when: cond.flag("abre") })], + }), + ), + ]); + await start("ord"); + expect(idx()).toEqual([0]); + }); + + it("el do de nodo con wait espera antes de mostrar la linea", async () => { + boot([ + def( + "wn", + "a", + n("a", { do: [act.wait(100)], line: "l.a", next: "b" }), + n("b", { line: "l.b" }), + ), + ]); + await start("wn"); + expect(useDialogStore.getState().visible).toBe(false); + expect(store().nodeId).toBe("a"); + clock.advance(100); + await flush(); + expect(useDialogStore.getState().key).toBe("l.a"); + }); + + it("el do de opcion con wait retrasa el paso al siguiente nodo", async () => { + boot([ + def( + "wo", + "q", + n("q", { choices: [c("c.go", { do: [act.wait(50), act.emit("listo")], next: "z" })] }), + n("z", { do: [act.emit("en-z")] }), + ), + ]); + await start("wo"); + await choose(0); + expect(customNames()).toEqual([]); + expect(store().choices).toEqual([]); + clock.advance(50); + await flush(); + expect(customNames()).toEqual(["listo", "en-z"]); + }); + + it("un say dentro del do espera su cierre (sin interbloqueo con el guion contenedor)", async () => { + boot([ + def("sy", "a", n("a", { do: [act.say("narra")], next: "b" }), n("b", { do: [act.emit("fin")] })), + ]); + await start("sy"); + expect(useDialogStore.getState().key).toBe("narra"); + expect(customNames()).toEqual([]); + await dismiss(); + expect(customNames()).toEqual(["fin"]); + expect(ended()[0]!.reason).toBe("finished"); + }); +}); + +describe("fin forzado y comandos", () => { + it("dialogue:end termina de inmediato con reason ended y oculta el bocadillo", async () => { + boot([def("fe", "a", n("a", { line: "l.a", next: "b" }), n("b", { line: "l.b" }))]); + await start("fe"); + expect(useDialogStore.getState().visible).toBe(true); + rt.executeCommand({ type: "dialogue:end" }); + await flush(); + expect(ended()).toEqual([{ type: "dialogue:ended", dialogueId: "fe", reason: "ended" }]); + expect(useDialogStore.getState().visible).toBe(false); + expect(store().activeDialogueId).toBeNull(); + expect(nodesEntered()).toEqual(["a"]); + }); + + it("dialogue:end con opciones pendientes tambien termina", async () => { + boot([def("fo", "q", n("q", { line: "l", choices: [c("c.a")] }))]); + await start("fo"); + rt.executeCommand({ type: "dialogue:end" }); + await flush(); + expect(ended()[0]!.reason).toBe("ended"); + expect(store().choices).toEqual([]); + }); + + it("dialogue:end sin dialogo activo no hace nada", async () => { + boot([]); + rt.executeCommand({ type: "dialogue:end" }); + await flush(); + expect(events).toHaveLength(0); + }); + + it("un segundo dialogue:start con uno activo avisa y no hace nada", async () => { + const warn = quiet(); + boot([def("d1", "a", n("a", { line: "l.1" })), def("d2", "a", n("a", { line: "l.2" }))]); + await start("d1"); + await start("d2"); + expect(warn).toHaveBeenCalled(); + expect(store().activeDialogueId).toBe("d1"); + expect(ofType("dialogue:started")).toHaveLength(1); + await dismiss(); + expect(ended().map((e) => e.dialogueId)).toEqual(["d1"]); + }); + + it("se puede iniciar otro dialogo despues de terminar el primero", async () => { + boot([def("d1", "a", n("a")), def("d2", "a", n("a", { line: "l.2" }))]); + await start("d1"); + await start("d2"); + expect(store().activeDialogueId).toBe("d2"); + }); +}); + +describe("dentro de un guion", () => { + it("la accion startDialogue espera al fin y el guion continua", async () => { + boot([ + def("sc", "a", n("a", { line: "l.a", choices: [c("c.ok", { do: [act.emit("opcion")] })] })), + ]); + const run = rt.runScript([act.emit("antes"), act.startDialogue("sc"), act.emit("despues")]); + await flush(); + expect(customNames()).toEqual(["antes"]); + await choose(0); + expect(customNames()).toEqual(["antes", "opcion", "despues"]); + expect(await run.done).toBe("finished"); + }); + + it("los do con wait funcionan dentro de un guion (no hay interbloqueo con la cola)", async () => { + boot([def("sw", "a", n("a", { do: [act.wait(10), act.emit("do")] }))]); + const run = rt.runScript([act.startDialogue("sw"), act.emit("fin")]); + await flush(); + clock.advance(10); + expect(await run.done).toBe("finished"); + expect(customNames()).toEqual(["do", "fin"]); + }); + + it("cancelar el guion a mitad cierra el dialogo con reason cancelled y limpia", async () => { + boot([def("cx", "q", n("q", { line: "l.q", choices: [c("c.a")] }))]); + const run = rt.runScript([act.startDialogue("cx"), act.emit("no-debe")]); + await flush(); + expect(store().activeDialogueId).toBe("cx"); + rt.executeCommand({ type: "script:cancelAll" }); + await flush(); + expect(await run.done).toBe("cancelled"); + expect(ended()).toEqual([{ type: "dialogue:ended", dialogueId: "cx", reason: "cancelled" }]); + expect(store().activeDialogueId).toBeNull(); + expect(useDialogStore.getState().visible).toBe(false); + expect(customNames()).toEqual([]); + }); + + it("interrupt con otro guion cancela el dialogo en curso", async () => { + boot([def("ix", "a", n("a", { line: "l.a" }))]); + rt.runScript([act.startDialogue("ix")]); + await flush(); + rt.runScript([act.emit("otro")], { interrupt: true }); + await flush(); + expect(ended()[0]!.reason).toBe("cancelled"); + expect(customNames()).toEqual(["otro"]); + }); + + it("cancelar durante el do de un nodo (wait) corta sin seguir", async () => { + boot([ + def( + "cw", + "a", + n("a", { do: [act.wait(100), act.emit("tarde")], next: "b" }), + n("b", { do: [act.emit("b")] }), + ), + ]); + rt.runScript([act.startDialogue("cw")]); + await flush(); + rt.executeCommand({ type: "script:cancelAll" }); + clock.advance(100); + await flush(); + expect(customNames()).toEqual([]); + expect(ended()[0]!.reason).toBe("cancelled"); + }); +}); + +describe("robustez", () => { + it("dialogo no registrado: aviso y fin finished, sin lanzar", async () => { + const warn = quiet(); + boot([]); + await start("nada"); + expect(warn).toHaveBeenCalled(); + expect(ended()).toEqual([{ type: "dialogue:ended", dialogueId: "nada", reason: "finished" }]); + expect(store().activeDialogueId).toBeNull(); + expect(getInputLockState().inputLocked).toBe(false); + }); + + it("start apuntando a un nodo inexistente: aviso y fin", async () => { + const warn = quiet(); + boot([def("bad", "fantasma", n("a"))]); + await start("bad"); + expect(warn).toHaveBeenCalled(); + expect(ended()[0]!.reason).toBe("finished"); + }); + + it("next a un nodo inexistente: aviso y fin tras el nodo valido", async () => { + const warn = quiet(); + boot([def("nx", "a", n("a", { line: "l.a", next: "fantasma" }))]); + await start("nx"); + await dismiss(); + expect(warn).toHaveBeenCalled(); + expect(ended()[0]!.reason).toBe("finished"); + expect(store().activeDialogueId).toBeNull(); + }); + + it("next de una opcion a un nodo inexistente: aviso y fin", async () => { + const warn = quiet(); + boot([def("cn", "q", n("q", { choices: [c("c.a", { next: "fantasma" })] }))]); + await start("cn"); + await choose(0); + expect(warn).toHaveBeenCalled(); + expect(ended()[0]!.reason).toBe("finished"); + }); + + it("bucle infinito de nodos sin linea: se corta con aviso", async () => { + const warn = quiet(); + boot([def("loop", "a", n("a", { next: "b" }), n("b", { next: "a" }))]); + await start("loop"); + await flush(5000); // 500 nodos encadenados = muchas microtareas + expect(warn).toHaveBeenCalled(); + expect(nodesEntered().length).toBe(500); + expect(ended()[0]!.reason).toBe("finished"); + expect(store().activeDialogueId).toBeNull(); + }); + + it("un dialogo largo con entradas del jugador no dispara la proteccion", async () => { + const nodes: DialogueNode[] = []; + for (let i = 0; i < 600; i++) { + nodes.push(n(`n${i}`, { line: "l", ...(i < 599 ? { next: `n${i + 1}` } : {}) })); + } + boot([def("long", "n0", ...nodes)]); + await start("long"); + for (let i = 0; i < 599; i++) await dismiss(); + expect(store().nodeId).toBe("n599"); + }); +}); + +describe("bloqueo de entrada", () => { + it("activo durante el dialogo y liberado al final", async () => { + boot([def("lk", "a", n("a", { line: "l.a" }))]); + expect(getInputLockState().inputLocked).toBe(false); + await start("lk"); + expect(getInputLockState().inputLocked).toBe(true); + await dismiss(); + expect(getInputLockState().inputLocked).toBe(false); + expect(ofType("input:lockChanged").map((e) => (e as { locked: boolean }).locked)).toEqual([ + true, + false, + ]); + }); + + it("liberado tambien con dialogue:end y al cancelar", async () => { + boot([def("lk", "a", n("a", { line: "l.a" }))]); + await start("lk"); + rt.executeCommand({ type: "dialogue:end" }); + await flush(); + expect(getInputLockState().inputLocked).toBe(false); + rt.runScript([act.startDialogue("lk")]); + await flush(); + expect(getInputLockState().inputLocked).toBe(true); + rt.executeCommand({ type: "script:cancelAll" }); + await flush(); + expect(getInputLockState().inputLocked).toBe(false); + }); + + it("no libera un bloqueo que el guion habia puesto antes", async () => { + boot([def("lk", "a", n("a", { line: "l.a" }))]); + rt.runScript([act.lockInput(true), act.startDialogue("lk"), act.wait(5)]); + await flush(); + await dismiss(); + expect(getInputLockState().inputLocked).toBe(true); + clock.advance(5); + await flush(); + expect(getInputLockState().inputLocked).toBe(false); + }); +}); + +describe("registro, dispose y constructores", () => { + it("getDialogues devuelve los registrados por config", () => { + const a = def("g1", "a", n("a")); + const b = def("g2", "a", n("a")); + boot([a, b]); + expect(rt.getDialogues().g1).toBe(a); + expect(rt.getDialogues().g2).toBe(b); + }); + + it("dispose con dialogo activo deja el store limpio y el bloqueo liberado", async () => { + boot([def("dp", "q", n("q", { line: "l", choices: [c("c.a")] }))]); + await start("dp"); + expect(store().activeDialogueId).toBe("dp"); + const seen: GameEvent[] = []; + rt.on("dialogue:ended", (e) => seen.push(e)); + rt.dispose(); + expect(store().activeDialogueId).toBeNull(); + expect(store().choices).toEqual([]); + expect(seen).toEqual([{ type: "dialogue:ended", dialogueId: "dp", reason: "cancelled" }]); + await flush(); + expect(getInputLockState().inputLocked).toBe(false); + }); + + it("los constructores producen datos planos equivalentes", () => { + expect(dialogue.define("x", "a", dialogue.node("a", { line: "l" }))).toEqual({ + id: "x", + start: "a", + nodes: [{ id: "a", line: "l" }], + }); + expect(dialogue.choice("t", { once: true })).toEqual({ text: "t", once: true }); + }); + + it("el bocadillo de una frase sigue funcionando fuera de un dialogo", async () => { + boot([]); + rt.executeCommand({ type: "dialog:trigger", dialogKey: "suelto" }); + expect(useDialogStore.getState().visible).toBe(true); + await dismiss(); + expect(useDialogStore.getState().visible).toBe(false); + expect(store().activeDialogueId).toBeNull(); + }); +}); diff --git a/packages/engine-core/src/__tests__/fixtures/miniAdventure.ts b/packages/engine-core/src/__tests__/fixtures/miniAdventure.ts new file mode 100644 index 0000000..aae55e9 --- /dev/null +++ b/packages/engine-core/src/__tests__/fixtures/miniAdventure.ts @@ -0,0 +1,268 @@ +import { + act, + branch, + cond, + dialogue, + otherwise, + type GameContent, + type GameItemConfig, + type GameSceneConfig, + type GameSceneInteractionFull, + type PlacedSceneItem, +} from "../../index"; + +/** + * "El faro": mini-aventura escrita solo con datos. + * + * Escenas : beach (inicial) -> cove -> lighthouse (final) + * NPCs : fisherman (beach), keeper (cove) + * Items : rusty-key, lens, lamp-frame, lamp, fish + * + * Puzzles encadenados: + * 1. Recoger y usar : rusty-key (suelo de beach) abre `chest` (useItem + flag) y da `lens`. + * 2. Conversacion : mirar `map` pone `map.seen`; solo entonces el pescador ofrece (opcion + * con `when` y `once`) el `lamp-frame`. + * 3. Combinar : lens + lamp-frame = lamp. + * 4. Intercambio/final : entregar `lamp` al guardian pone `keeper.lit`, que abre la transicion + * `to-lighthouse`; el `onEnter` del faro cierra el juego (`game.finished`). + * + * Extras: transicion bloqueada con `blocked`, `onEnter` solo la primera vez (flag `intro.done`), + * `initialItems` con `when` (fish solo si ya se visito beach), `useItemDefault`, `call`. + */ + +const interaction = (id: string): GameSceneInteractionFull => ({ + id, + kind: "drop-target", + position: [3, 0, 3], + halfSize: [0.5, 0.5, 0.5], + label: `${id}.label`, + dialogKeys: { hit: `${id}.hit`, miss: `${id}.miss` }, +}); + +const placed = (id: string, itemId: string, interactionId: string, sceneId: string): PlacedSceneItem => ({ + id, + itemId, + interactionId, + name: `item.${itemId}`, + spriteUrl: `/${itemId}.png`, + worldPosition: [3, 0, 3], + canPickup: true, + sceneId, +}); + +const item = (id: string, extra: Partial = {}): GameItemConfig => ({ + id, + name: `item.${id}`, + spriteUrl: `/${id}.png`, + interactionRules: {}, + defaultRule: { outcome: "return" }, + ...extra, +}); + +const base = (id: string): Pick< + GameSceneConfig, + "id" | "label" | "background" | "playerSpawn" | "ground" | "walls" +> => ({ + id, + label: `scene.${id}`, + background: `/${id}.png`, + playerSpawn: [0, 0, 0], + ground: { minX: -8, maxX: 8, minZ: -8, maxZ: 8, y: 0 }, + walls: [], +}); + +const zone = [0.5, 1, 0.5] as [number, number, number]; + +const beach: GameSceneConfig = { + ...base("beach"), + interactions: [interaction("sand")], + initialItems: [{ item: placed("key-on-sand", "rusty-key", "sand", "beach") }], + // Solo la primera vez: el flag, no `visited` (al evaluarse la escena ya cuenta como visitada). + onEnter: [branch(cond.not(cond.flag("intro.done")), act.say("beach.intro"), act.setFlag("intro.done"))], + hotspots: [ + { + id: "chest", + label: "chest.label", + position: [-3, 0, 2], + halfSize: zone, + approach: [-2, 0, 2], + verbs: { + look: [otherwise(act.say("chest.look"))], + use: [ + branch(cond.flag("chest.open"), act.say("chest.empty")), + otherwise(act.say("chest.locked")), + ], + }, + useItem: { + "rusty-key": [ + branch(cond.flag("chest.open"), act.say("chest.alreadyOpen")), + otherwise( + act.say("chest.unlock"), + act.removeItem("rusty-key"), + act.setFlag("chest.open"), + act.giveItem("lens"), + ), + ], + }, + useItemDefault: [otherwise(act.say("chest.nothing"))], + }, + { + id: "map", + label: "map.label", + position: [0, 0, -3], + halfSize: zone, + verbs: { look: [otherwise(act.say("map.look"), act.setFlag("map.seen"))] }, + }, + ], + npcs: [ + { + id: "fisherman", + name: "fisherman.name", + characterId: "fisherman", + position: [3, 0, -2], + dialogueId: "fisher-talk", + }, + ], + transitions: [ + { + id: "to-cove", + kind: "collision", + targetSceneId: "cove", + position: [7, 0, 0], + halfSize: [0.5, 1, 2], + }, + ], +}; + +const cove: GameSceneConfig = { + ...base("cove"), + interactions: [interaction("rocks")], + // `when`: el pescado solo aparece si ya se paso por la playa. + initialItems: [ + { item: placed("fish-on-rocks", "fish", "rocks", "cove"), when: cond.visited("beach") }, + ], + hotspots: [], + npcs: [ + { + id: "keeper", + name: "keeper.name", + characterId: "keeper", + position: [2, 0, 2], + dialogueId: "keeper-talk", + useItem: { + lamp: [ + otherwise( + act.say("keeper.thanks", "keeper"), + act.removeItem("lamp"), + act.setFlag("keeper.lit"), + ), + ], + }, + verbs: { look: [otherwise(act.say("keeper.look"))] }, + }, + ], + transitions: [ + { + id: "to-beach", + kind: "collision", + targetSceneId: "beach", + position: [-7, 0, 0], + halfSize: [0.5, 1, 2], + }, + { + id: "to-lighthouse", + kind: "collision", + targetSceneId: "lighthouse", + position: [0, 0, 7], + halfSize: [2, 1, 0.5], + when: cond.flag("keeper.lit"), + blocked: [act.say("lighthouse.locked")], + }, + ], +}; + +const lighthouse: GameSceneConfig = { + ...base("lighthouse"), + interactions: [], + onEnter: [ + branch( + cond.flag("keeper.lit"), + act.say("lighthouse.ending"), + act.call("credits", { ending: "good" }), + act.setFlag("game.finished"), + ), + ], + hotspots: [ + { + id: "beacon", + label: "beacon.label", + position: [0, 0, 0], + halfSize: zone, + verbs: { + look: [ + branch(cond.flag("game.finished"), act.say("beacon.on")), + otherwise(act.say("beacon.off")), + ], + }, + }, + ], +}; + +const items: GameItemConfig[] = [ + item("rusty-key"), + item("lens", { + combine: { + "lamp-frame": [ + otherwise( + act.say("combine.lamp"), + act.removeItem("lens"), + act.removeItem("lamp-frame"), + act.giveItem("lamp"), + ), + ], + }, + }), + item("lamp-frame"), + item("lamp"), + item("fish"), +]; + +const dialogues = [ + dialogue.define( + "fisher-talk", + "root", + dialogue.node("root", { + speaker: "fisherman", + line: "fisher.hello", + choices: [ + // 0: la pista solo si ya se miro el mapa; una sola vez. + dialogue.choice("ask.frame", { + when: cond.flag("map.seen"), + once: true, + do: [act.say("fisher.frame", "fisherman"), act.giveItem("lamp-frame")], + next: "root", + }), + // 1: saludo, solo la primera vez. + dialogue.choice("ask.weather", { once: true, do: [act.say("fisher.weather", "fisherman")], next: "root" }), + // 2: despedida (sin next: termina la conversacion). + dialogue.choice("bye"), + ], + }), + ), + dialogue.define( + "keeper-talk", + "root", + dialogue.node("root", { + speaker: "keeper", + line: "keeper.hello", + choices: [dialogue.choice("ask.light", { do: [act.say("keeper.light", "keeper")], next: "root" }), dialogue.choice("bye")], + }), + ), +]; + +export const miniAdventure: GameContent = { + scenes: [beach, cove, lighthouse], + items, + dialogues, + handlers: new Set(["credits"]), +}; diff --git a/packages/engine-core/src/__tests__/gameRuntime.test.ts b/packages/engine-core/src/__tests__/gameRuntime.test.ts new file mode 100644 index 0000000..87ca52d --- /dev/null +++ b/packages/engine-core/src/__tests__/gameRuntime.test.ts @@ -0,0 +1,337 @@ +import { describe, it, expect, vi, afterEach } from "vitest"; +import { + createGameRuntime, + getGameRuntime, + getGameState, + getGameActions, + registerScene, + registerItem, + registerRule, + toRuntimeScene, + useSceneStore, + type GameRuntime, + type GameSceneConfig, + type GameItemConfig, + type GameRuleConfig, +} from "../index"; + +function makeScene(id: string, extra: Partial = {}): GameSceneConfig { + return { + id, + label: `Scene ${id}`, + background: "/bg.png", + playerSpawn: [0, 0, 0], + ground: { minX: -5, maxX: 5, minZ: -5, maxZ: 5, y: 0 }, + walls: [], + interactions: [], + ...extra, + }; +} + +function makeItem(id: string): GameItemConfig { + return { + id, + name: id, + spriteUrl: "/i.png", + interactionRules: {}, + defaultRule: { outcome: "return" }, + }; +} + +const makeRule = (key: string): GameRuleConfig => ({ key, phrases: ["hola"] }); + +let rt: GameRuntime | null = null; +afterEach(() => { + rt?.dispose(); + rt = null; + vi.restoreAllMocks(); +}); + +describe("registry", () => { + it("createGameRuntime devuelve escenas/items/rules registrados", () => { + rt = createGameRuntime({ + scenes: [makeScene("rt-a")], + items: [makeItem("rt-item")], + rules: [makeRule("rt.rule")], + }); + expect(rt.getScenes()["rt-a"]).toMatchObject({ id: "rt-a" }); + expect(rt.getItems()["rt-item"]).toMatchObject({ id: "rt-item" }); + expect(rt.getRules()["rt.rule"]).toMatchObject({ key: "rt.rule" }); + }); + + it("re-registrar sobreescribe por id/key", () => { + registerScene(makeScene("rt-over", { label: "v1" })); + registerScene(makeScene("rt-over", { label: "v2" })); + registerItem({ ...makeItem("rt-over-i"), name: "v1" }); + registerItem({ ...makeItem("rt-over-i"), name: "v2" }); + registerRule({ key: "rt.over", phrases: ["v1"] }); + registerRule({ key: "rt.over", phrases: ["v2"] }); + rt = createGameRuntime(); + expect(rt.getScenes()["rt-over"]!.label).toBe("v2"); + expect(rt.getItems()["rt-over-i"]!.name).toBe("v2"); + expect(rt.getRules()["rt.over"]!.phrases).toEqual(["v2"]); + }); + + it("toRuntimeScene conserva transitions y music", () => { + const cfg = makeScene("rt-conv", { + music: { trackUrl: "/m.mp3" }, + transitions: [ + { id: "t", kind: "collision", targetSceneId: "x", position: [0, 0, 0], halfSize: [1, 1, 1] }, + ], + }); + const scene = toRuntimeScene(cfg); + expect(scene.music).toEqual({ trackUrl: "/m.mp3" }); + expect(scene.transitions).toHaveLength(1); + }); +}); + +describe("scene commands", () => { + it("scene:set conserva transitions y music en el store", () => { + rt = createGameRuntime({ + scenes: [ + makeScene("rt-full", { + music: { trackUrl: "/m.mp3", persistAcrossScenes: true }, + transitions: [ + { id: "t1", kind: "collision", targetSceneId: "rt-b", position: [1, 0, 1], halfSize: [1, 1, 1] }, + ], + }), + ], + }); + rt.executeCommand({ type: "scene:set", sceneId: "rt-full" }); + const { scene, sceneId } = useSceneStore.getState(); + expect(sceneId).toBe("rt-full"); + expect(scene.music).toEqual({ trackUrl: "/m.mp3", persistAcrossScenes: true }); + expect(scene.transitions?.map((t) => t.id)).toEqual(["t1"]); + }); + + it("scene:set emite scene:changed", () => { + rt = createGameRuntime({ scenes: [makeScene("rt-ev")] }); + const handler = vi.fn(); + rt.on("scene:changed", handler); + rt.executeCommand({ type: "scene:set", sceneId: "rt-ev" }); + expect(handler).toHaveBeenCalledTimes(1); + expect(handler.mock.calls[0]![0]).toMatchObject({ sceneId: "rt-ev" }); + }); + + it("scene:set con escena no registrada hace warn y no cambia estado", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + rt = createGameRuntime({ scenes: [makeScene("rt-keep")] }); + rt.executeCommand({ type: "scene:set", sceneId: "rt-keep" }); + rt.executeCommand({ type: "scene:set", sceneId: "no-existe" }); + expect(warn).toHaveBeenCalled(); + expect(getGameState().sceneId).toBe("rt-keep"); + }); + + it("scene:respawn incrementa respawnSignal", () => { + rt = createGameRuntime(); + const before = getGameState().respawnSignal; + rt.executeCommand({ type: "scene:respawn" }); + expect(getGameState().respawnSignal).toBe(before + 1); + }); + + it("player:move actualiza la posición", () => { + rt = createGameRuntime(); + rt.executeCommand({ type: "player:move", position: [2, 0, 3] }); + expect(getGameState().playerPosition).toEqual([2, 0, 3]); + }); +}); + +describe("transition commands", () => { + const scenes = () => [ + makeScene("rt-from", { + transitions: [ + { id: "go", kind: "collision", targetSceneId: "rt-to", position: [3, 0, 3], halfSize: [1, 1, 1] }, + { id: "bad", kind: "collision", targetSceneId: "rt-missing", position: [3, 0, 3], halfSize: [1, 1, 1] }, + ], + }), + makeScene("rt-to"), + ]; + + it("transition:activate cambia de escena y emite started + completed", () => { + rt = createGameRuntime({ scenes: scenes() }); + rt.executeCommand({ type: "scene:set", sceneId: "rt-from" }); + const started = vi.fn(); + const completed = vi.fn(); + rt.on("transition:started", started); + rt.on("transition:completed", completed); + rt.executeCommand({ type: "transition:activate", transitionId: "go" }); + expect(getGameState().sceneId).toBe("rt-to"); + expect(started).toHaveBeenCalledWith({ type: "transition:started", transitionId: "go" }); + expect(completed).toHaveBeenCalledWith({ + type: "transition:completed", + fromSceneId: "rt-from", + toSceneId: "rt-to", + }); + }); + + it("transition:activate desconocida hace warn y no cambia escena", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + rt = createGameRuntime({ scenes: scenes() }); + rt.executeCommand({ type: "scene:set", sceneId: "rt-from" }); + rt.executeCommand({ type: "transition:activate", transitionId: "nope" }); + expect(warn).toHaveBeenCalled(); + expect(getGameState().sceneId).toBe("rt-from"); + }); + + it("transition:activate a escena no registrada emite started pero no completed", () => { + vi.spyOn(console, "warn").mockImplementation(() => {}); + rt = createGameRuntime({ scenes: scenes() }); + rt.executeCommand({ type: "scene:set", sceneId: "rt-from" }); + const started = vi.fn(); + const completed = vi.fn(); + rt.on("transition:started", started); + rt.on("transition:completed", completed); + rt.executeCommand({ type: "transition:activate", transitionId: "bad" }); + expect(started).toHaveBeenCalledTimes(1); + expect(completed).not.toHaveBeenCalled(); + expect(getGameState().sceneId).toBe("rt-from"); + }); +}); + +describe("player:walkTo", () => { + it("destino alcanzable activa playerWalkingState y emite walkStarted", () => { + rt = createGameRuntime({ scenes: [makeScene("rt-walk")] }); + rt.executeCommand({ type: "scene:set", sceneId: "rt-walk" }); + useSceneStore.getState().setPlayerWalkingState(null); + const started = vi.fn(); + rt.on("player:walkStarted", started); + rt.executeCommand({ type: "player:walkTo", position: [3, 0, 3] }); + const walking = useSceneStore.getState().playerWalkingState; + expect(walking?.isActive).toBe(true); + expect(walking!.pathPoints.length).toBeGreaterThanOrEqual(2); + expect(walking!.targetPosition).toEqual([3, 0, 3]); + expect(started).toHaveBeenCalledTimes(1); + }); + + it("destino inalcanzable emite walkAborted y no usa console.log", () => { + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + // Un bloque con colisión que cubre todo el suelo deja al jugador sin ruta. + const blocker = { + id: "blocker", + position: [0, 0, 0], + halfSize: [20, 1, 20], + hasCollision: true, + } as unknown as GameSceneConfig["interactions"][number]; + rt = createGameRuntime({ scenes: [makeScene("rt-walk2", { interactions: [blocker] })] }); + rt.executeCommand({ type: "scene:set", sceneId: "rt-walk2" }); + useSceneStore.getState().setPlayerWalkingState(null); + const aborted = vi.fn(); + rt.on("player:walkAborted", aborted); + rt.executeCommand({ type: "player:walkTo", position: [99, 0, 99] }); + expect(aborted).toHaveBeenCalledWith({ type: "player:walkAborted", reason: "unreachable" }); + expect(useSceneStore.getState().playerWalkingState).toBeNull(); + expect(log).not.toHaveBeenCalled(); + }); +}); + +describe("dialog / inventory commands", () => { + it("dialog:trigger sin adapter no lanza y emite el evento", () => { + rt = createGameRuntime({ rules: [makeRule("rt.dlg")] }); + const handler = vi.fn(); + rt.on("dialog:triggered", handler); + expect(() => rt!.executeCommand({ type: "dialog:trigger", dialogKey: "rt.dlg" })).not.toThrow(); + expect(handler).toHaveBeenCalledWith({ + type: "dialog:triggered", + text: "hola", + dialogKey: "rt.dlg", + source: "command", + }); + }); + + it("dialog:trigger con clave sin regla usa la clave como texto y llama al adapter", () => { + const adapter = { show: vi.fn(), hide: vi.fn() }; + rt = createGameRuntime({ dialogAdapter: adapter }); + rt.executeCommand({ type: "dialog:trigger", dialogKey: "rt.sin.regla" }); + expect(adapter.show).toHaveBeenCalledWith("rt.sin.regla", "rt.sin.regla"); + }); + + it("dialog:dismiss incluye la clave activa y llama a hide", () => { + const adapter = { show: vi.fn(), hide: vi.fn() }; + rt = createGameRuntime({ dialogAdapter: adapter }); + const handler = vi.fn(); + rt.on("dialog:dismissed", handler); + rt.executeCommand({ type: "dialog:trigger", dialogKey: "k" }); + rt.executeCommand({ type: "dialog:dismiss" }); + expect(adapter.hide).toHaveBeenCalledTimes(1); + expect(handler).toHaveBeenCalledWith({ type: "dialog:dismissed", dialogKey: "k" }); + }); + + it("inventory:toggle delega en el adapter y es no-op sin él", () => { + const adapter = { toggle: vi.fn(), isOpen: () => false }; + rt = createGameRuntime({ inventoryAdapter: adapter }); + rt.executeCommand({ type: "inventory:toggle" }); + expect(adapter.toggle).toHaveBeenCalledTimes(1); + rt.dispose(); + rt = createGameRuntime(); + expect(() => rt!.executeCommand({ type: "inventory:toggle" })).not.toThrow(); + }); +}); + +describe("accessors, bus y dispose", () => { + it("getGameState / getGameActions.setScene funcionan sin hooks", () => { + registerScene(makeScene("rt-acc")); + getGameActions().setScene("rt-acc"); + expect(getGameState().sceneId).toBe("rt-acc"); + }); + + it("getGameActions.setScene conserva transitions y music", () => { + registerScene( + makeScene("rt-acc2", { + music: { trackUrl: "/x.mp3" }, + transitions: [ + { id: "q", kind: "collision", targetSceneId: "a", position: [0, 0, 0], halfSize: [1, 1, 1] }, + ], + }), + ); + getGameActions().setScene("rt-acc2"); + const { scene } = getGameState(); + expect(scene.music?.trackUrl).toBe("/x.mp3"); + expect(scene.transitions).toHaveLength(1); + }); + + it("getGameActions.setScene con escena no registrada hace warn", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + getGameActions().setScene("rt-ghost"); + expect(warn).toHaveBeenCalled(); + }); + + it("emit y on funcionan, y unsubscribe corta la suscripción", () => { + rt = createGameRuntime(); + const handler = vi.fn(); + const off = rt.on("dialog:dismissed", handler); + rt.emit({ type: "dialog:dismissed" }); + off(); + rt.emit({ type: "dialog:dismissed" }); + expect(handler).toHaveBeenCalledTimes(1); + }); + + it("getGameRuntime devuelve el handle activo", () => { + rt = createGameRuntime(); + expect(getGameRuntime()).toBe(rt); + }); + + it("dispose limpia bus, comandos y singleton", () => { + vi.spyOn(console, "warn").mockImplementation(() => {}); + rt = createGameRuntime({ scenes: [makeScene("rt-disp")] }); + const handler = vi.fn(); + rt.on("scene:changed", handler); + rt.dispose(); + expect(getGameRuntime()).toBeNull(); + // comandos limpiados: ya no cambia de escena + const before = getGameState().sceneId; + rt.executeCommand({ type: "scene:set", sceneId: "rt-disp" }); + expect(getGameState().sceneId).toBe(before); + // emisor del store desactivado y bus vacío + useSceneStore.getState().setScene("rt-disp", toRuntimeScene(makeScene("rt-disp"))); + expect(handler).not.toHaveBeenCalled(); + rt = null; + }); + + it("dispose de un runtime antiguo no borra el singleton del nuevo", () => { + const first = createGameRuntime(); + const second = createGameRuntime(); + first.dispose(); + expect(getGameRuntime()).toBe(second); + rt = second; + }); +}); diff --git a/packages/engine-core/src/__tests__/gameRuntimePlayerStop.test.ts b/packages/engine-core/src/__tests__/gameRuntimePlayerStop.test.ts new file mode 100644 index 0000000..da615cc --- /dev/null +++ b/packages/engine-core/src/__tests__/gameRuntimePlayerStop.test.ts @@ -0,0 +1,82 @@ +import { describe, it, expect, vi, afterEach } from "vitest"; +import { + createGameRuntime, + registerScene, + useSceneStore, + type GameRuntime, + type GameSceneConfig, +} from "../index"; + +function makeScene(id: string, extra: Partial = {}): GameSceneConfig { + return { + id, + label: `Scene ${id}`, + background: "/bg.png", + playerSpawn: [0, 0, 0], + ground: { minX: -5, maxX: 5, minZ: -5, maxZ: 5, y: 0 }, + walls: [], + interactions: [], + ...extra, + }; +} + +let rt: GameRuntime | null = null; +afterEach(() => { + rt?.dispose(); + rt = null; + vi.restoreAllMocks(); +}); + +describe("player:stop", () => { + it("tras player:walkTo a destino alcanzable, player:stop deja playerWalkingState inactivo o nulo", () => { + rt = createGameRuntime({ scenes: [makeScene("rt-stop-1")] }); + rt.executeCommand({ type: "scene:set", sceneId: "rt-stop-1" }); + useSceneStore.getState().setPlayerWalkingState(null); + + // Start a walk + rt.executeCommand({ type: "player:walkTo", position: [3, 0, 3] }); + const walking = useSceneStore.getState().playerWalkingState; + expect(walking?.isActive).toBe(true); + + // Stop the walk + rt.executeCommand({ type: "player:stop" }); + const stopped = useSceneStore.getState().playerWalkingState; + expect(stopped).toBeNull(); + }); + + it("emite player:walkAborted con reason: 'user-input' exactamente una vez", () => { + rt = createGameRuntime({ scenes: [makeScene("rt-stop-2")] }); + rt.executeCommand({ type: "scene:set", sceneId: "rt-stop-2" }); + useSceneStore.getState().setPlayerWalkingState(null); + + const aborted = vi.fn(); + rt.on("player:walkAborted", aborted); + + // Start a walk + rt.executeCommand({ type: "player:walkTo", position: [3, 0, 3] }); + + // Stop the walk + rt.executeCommand({ type: "player:stop" }); + + expect(aborted).toHaveBeenCalledTimes(1); + expect(aborted).toHaveBeenCalledWith({ + type: "player:walkAborted", + reason: "user-input", + }); + }); + + it("player:stop sin caminata activa no emite nada", () => { + rt = createGameRuntime({ scenes: [makeScene("rt-stop-3")] }); + rt.executeCommand({ type: "scene:set", sceneId: "rt-stop-3" }); + useSceneStore.getState().setPlayerWalkingState(null); + + const aborted = vi.fn(); + rt.on("player:walkAborted", aborted); + + // Try to stop without a walk + rt.executeCommand({ type: "player:stop" }); + + expect(aborted).not.toHaveBeenCalled(); + expect(useSceneStore.getState().playerWalkingState).toBeNull(); + }); +}); diff --git a/packages/engine-core/src/__tests__/gameRuntimeUiStores.test.ts b/packages/engine-core/src/__tests__/gameRuntimeUiStores.test.ts new file mode 100644 index 0000000..c30ab86 --- /dev/null +++ b/packages/engine-core/src/__tests__/gameRuntimeUiStores.test.ts @@ -0,0 +1,147 @@ +import { describe, it, expect, vi, afterEach, beforeEach } from "vitest"; +import { + createGameRuntime, + getGameState, + getDialogState, + getInventoryUiState, + useDialogStore, + useInventoryUiStore, + type GameRuntime, + type GameSceneConfig, +} from "../index"; + +function makeScene(id: string, extra: Partial = {}): GameSceneConfig { + return { + id, + label: `Scene ${id}`, + background: "/bg.png", + playerSpawn: [1, 0, 1], + ground: { minX: -5, maxX: 5, minZ: -5, maxZ: 5, y: 0 }, + walls: [], + interactions: [], + ...extra, + }; +} + +const resetStores = () => { + useDialogStore.setState({ text: "", key: undefined, visible: false, triggerCount: 0 }); + useInventoryUiStore.setState({ isOpen: false }); +}; + +let rt: GameRuntime | null = null; +beforeEach(resetStores); +afterEach(() => { + rt?.dispose(); + rt = null; + resetStores(); + vi.restoreAllMocks(); +}); + +describe("scene:set / transition:activate con spawn", () => { + it("scene:set sin spawnPosition usa el playerSpawn de la escena", () => { + rt = createGameRuntime({ scenes: [makeScene("ui-a")] }); + rt.executeCommand({ type: "scene:set", sceneId: "ui-a" }); + expect(getGameState().playerPosition).toEqual([1, 0, 1]); + }); + + it("scene:set con spawnPosition coloca al jugador ahí", () => { + rt = createGameRuntime({ scenes: [makeScene("ui-a")] }); + rt.executeCommand({ type: "scene:set", sceneId: "ui-a", spawnPosition: [3, 0, -2] }); + expect(getGameState().playerPosition).toEqual([3, 0, -2]); + }); + + const withTransition = (spawnPosition?: [number, number, number]) => [ + makeScene("ui-from", { + transitions: [ + { + id: "ui-go", + kind: "collision", + targetSceneId: "ui-to", + position: [0, 0, 0], + halfSize: [1, 1, 1], + ...(spawnPosition ? { spawnPosition } : {}), + }, + ], + }), + makeScene("ui-to", { playerSpawn: [9, 0, 9] }), + ]; + + it("transition:activate con spawnPosition lo usa", () => { + rt = createGameRuntime({ scenes: withTransition([2, 0, 4]) }); + rt.executeCommand({ type: "scene:set", sceneId: "ui-from" }); + rt.executeCommand({ type: "transition:activate", transitionId: "ui-go" }); + expect(getGameState().sceneId).toBe("ui-to"); + expect(getGameState().playerPosition).toEqual([2, 0, 4]); + }); + + it("transition:activate sin spawnPosition usa el playerSpawn destino", () => { + rt = createGameRuntime({ scenes: withTransition() }); + rt.executeCommand({ type: "scene:set", sceneId: "ui-from" }); + rt.executeCommand({ type: "transition:activate", transitionId: "ui-go" }); + expect(getGameState().playerPosition).toEqual([9, 0, 9]); + }); +}); + +describe("dialog sin adapter (store del core)", () => { + it("dialog:trigger escribe en el store del core", () => { + rt = createGameRuntime({ rules: [{ key: "ui.d", phrases: ["hola"] }] }); + rt.executeCommand({ type: "dialog:trigger", dialogKey: "ui.d" }); + expect(getDialogState()).toMatchObject({ text: "hola", key: "ui.d", visible: true }); + }); + + it("dialog:dismiss oculta el diálogo", () => { + rt = createGameRuntime(); + rt.executeCommand({ type: "dialog:trigger", dialogKey: "ui.x" }); + rt.executeCommand({ type: "dialog:dismiss" }); + expect(getDialogState().visible).toBe(false); + }); + + it("triggerCount incrementa en cada disparo y no en dismiss", () => { + rt = createGameRuntime(); + rt.executeCommand({ type: "dialog:trigger", dialogKey: "a" }); + rt.executeCommand({ type: "dialog:trigger", dialogKey: "a" }); + expect(getDialogState().triggerCount).toBe(2); + rt.executeCommand({ type: "dialog:dismiss" }); + expect(getDialogState().triggerCount).toBe(2); + }); + + it("con dialogAdapter el store del core no se toca", () => { + const adapter = { show: vi.fn(), hide: vi.fn() }; + rt = createGameRuntime({ dialogAdapter: adapter }); + rt.executeCommand({ type: "dialog:trigger", dialogKey: "k" }); + rt.executeCommand({ type: "dialog:dismiss" }); + expect(adapter.show).toHaveBeenCalledWith("k", "k"); + expect(adapter.hide).toHaveBeenCalled(); + expect(getDialogState()).toMatchObject({ visible: false, triggerCount: 0, text: "" }); + }); + + it("show del store conserva forma de la demo (key opcional)", () => { + useDialogStore.getState().show("t"); + expect(getDialogState()).toMatchObject({ text: "t", key: undefined, visible: true, triggerCount: 1 }); + }); +}); + +describe("inventory sin adapter (store del core)", () => { + it("inventory:toggle alterna el store", () => { + rt = createGameRuntime(); + rt.executeCommand({ type: "inventory:toggle" }); + expect(getInventoryUiState().isOpen).toBe(true); + rt.executeCommand({ type: "inventory:toggle" }); + expect(getInventoryUiState().isOpen).toBe(false); + }); + + it("con inventoryAdapter el store del core no se toca", () => { + const adapter = { toggle: vi.fn(), isOpen: () => false }; + rt = createGameRuntime({ inventoryAdapter: adapter }); + rt.executeCommand({ type: "inventory:toggle" }); + expect(adapter.toggle).toHaveBeenCalledTimes(1); + expect(getInventoryUiState().isOpen).toBe(false); + }); + + it("open/close del store funcionan", () => { + getInventoryUiState().open(); + expect(getInventoryUiState().isOpen).toBe(true); + getInventoryUiState().close(); + expect(getInventoryUiState().isOpen).toBe(false); + }); +}); diff --git a/packages/engine-core/src/__tests__/hotspots.test.ts b/packages/engine-core/src/__tests__/hotspots.test.ts new file mode 100644 index 0000000..dcb7153 --- /dev/null +++ b/packages/engine-core/src/__tests__/hotspots.test.ts @@ -0,0 +1,350 @@ +import { describe, it, expect, vi, afterEach, beforeEach } from "vitest"; +import { + act, + branch, + cond, + createGameRuntime, + getAvailableVerbs, + getConditionContext, + getDefaultVerb, + getInventoryState, + getSceneState, + getWorldState, + otherwise, + toRuntimeScene, + useDialogStore, + type GameEvent, + type GameEventType, + type GameRuntime, + type GameSceneConfig, + type GameSceneHotspot, +} from "../index"; +import { HeadlessClock } from "../ports/headlessClock"; +import { flush, makeItem, makeScene, resetStores } from "./sequencerHarness"; + +const box = { + position: [2, 0, 2] as [number, number, number], + halfSize: [0.5, 0.5, 0.5] as [number, number, number], +}; +const hs = (id: string, extra: Partial = {}): GameSceneHotspot => ({ + id, + label: `hs.${id}`, + ...box, + ...extra, +}); + +let rt: GameRuntime; +let events: GameEvent[]; + +function start( + hotspots: GameSceneHotspot[], + opts: { blocked?: boolean; record?: GameEventType[] } = {}, +) { + const scenes: GameSceneConfig[] = [ + makeScene("hs-a", { hotspots }), + makeScene("hs-blocked", { + hotspots, + interactions: [ + { id: "blocker", position: [0, 0, 0], halfSize: [20, 1, 20], hasCollision: true }, + ] as unknown as GameSceneConfig["interactions"], + }), + ]; + rt = createGameRuntime({ + scenes, + items: [makeItem("hs-key"), makeItem("hs-coin")], + clock: new HeadlessClock(), + instantWalk: true, + }); + rt.executeCommand({ type: "scene:set", sceneId: opts.blocked ? "hs-blocked" : "hs-a" }); + events = []; + const types: GameEventType[] = opts.record ?? [ + "hotspot:interacted", + "hotspot:noAction", + "custom", + "player:walkCompleted", + "player:walkAborted", + ]; + for (const t of types) rt.on(t, (e) => events.push(e as GameEvent)); +} + +const interact = async ( + hotspotId: string, + verb: "look" | "use" | "talk" | "useItem", + itemId?: string, +) => { + rt.executeCommand({ type: "hotspot:interact", hotspotId, verb, ...(itemId ? { itemId } : {}) }); + await flush(); +}; +const customNames = () => + events.filter((e) => e.type === "custom").map((e) => (e as { name: string }).name); +const ofType = (t: string) => events.filter((e) => e.type === t); +const giveInv = (id: string) => + getInventoryState().addItem({ id, name: id, spriteUrl: `/${id}.png` }); + +beforeEach(resetStores); +afterEach(() => { + rt?.dispose(); + resetStores(); + vi.restoreAllMocks(); +}); + +describe("hotspot:interact por verbo", () => { + it("look ejecuta su guion y emite interacted", async () => { + start([hs("door", { verbs: { look: [otherwise(act.emit("looked"))] } })]); + await interact("door", "look"); + expect(customNames()).toEqual(["looked"]); + expect(ofType("hotspot:interacted")).toEqual([ + { type: "hotspot:interacted", hotspotId: "door", verb: "look" }, + ]); + }); + + it("use ejecuta su guion", async () => { + start([hs("lever", { verbs: { use: [otherwise(act.setFlag("pulled"))] } })]); + await interact("lever", "use"); + expect(getWorldState().flags.pulled).toBe(true); + }); + + it("talk ejecuta su guion", async () => { + start([hs("npc", { verbs: { talk: [otherwise(act.emit("talked"))] } })]); + await interact("npc", "talk"); + expect(customNames()).toEqual(["talked"]); + }); + + it("un say del guion muestra el dialogo", async () => { + start([hs("sign", { verbs: { look: [otherwise(act.say("sign.text"))] } })]); + await interact("sign", "look"); + expect(useDialogStore.getState().visible).toBe(true); + expect(useDialogStore.getState().key).toBe("sign.text"); + rt.executeCommand({ type: "dialog:dismiss" }); + await flush(); + }); + + it("el guion solo ejecuta el verbo pedido", async () => { + start([ + hs("x", { + verbs: { look: [otherwise(act.emit("look"))], use: [otherwise(act.emit("use"))] }, + }), + ]); + await interact("x", "use"); + expect(customNames()).toEqual(["use"]); + }); +}); + +describe("ramas", () => { + const h = hs("chest", { + verbs: { + look: [branch(cond.flag("opened"), act.emit("open")), otherwise(act.emit("closed"))], + }, + }); + + it("elige la rama condicionada o el otherwise", async () => { + start([h]); + await interact("chest", "look"); + getWorldState().setFlag("opened", true); + await interact("chest", "look"); + expect(customNames()).toEqual(["closed", "open"]); + }); + + it("el guion pone un flag que cambia la rama de la siguiente interaccion", async () => { + start([ + hs("bell", { + verbs: { + use: [ + branch(cond.flag("rung"), act.emit("again")), + otherwise(act.setFlag("rung"), act.emit("first")), + ], + }, + }), + ]); + await interact("bell", "use"); + await interact("bell", "use"); + expect(customNames()).toEqual(["first", "again"]); + }); + + it("sin rama aplicable emite noAction no-rule y no corre guion", async () => { + start([hs("gate", { verbs: { look: [branch(cond.flag("never"), act.emit("x"))] } })], { + record: ["hotspot:interacted", "hotspot:noAction", "script:started"], + }); + await interact("gate", "look"); + expect(events).toEqual([ + { type: "hotspot:noAction", hotspotId: "gate", verb: "look", reason: "no-rule" }, + ]); + }); + + it("verbo sin definir -> no-rule", async () => { + start([hs("g", { verbs: { look: [otherwise()] } })]); + await interact("g", "talk"); + expect(ofType("hotspot:noAction")).toMatchObject([{ reason: "no-rule", verb: "talk" }]); + }); + + it("una rama con guion vacio cuenta como aplicable", async () => { + start([hs("g", { verbs: { look: [otherwise()] } })]); + await interact("g", "look"); + expect(ofType("hotspot:interacted")).toHaveLength(1); + expect(ofType("hotspot:noAction")).toHaveLength(0); + }); +}); + +describe("visibleWhen y noAction", () => { + it("not-found si el hotspot no existe", async () => { + start([hs("a")]); + vi.spyOn(console, "warn").mockImplementation(() => {}); + await interact("nope", "look"); + expect(ofType("hotspot:noAction")).toEqual([ + { type: "hotspot:noAction", hotspotId: "nope", verb: "look", reason: "not-found" }, + ]); + }); + + it("not-found en una escena sin hotspots", async () => { + start([]); + vi.spyOn(console, "warn").mockImplementation(() => {}); + await interact("a", "look"); + expect(ofType("hotspot:noAction")).toMatchObject([{ reason: "not-found" }]); + }); + + it("hidden si visibleWhen no se cumple; visible cuando se cumple", async () => { + start([ + hs("secret", { + visibleWhen: cond.flag("found"), + verbs: { look: [otherwise(act.emit("seen"))] }, + }), + ]); + await interact("secret", "look"); + expect(ofType("hotspot:noAction")).toMatchObject([{ reason: "hidden" }]); + expect(customNames()).toEqual([]); + getWorldState().setFlag("found", true); + await interact("secret", "look"); + expect(customNames()).toEqual(["seen"]); + }); + + it("missing-item si useItem sin itemId o con el item ausente", async () => { + start([hs("lock", { useItemDefault: [otherwise(act.emit("x"))] })]); + await interact("lock", "useItem", "hs-key"); + await interact("lock", "useItem"); + expect(ofType("hotspot:noAction")).toMatchObject([ + { reason: "missing-item", itemId: "hs-key" }, + { reason: "missing-item" }, + ]); + expect(customNames()).toEqual([]); + }); +}); + +describe("useItem", () => { + const lock = hs("lock", { + useItem: { + "hs-key": [ + otherwise(act.emit("keyed"), act.removeItem("hs-key"), act.setFlag("unlocked")), + ], + }, + useItemDefault: [otherwise(act.emit("nope"))], + }); + + it("usa la regla propia del item y el guion consume el item", async () => { + start([lock]); + giveInv("hs-key"); + await interact("lock", "useItem", "hs-key"); + expect(customNames()).toEqual(["keyed"]); + expect(getWorldState().flags.unlocked).toBe(true); + expect(getInventoryState().slots.every((s) => s === null)).toBe(true); + expect(ofType("hotspot:interacted")).toEqual([ + { type: "hotspot:interacted", hotspotId: "lock", verb: "useItem", itemId: "hs-key" }, + ]); + }); + + it("cae a useItemDefault sin regla propia, y el item no se consume solo", async () => { + start([lock]); + giveInv("hs-coin"); + await interact("lock", "useItem", "hs-coin"); + expect(customNames()).toEqual(["nope"]); + expect(getInventoryState().slots.some((s) => s?.id === "hs-coin")).toBe(true); + }); + + it("sin regla ni default -> no-rule", async () => { + start([hs("lock", { useItem: { "hs-key": [otherwise()] } })]); + giveInv("hs-coin"); + await interact("lock", "useItem", "hs-coin"); + expect(ofType("hotspot:noAction")).toMatchObject([{ reason: "no-rule", itemId: "hs-coin" }]); + }); +}); + +describe("approach", () => { + it("camina al punto antes de actuar", async () => { + start([hs("d", { approach: [3, 0, 3], verbs: { look: [otherwise(act.emit("acted"))] } })], { + record: ["custom", "player:walkCompleted"], + }); + await interact("d", "look"); + expect(events.map((e) => e.type)).toEqual(["player:walkCompleted", "custom"]); + expect(getSceneState().playerPosition).toEqual([3, 0, 3]); + }); + + it("sin approach actua desde donde esta", async () => { + start([hs("d", { verbs: { look: [otherwise(act.emit("acted"))] } })], { + record: ["custom", "player:walkCompleted"], + }); + await interact("d", "look"); + expect(events.map((e) => e.type)).toEqual(["custom"]); + }); + + it("si la caminata se aborta el guion sigue", async () => { + start([hs("d", { approach: [3, 0, 3], verbs: { look: [otherwise(act.emit("acted"))] } })], { + blocked: true, + }); + await interact("d", "look"); + expect(ofType("player:walkAborted")).toHaveLength(1); + expect(customNames()).toEqual(["acted"]); + }); +}); + +describe("getDefaultVerb / getAvailableVerbs", () => { + const all = hs("a", { + verbs: { look: [otherwise()], use: [otherwise()], talk: [otherwise()] }, + }); + const ctx = () => getConditionContext(); + + it("prefiere talk, luego use, luego look", () => { + start([]); + expect(getDefaultVerb(all, ctx())).toBe("talk"); + expect( + getDefaultVerb(hs("b", { verbs: { look: [otherwise()], use: [otherwise()] } }), ctx()), + ).toBe("use"); + expect(getDefaultVerb(hs("c", { verbs: { look: [otherwise()] } }), ctx())).toBe("look"); + }); + + it("devuelve null sin verbos aplicables", () => { + start([]); + expect(getDefaultVerb(hs("n"), ctx())).toBeNull(); + expect( + getDefaultVerb(hs("n", { verbs: { talk: [branch(cond.flag("z"), act.emit("q"))] } }), ctx()), + ).toBeNull(); + }); + + it("solo cuenta verbos con rama aplicable en ese contexto", () => { + start([]); + const h = hs("m", { + verbs: { talk: [branch(cond.flag("met"), act.emit("hi"))], look: [otherwise()] }, + }); + expect(getAvailableVerbs(h, ctx())).toEqual(["look"]); + expect(getDefaultVerb(h, ctx())).toBe("look"); + getWorldState().setFlag("met", true); + expect(getAvailableVerbs(h, ctx())).toEqual(["talk", "look"]); + expect(getDefaultVerb(h, ctx())).toBe("talk"); + }); + + it("getAvailableVerbs sigue el orden talk, use, look", () => { + start([]); + expect(getAvailableVerbs(all, ctx())).toEqual(["talk", "use", "look"]); + }); +}); + +describe("escenas", () => { + it("toRuntimeScene conserva hotspots", () => { + const hotspots = [hs("a")]; + expect(toRuntimeScene(makeScene("s", { hotspots })).hotspots).toBe(hotspots); + }); + + it("la escena activa los lleva; una escena sin hotspots no cambia", () => { + start([hs("a")]); + expect(getSceneState().scene.hotspots?.map((h) => h.id)).toEqual(["a"]); + expect(toRuntimeScene(makeScene("plain")).hotspots).toBeUndefined(); + }); +}); diff --git a/packages/engine-core/src/__tests__/inventoryCommands.test.ts b/packages/engine-core/src/__tests__/inventoryCommands.test.ts new file mode 100644 index 0000000..ffe7af0 --- /dev/null +++ b/packages/engine-core/src/__tests__/inventoryCommands.test.ts @@ -0,0 +1,299 @@ +import { describe, it, expect, vi, afterEach, beforeEach } from "vitest"; +import { + act, + createGameRuntime, + getInventoryState, + getPlacedItemsState, + getWorldState, + otherwise, + type GameEvent, + type GameEventType, + type GameItemConfig, + type GameRuntime, + type PlacedSceneItem, +} from "../index"; +import { HeadlessClock } from "../ports/headlessClock"; +import { flush, makeItem, makeScene, resetStores } from "./sequencerHarness"; + +const interaction = { + id: "table", + kind: "drop-target", + position: [1, 0, 1], + halfSize: [0.5, 0.5, 0.5], + dialogKeys: { hit: "t.hit", miss: "t.miss" }, + label: "table", +}; + +const items: GameItemConfig[] = [ + { ...makeItem("ic-key"), interactionRules: { table: { outcome: "place", placeCanPickup: true } } }, + { ...makeItem("ic-coin"), interactionRules: { table: { outcome: "consume" } } }, + makeItem("ic-gem"), // default: return + { ...makeItem("ic-bad"), interactionRules: { table: { outcome: "rule-miss" } } }, + { + ...makeItem("ic-fixed"), + interactionRules: { table: { outcome: "place", placeCanPickup: false } }, + }, +]; + +let rt: GameRuntime; +let events: GameEvent[]; + +beforeEach(() => { + resetStores(); + rt = createGameRuntime({ + scenes: [ + makeScene("ic-a", { + interactions: [interaction] as never, + hotspots: [ + { + id: "altar", + label: "altar", + position: [0, 0, 0], + halfSize: [1, 1, 1], + useItem: { "ic-coin": [otherwise(act.setFlag("offered"))] }, + }, + ], + }), + makeScene("ic-b"), + ], + items, + clock: new HeadlessClock(), + instantWalk: true, + }); + rt.executeCommand({ type: "scene:set", sceneId: "ic-a" }); + events = []; + const types: GameEventType[] = [ + "item:pickedUp", + "item:dropped", + "inventory:pickupFailed", + "hotspot:interacted", + ]; + for (const t of types) rt.on(t, (e) => events.push(e as GameEvent)); +}); +afterEach(() => { + rt.dispose(); + resetStores(); + vi.restoreAllMocks(); +}); + +const give = (id: string) => + getInventoryState().addItem({ id, name: id, spriteUrl: `/${id}.png` }); +const slotOf = (id: string) => getInventoryState().slots.findIndex((s) => s?.id === id); +const placed = (over: Partial = {}): PlacedSceneItem => ({ + id: "p1", + itemId: "ic-key", + interactionId: "table", + name: "ic-key", + spriteUrl: "/ic-key.png", + worldPosition: [1, 1, 1], + canPickup: true, + sceneId: "ic-a", + ...over, +}); + +describe("inventory:pickup", () => { + it("recoge el primer item colocado de la escena actual", () => { + getPlacedItemsState().addItem(placed()); + rt.executeCommand({ type: "inventory:pickup", itemId: "ic-key" }); + expect(getPlacedItemsState().items).toEqual([]); + expect(slotOf("ic-key")).toBeGreaterThanOrEqual(0); + expect(events).toEqual([{ type: "item:pickedUp", itemId: "ic-key", quantity: 1 }]); + }); + + it("ignora los items colocados en otra escena", () => { + getPlacedItemsState().addItem(placed({ sceneId: "ic-b" })); + rt.executeCommand({ type: "inventory:pickup", itemId: "ic-key" }); + expect(getPlacedItemsState().items).toHaveLength(1); + expect(events).toEqual([ + { type: "inventory:pickupFailed", itemId: "ic-key", reason: "not-found" }, + ]); + }); + + it("con placedItemId recoge ese concreto", () => { + getPlacedItemsState().addItem(placed({ id: "p1" })); + getPlacedItemsState().addItem(placed({ id: "p2" })); + rt.executeCommand({ type: "inventory:pickup", itemId: "ic-key", placedItemId: "p2" }); + expect(getPlacedItemsState().items.map((p) => p.id)).toEqual(["p1"]); + expect(getInventoryState().slots[0]?.quantity).toBe(1); + }); + + it("bloqueado: no cambia nada y emite pickupFailed blocked", () => { + getPlacedItemsState().addItem(placed({ canPickup: false })); + rt.executeCommand({ type: "inventory:pickup", itemId: "ic-key" }); + expect(getPlacedItemsState().items).toHaveLength(1); + expect(slotOf("ic-key")).toBe(-1); + expect(events).toEqual([ + { type: "inventory:pickupFailed", itemId: "ic-key", reason: "blocked" }, + ]); + }); + + it("inventario lleno: no cambia nada y emite pickupFailed full", () => { + for (let i = 0; i < 9; i++) { + getInventoryState().addItem({ id: `filler-${i}`, name: "f", spriteUrl: "/f.png" }); + } + getPlacedItemsState().addItem(placed()); + rt.executeCommand({ type: "inventory:pickup", itemId: "ic-key" }); + expect(getPlacedItemsState().items).toHaveLength(1); + expect(events).toEqual([{ type: "inventory:pickupFailed", itemId: "ic-key", reason: "full" }]); + }); + + it("inexistente: pickupFailed not-found", () => { + rt.executeCommand({ type: "inventory:pickup", itemId: "ic-key" }); + rt.executeCommand({ type: "inventory:pickup", itemId: "ic-key", placedItemId: "ghost" }); + expect(events.map((e) => (e as { reason: string }).reason)).toEqual(["not-found", "not-found"]); + }); + + it("item no registrado: pickupFailed unknown-item", () => { + getPlacedItemsState().addItem(placed({ itemId: "mystery" })); + rt.executeCommand({ type: "inventory:pickup", itemId: "mystery" }); + expect(events).toEqual([ + { type: "inventory:pickupFailed", itemId: "mystery", reason: "unknown-item" }, + ]); + }); +}); + +describe("inventory:drop", () => { + it("place: quita del slot y coloca el item en la escena activa", () => { + give("ic-key"); + rt.executeCommand({ + type: "inventory:drop", + itemId: "ic-key", + slotIndex: 0, + interactionId: "table", + }); + expect(slotOf("ic-key")).toBe(-1); + const [item] = getPlacedItemsState().items; + expect(item).toMatchObject({ + itemId: "ic-key", + interactionId: "table", + sceneId: "ic-a", + canPickup: true, + }); + expect(events).toEqual([ + { type: "item:dropped", itemId: "ic-key", outcome: "place", interactionId: "table" }, + ]); + }); + + it("place y luego pickup cierran el ciclo", () => { + give("ic-key"); + rt.executeCommand({ + type: "inventory:drop", + itemId: "ic-key", + slotIndex: 0, + interactionId: "table", + }); + rt.executeCommand({ type: "inventory:pickup", itemId: "ic-key" }); + expect(slotOf("ic-key")).toBe(0); + expect(getPlacedItemsState().items).toEqual([]); + }); + + it("consume: quita del slot sin colocar", () => { + give("ic-coin"); + rt.executeCommand({ + type: "inventory:drop", + itemId: "ic-coin", + slotIndex: 0, + interactionId: "table", + }); + expect(slotOf("ic-coin")).toBe(-1); + expect(getPlacedItemsState().items).toEqual([]); + expect(events).toEqual([ + { type: "item:dropped", itemId: "ic-coin", outcome: "consume", interactionId: "table" }, + ]); + }); + + it("consume solo quita una unidad de un stack", () => { + give("ic-coin"); + give("ic-coin"); + rt.executeCommand({ + type: "inventory:drop", + itemId: "ic-coin", + slotIndex: 0, + interactionId: "table", + }); + expect(getInventoryState().slots[0]?.quantity).toBe(1); + }); + + it("return: la regla por defecto devuelve el item sin cambios", () => { + give("ic-gem"); + rt.executeCommand({ + type: "inventory:drop", + itemId: "ic-gem", + slotIndex: 0, + interactionId: "table", + }); + expect(slotOf("ic-gem")).toBe(0); + expect(events).toEqual([ + { type: "item:dropped", itemId: "ic-gem", outcome: "return", interactionId: "table" }, + ]); + }); + + it("rule-miss (regla invalida) se trata como return, sin cambios", () => { + vi.spyOn(console, "warn").mockImplementation(() => {}); + give("ic-bad"); + rt.executeCommand({ + type: "inventory:drop", + itemId: "ic-bad", + slotIndex: 0, + interactionId: "table", + }); + expect(slotOf("ic-bad")).toBe(0); + expect(getPlacedItemsState().items).toEqual([]); + expect(events).toMatchObject([{ type: "item:dropped", outcome: "return" }]); + }); + + it("sin destino: return sin cambios ni interactionId", () => { + give("ic-key"); + rt.executeCommand({ type: "inventory:drop", itemId: "ic-key", slotIndex: 0 }); + expect(slotOf("ic-key")).toBe(0); + expect(events).toEqual([{ type: "item:dropped", itemId: "ic-key", outcome: "return" }]); + }); + + it("interaccion inexistente o slot que no contiene el item: return", () => { + give("ic-key"); + rt.executeCommand({ + type: "inventory:drop", + itemId: "ic-key", + slotIndex: 0, + interactionId: "ghost", + }); + rt.executeCommand({ + type: "inventory:drop", + itemId: "ic-key", + slotIndex: 5, + interactionId: "table", + }); + expect(slotOf("ic-key")).toBe(0); + expect(events.map((e) => (e as { outcome: string }).outcome)).toEqual(["return", "return"]); + }); + + it("sobre un hotspot equivale a hotspot:interact useItem", async () => { + give("ic-coin"); + rt.executeCommand({ + type: "inventory:drop", + itemId: "ic-coin", + slotIndex: 0, + hotspotId: "altar", + }); + await flush(); + expect(getWorldState().flags.offered).toBe(true); + expect(events).toEqual([ + { type: "hotspot:interacted", hotspotId: "altar", verb: "useItem", itemId: "ic-coin" }, + ]); + // El guion decide: sin removeItem el item sigue en el inventario. + expect(slotOf("ic-coin")).toBe(0); + }); + + it("place con canPickup false deja el item fijo y el pickup falla blocked", () => { + give("ic-fixed"); + rt.executeCommand({ + type: "inventory:drop", + itemId: "ic-fixed", + slotIndex: 0, + interactionId: "table", + }); + rt.executeCommand({ type: "inventory:pickup", itemId: "ic-fixed" }); + expect(getPlacedItemsState().items).toHaveLength(1); + expect(events.at(-1)).toMatchObject({ type: "inventory:pickupFailed", reason: "blocked" }); + }); +}); diff --git a/packages/engine-core/src/__tests__/inventoryRuleContext.test.ts b/packages/engine-core/src/__tests__/inventoryRuleContext.test.ts new file mode 100644 index 0000000..6a0ad4e --- /dev/null +++ b/packages/engine-core/src/__tests__/inventoryRuleContext.test.ts @@ -0,0 +1,119 @@ +import { describe, it, expect, vi, afterEach } from "vitest"; +import { + createInventoryRuleContext, + resolveInventoryDropHitDecision, + resolvePickupPlacedItemDecision, + type GameItemConfig, + type GameItemRule, +} from "../index"; + +function makeItem(extra: Partial = {}): GameItemConfig { + return { + id: "key", + name: "Llave", + spriteUrl: "/key.png", + descriptionDialogKey: "item.key.description", + pickupSoundUrl: "/pick.ogg", + interactionRules: { + door: { outcome: "consume", hitDialogKey: "item.key.door.hit" }, + pedestal: { outcome: "place", placeCanPickup: true }, + }, + defaultRule: { outcome: "return", missDialogKey: "item.key.default.miss" }, + ...extra, + }; +} + +const interaction = { id: "door", position: [0, 0, 0], halfSize: [1, 1, 1] } as never; +const payload = { stack: { id: "key", name: "Llave", spriteUrl: "/key.png" }, fromSlotIndex: 3 }; + +afterEach(() => vi.restoreAllMocks()); + +describe("createInventoryRuleContext", () => { + it("resuelve definicion y reglas desde un registro", () => { + const ctx = createInventoryRuleContext({ key: makeItem() }); + const def = ctx.getItemDefinition("key"); + expect(def).toMatchObject({ id: "key", name: "Llave", descriptionDialogKey: "item.key.description", pickupSoundUrl: "/pick.ogg" }); + expect(ctx.resolveItemRule("key", "door")?.outcome).toBe("consume"); + expect(ctx.resolveItemRule("key", "pedestal")).toMatchObject({ outcome: "place", placeCanPickup: true }); + }); + + it("usa defaultRule si no hay regla para la interaccion", () => { + const ctx = createInventoryRuleContext({ key: makeItem() }); + expect(ctx.resolveItemRule("key", "otra")).toEqual({ outcome: "return", missDialogKey: "item.key.default.miss" }); + }); + + it("item desconocido devuelve null en ambas funciones (y no cae al prototipo)", () => { + const ctx = createInventoryRuleContext({ key: makeItem() }); + expect(ctx.getItemDefinition("nope")).toBeNull(); + expect(ctx.resolveItemRule("nope", "door")).toBeNull(); + expect(ctx.getItemDefinition("toString")).toBeNull(); + expect(ctx.resolveItemRule("key", "constructor")?.outcome).toBe("return"); + }); + + it("con funcion lee el registro en cada uso, no al crear el contexto", () => { + let registry: Record = {}; + const ctx = createInventoryRuleContext(() => registry); + expect(ctx.getItemDefinition("key")).toBeNull(); + registry = { key: makeItem() }; + expect(ctx.getItemDefinition("key")?.id).toBe("key"); + registry = {}; + expect(ctx.resolveItemRule("key", "door")).toBeNull(); + }); + + it("encaja con las reglas de inventario (drop consume, pickup)", () => { + const ctx = createInventoryRuleContext({ key: makeItem() }); + expect(resolveInventoryDropHitDecision(ctx, { interaction, payload, now: 1 })).toMatchObject({ + kind: "consume", + fromSlotIndex: 3, + dialogKey: "item.key.door.hit", + }); + const unknown = { ...payload, stack: { ...payload.stack, id: "zzz" } }; + expect(resolveInventoryDropHitDecision(ctx, { interaction, payload: unknown, now: 1 }).kind).toBe("unknown-item"); + expect( + resolvePickupPlacedItemDecision(ctx, { + placedItem: { id: "p1", itemId: "key", canPickup: true } as never, + }).kind, + ).toBe("allow"); + }); + + it("regla especifica con outcome invalido: resolveItemRule null y el drop es rule-miss (no consume ni coloca)", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const bad = { outcome: "pickup-success" } as GameItemRule; + const ctx = createInventoryRuleContext({ + key: makeItem({ interactionRules: { door: bad } }), + }); + expect(ctx.resolveItemRule("key", "door")).toBeNull(); + expect(resolveInventoryDropHitDecision(ctx, { interaction, payload, now: 1 }).kind).toBe("rule-miss"); + expect(ctx.getItemDefinition("key")?.interactionRules).toEqual({}); + expect(warn).toHaveBeenCalled(); + }); + + it("outcome fuera del tipo (valor desconocido en runtime) tambien se rechaza", () => { + vi.spyOn(console, "warn").mockImplementation(() => {}); + const bad = { outcome: "banana" } as unknown as GameItemRule; + const ctx = createInventoryRuleContext({ key: makeItem({ interactionRules: { door: bad } }) }); + expect(ctx.resolveItemRule("key", "door")).toBeNull(); + }); + + it("defaultRule invalida: resolveItemRule null; la definicion usa un return seguro con missDialogKey", () => { + vi.spyOn(console, "warn").mockImplementation(() => {}); + const ctx = createInventoryRuleContext({ + key: makeItem({ defaultRule: { outcome: "rule-miss", missDialogKey: "m.k" } }), + }); + expect(ctx.resolveItemRule("key", "otra")).toBeNull(); + expect(ctx.getItemDefinition("key")?.defaultRule).toEqual({ outcome: "return", missDialogKey: "m.k" }); + // las reglas validas siguen funcionando + expect(ctx.resolveItemRule("key", "door")?.outcome).toBe("consume"); + }); + + it("avisa una sola vez por regla invalida", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const ctx = createInventoryRuleContext({ + key: makeItem({ interactionRules: { door: { outcome: "rule-miss" } } }), + }); + ctx.resolveItemRule("key", "door"); + ctx.resolveItemRule("key", "door"); + ctx.getItemDefinition("key"); + expect(warn).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/engine-core/src/__tests__/inventoryRulesParity.test.ts b/packages/engine-core/src/__tests__/inventoryRulesParity.test.ts new file mode 100644 index 0000000..012d375 --- /dev/null +++ b/packages/engine-core/src/__tests__/inventoryRulesParity.test.ts @@ -0,0 +1,157 @@ +import { describe, expect, it } from "vitest"; + +import { + resolveInventoryDropHitDecision, + resolveInventoryDropMissDialogKey, + resolveInventoryDropOnPlayerMessage, + resolvePickupPlacedItemDecision, + type ItemDefinition, + type ItemInteractionRule, +} from "../game/logic/rules/inventoryRules"; + +// Paridad con la version de la demo (referencia de comportamiento): los +// fallbacks de dialogKey usan `??` (solo null/undefined), nunca `||`. + +const items: Record = { + key: { + id: "key", + name: "Llave", + spriteUrl: "/key.png", + interactionRules: { + door: { outcome: "consume", hitDialogKey: "item.key.hit" as never }, + empty: { outcome: "consume", hitDialogKey: "" as never }, + "empty-place": { outcome: "place", hitDialogKey: "" as never }, + "empty-return": { outcome: "return", hitDialogKey: "" as never, missDialogKey: "miss" as never }, + "empty-miss": { outcome: "return", missDialogKey: "" as never }, + }, + defaultRule: { outcome: "return", missDialogKey: "item.key.default.miss" as never }, + }, +}; + +const ctx = { + getItemDefinition: (id: string) => items[id] ?? null, + resolveItemRule: (id: string, interactionId: string): ItemInteractionRule | null => { + const item = items[id]; + if (!item) return null; + return item.interactionRules[interactionId] ?? item.defaultRule; + }, +}; + +const payload = { stack: { id: "key", name: "Llave", spriteUrl: "/key.png" }, fromSlotIndex: 2 }; +const base = { position: [0, 0, 0] as [number, number, number], halfSize: [1, 1, 1] as [number, number, number] }; +const dialogKeys = { hit: "scene.hit", miss: "scene.miss" }; + +describe("inventoryRules paridad con la demo", () => { + it("consume: hitDialogKey vacio se respeta (no cae a la escena)", () => { + const d = resolveInventoryDropHitDecision(ctx, { + interaction: { ...base, id: "empty", dialogKeys } as never, + payload, + now: 1, + }); + expect(d).toEqual({ kind: "consume", fromSlotIndex: 2, dialogKey: "" }); + }); + + it("place: hitDialogKey vacio se respeta", () => { + const d = resolveInventoryDropHitDecision(ctx, { + interaction: { ...base, id: "empty-place", dialogKeys } as never, + payload, + now: 1, + }); + expect(d.kind).toBe("place"); + if (d.kind !== "place") return; + expect(d.dialogKey).toBe(""); + }); + + it("return: hitDialogKey vacio se respeta (no cae a missDialogKey)", () => { + const d = resolveInventoryDropHitDecision(ctx, { + interaction: { ...base, id: "empty-return", dialogKeys } as never, + payload, + now: 1, + }); + expect(d).toEqual({ kind: "return", dialogKey: "" }); + }); + + it("rule-miss: dialogKeys.miss vacio de la escena se respeta", () => { + const d = resolveInventoryDropHitDecision( + { ...ctx, resolveItemRule: () => null }, + { interaction: { ...base, id: "x", dialogKeys: { hit: "h", miss: "" } } as never, payload, now: 1 }, + ); + expect(d).toEqual({ kind: "rule-miss", dialogKey: "" }); + }); + + it("drop miss: missDialogKey vacio de la regla se respeta", () => { + const key = resolveInventoryDropMissDialogKey(ctx, { + payload, + interaction: { ...base, id: "empty-miss", dialogKeys } as never, + sceneInteractions: [], + }); + expect(key).toBe(""); + }); + + it("drop miss: orden regla > interaction > primer drop-target > default", () => { + const targets = [{ ...base, kind: "drop-target", dialogKeys: { hit: "h", miss: "first.miss" } }] as never; + expect( + resolveInventoryDropMissDialogKey(ctx, { + payload, + interaction: { ...base, id: "unknown", dialogKeys } as never, + sceneInteractions: targets, + }), + ).toBe("item.key.default.miss"); + expect( + resolveInventoryDropMissDialogKey({ ...ctx, resolveItemRule: () => null }, { + payload, + interaction: { ...base, id: "u", dialogKeys } as never, + sceneInteractions: targets, + }), + ).toBe("scene.miss"); + expect( + resolveInventoryDropMissDialogKey(ctx, { payload, sceneInteractions: targets }), + ).toBe("first.miss"); + }); + + it("pickup: dialogKeys vacios en el item colocado se respetan", () => { + const blocked = resolvePickupPlacedItemDecision(ctx, { + placedItem: { + id: "p", itemId: "key", interactionId: "door", name: "Llave", spriteUrl: "/k.png", + worldPosition: [0, 0, 0], canPickup: false, pickupBlockedDialogKey: "" as never, + }, + }); + expect(blocked).toEqual({ kind: "blocked", dialogKey: "" }); + const allowed = resolvePickupPlacedItemDecision(ctx, { + placedItem: { + id: "p", itemId: "key", interactionId: "door", name: "Llave", spriteUrl: "/k.png", + worldPosition: [0, 0, 0], canPickup: true, pickupSuccessDialogKey: "" as never, + }, + }); + expect(allowed.kind === "allow" && allowed.successDialogKey).toBe(""); + }); + + it("pickup: claves por defecto item..pickup.", () => { + const placedItem = { + id: "p", itemId: "key", interactionId: "door", name: "Llave", spriteUrl: "/k.png", + worldPosition: [0, 0, 0] as [number, number, number], + }; + expect(resolvePickupPlacedItemDecision(ctx, { placedItem: { ...placedItem, canPickup: false } })) + .toEqual({ kind: "blocked", dialogKey: "item.key.pickup.blocked" }); + const ok = resolvePickupPlacedItemDecision(ctx, { placedItem: { ...placedItem, canPickup: true } }); + expect(ok.kind === "allow" && ok.successDialogKey).toBe("item.key.pickup.allowed"); + expect(resolvePickupPlacedItemDecision(ctx, { placedItem: { ...placedItem, itemId: "nope", canPickup: true } })) + .toEqual({ kind: "ignore" }); + }); + + it("drop sobre player: item desconocido y item sin descriptionDialogKey", () => { + expect( + resolveInventoryDropOnPlayerMessage(ctx, { payload: { ...payload, stack: { ...payload.stack, id: "zz" } } }), + ).toEqual({ kind: "text", text: "No conozco este item todavía." }); + expect(resolveInventoryDropOnPlayerMessage(ctx, { payload })).toEqual({ kind: "text", text: "Es Llave." }); + }); + + it("drop hit: item desconocido -> unknown-item", () => { + const d = resolveInventoryDropHitDecision(ctx, { + interaction: { ...base, id: "door", dialogKeys } as never, + payload: { ...payload, stack: { ...payload.stack, id: "zz" } }, + now: 1, + }); + expect(d.kind).toBe("unknown-item"); + }); +}); diff --git a/packages/engine-core/src/__tests__/itemCombine.test.ts b/packages/engine-core/src/__tests__/itemCombine.test.ts new file mode 100644 index 0000000..d927723 --- /dev/null +++ b/packages/engine-core/src/__tests__/itemCombine.test.ts @@ -0,0 +1,269 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { + act, + branch, + cond, + createGameRuntime, + getInventoryState, + getWorldState, + otherwise, + type GameEvent, + type GameEventType, + type GameRuntime, + type GameItemConfig, + type GameSceneConfig, +} from "../index"; +import { HeadlessClock } from "../ports/headlessClock"; +import { flush, makeItem, makeScene, resetStores } from "./sequencerHarness"; + +let rt: GameRuntime; +let events: GameEvent[]; + +function start(items: GameItemConfig[] = []) { + const scenes: GameSceneConfig[] = [makeScene("s")]; + rt = createGameRuntime({ + scenes, + items, + clock: new HeadlessClock(), + instantWalk: true, + }); + rt.executeCommand({ type: "scene:set", sceneId: "s" }); + events = []; + const types: GameEventType[] = ["item:combined", "item:combineFailed", "custom"]; + for (const t of types) rt.on(t, (e) => events.push(e as GameEvent)); +} + +const combine = async (itemId: string, withItemId: string) => { + rt.executeCommand({ type: "inventory:combine", itemId, withItemId }); + await flush(); +}; + +const addItem = (id: string) => + getInventoryState().addItem({ id, name: id, spriteUrl: `/${id}.png` }); + +const customNames = () => + events.filter((e) => e.type === "custom").map((e) => (e as { name: string }).name); + +const ofType = (t: string) => events.filter((e) => e.type === t); + +beforeEach(resetStores); +afterEach(() => { + rt?.dispose(); + resetStores(); + vi.restoreAllMocks(); +}); + +describe("inventory:combine", () => { + it("combina dos ítems y ejecuta el guion del primero", async () => { + const rope = { + ...makeItem("rope"), + combine: { + hook: [otherwise(act.emit("ropeHook"), act.removeItem("rope"), act.removeItem("hook"), act.giveItem("grapple"))], + }, + }; + const hook = makeItem("hook"); + const grapple = makeItem("grapple"); + start([rope, hook, grapple]); + addItem("rope"); + addItem("hook"); + await combine("rope", "hook"); + expect(customNames()).toEqual(["ropeHook"]); + expect(getInventoryState().slots.some((s) => s?.id === "grapple")).toBe(true); + expect(getInventoryState().slots.some((s) => s?.id === "rope")).toBe(false); + expect(getInventoryState().slots.some((s) => s?.id === "hook")).toBe(false); + }); + + it("combina ítems cuando la regla está en el segundo ítem (simetría)", async () => { + const rope = makeItem("rope"); + const hook = { + ...makeItem("hook"), + combine: { + rope: [otherwise(act.emit("combined"))], + }, + }; + start([rope, hook]); + addItem("rope"); + addItem("hook"); + await combine("rope", "hook"); + expect(customNames()).toEqual(["combined"]); + expect(ofType("item:combined")).toHaveLength(1); + }); + + it("emite item:combined al combinar con éxito", async () => { + const rope = { + ...makeItem("rope"), + combine: { + hook: [otherwise(act.emit("ok"))], + }, + }; + const hook = makeItem("hook"); + start([rope, hook]); + addItem("rope"); + addItem("hook"); + await combine("rope", "hook"); + expect(ofType("item:combined")).toEqual([ + { type: "item:combined", itemId: "rope", withItemId: "hook" }, + ]); + }); + + it("emite item:combineFailed si no hay regla aplicable", async () => { + const rope = makeItem("rope"); + const hook = makeItem("hook"); + start([rope, hook]); + addItem("rope"); + addItem("hook"); + await combine("rope", "hook"); + expect(ofType("item:combineFailed")).toEqual([ + { type: "item:combineFailed", itemId: "rope", withItemId: "hook" }, + ]); + expect(ofType("item:combined")).toHaveLength(0); + }); + + it("emite item:combineFailed si falta uno de los ítems en el inventario", async () => { + const rope = { + ...makeItem("rope"), + combine: { + hook: [otherwise(act.emit("ok"))], + }, + }; + const hook = makeItem("hook"); + start([rope, hook]); + addItem("rope"); + // No agrega hook + await combine("rope", "hook"); + expect(ofType("item:combineFailed")).toEqual([ + { type: "item:combineFailed", itemId: "rope", withItemId: "hook" }, + ]); + }); + + it("emite item:combineFailed si el primer ítem no está en el inventario", async () => { + const rope = { + ...makeItem("rope"), + combine: { + hook: [otherwise(act.emit("ok"))], + }, + }; + const hook = makeItem("hook"); + start([rope, hook]); + // No agrega rope + addItem("hook"); + await combine("rope", "hook"); + expect(ofType("item:combineFailed")).toHaveLength(1); + }); + + it("emite item:combineFailed si se intenta combinar un ítem consigo mismo", async () => { + const rope = { + ...makeItem("rope"), + combine: { + rope: [otherwise(act.emit("self"))], + }, + }; + start([rope]); + addItem("rope"); + await combine("rope", "rope"); + expect(ofType("item:combineFailed")).toEqual([ + { type: "item:combineFailed", itemId: "rope", withItemId: "rope" }, + ]); + expect(customNames()).toEqual([]); + }); + + it("usa rama condicionada que se cumple", async () => { + const rope = { + ...makeItem("rope"), + combine: { + hook: [ + branch(cond.flag("hasKnot"), act.emit("knotted")), + otherwise(act.emit("plain")), + ], + }, + }; + const hook = makeItem("hook"); + start([rope, hook]); + addItem("rope"); + addItem("hook"); + await combine("rope", "hook"); + expect(customNames()).toEqual(["plain"]); + getWorldState().setFlag("hasKnot", true); + // Clear events for next combine + events = []; + addItem("rope"); + addItem("hook"); + await combine("rope", "hook"); + expect(customNames()).toEqual(["knotted"]); + }); + + it("usa rama condicionada que NO se cumple", async () => { + const rope = { + ...makeItem("rope"), + combine: { + hook: [branch(cond.flag("never"), act.emit("never"))], + }, + }; + const hook = makeItem("hook"); + start([rope, hook]); + addItem("rope"); + addItem("hook"); + await combine("rope", "hook"); + expect(ofType("item:combineFailed")).toHaveLength(1); + expect(customNames()).toEqual([]); + }); + + it("el guion consigue usar acciones complejas: removeItem, giveItem, setFlag", async () => { + const sword = { + ...makeItem("sword"), + combine: { + stone: [ + otherwise( + act.removeItem("sword"), + act.removeItem("stone"), + act.giveItem("sharpSword"), + act.setFlag("sharpened", true), + act.emit("done"), + ), + ], + }, + }; + const stone = makeItem("stone"); + const sharpSword = makeItem("sharpSword"); + start([sword, stone, sharpSword]); + addItem("sword"); + addItem("stone"); + await combine("sword", "stone"); + expect(customNames()).toEqual(["done"]); + expect(getWorldState().flags.sharpened).toBe(true); + expect(getInventoryState().slots.some((s) => s?.id === "sharpSword")).toBe(true); + expect(getInventoryState().slots.some((s) => s?.id === "sword")).toBe(false); + expect(getInventoryState().slots.some((s) => s?.id === "stone")).toBe(false); + }); + + it("no ejecuta guion si falta algún ítem, incluso si hay regla", async () => { + const rope = { + ...makeItem("rope"), + combine: { + hook: [otherwise(act.setFlag("combined", true))], + }, + }; + const hook = makeItem("hook"); + start([rope, hook]); + addItem("rope"); + // Falta hook + await combine("rope", "hook"); + expect(getWorldState().flags.combined).toBeUndefined(); + expect(ofType("item:combineFailed")).toHaveLength(1); + }); + + it("en orden inverso (hook + rope)", async () => { + const rope = { + ...makeItem("rope"), + combine: { + hook: [otherwise(act.emit("combined"))], + }, + }; + const hook = makeItem("hook"); + start([rope, hook]); + addItem("rope"); + addItem("hook"); + await combine("hook", "rope"); + expect(customNames()).toEqual(["combined"]); + }); +}); diff --git a/packages/engine-core/src/__tests__/legacyAdapterPickup.test.ts b/packages/engine-core/src/__tests__/legacyAdapterPickup.test.ts new file mode 100644 index 0000000..76eeffe --- /dev/null +++ b/packages/engine-core/src/__tests__/legacyAdapterPickup.test.ts @@ -0,0 +1,33 @@ +import { describe, it, expect } from "vitest"; +import { legacyRuntimeEventToGameEvent } from "../game/events/legacyAdapter"; + +describe("legacyRuntimeEventToGameEvent: recogida", () => { + it("onDrop pickup-success se emite como item:pickedUp", () => { + const ge = legacyRuntimeEventToGameEvent({ + type: "onDrop", + outcome: "pickup-success", + itemId: "gameboy", + interactionId: "slot-1", + }); + expect(ge).toEqual({ type: "item:pickedUp", itemId: "gameboy", quantity: 1 }); + }); + + it.each([ + "place", + "return", + "consume", + "rule-miss", + "unknown-item", + "on-player", + "pickup-blocked", + "item-interact", + ])("onDrop %s sigue siendo item:dropped", (outcome) => { + const ge = legacyRuntimeEventToGameEvent({ + type: "onDrop", + outcome, + itemId: "gameboy", + }); + expect(ge.type).toBe("item:dropped"); + if (ge.type === "item:dropped") expect(ge.outcome).toBe(outcome); + }); +}); diff --git a/packages/engine-core/src/__tests__/legacyOutcomes.test.ts b/packages/engine-core/src/__tests__/legacyOutcomes.test.ts new file mode 100644 index 0000000..84eeab7 --- /dev/null +++ b/packages/engine-core/src/__tests__/legacyOutcomes.test.ts @@ -0,0 +1,186 @@ +import { describe, it, expect } from "vitest"; +import { legacyRuntimeEventToGameEvent, gameEventToLegacyRuntimeEvent } from "../game/events/legacyAdapter"; +import type { RuntimeEvent } from "../game/types"; +import type { GameEvent } from "../game/events/types"; + +/** + * Tests that verify all legacy outcome values from onDrop events are correctly + * preserved when converting between RuntimeEvent and GameEvent representations. + */ +describe("Legacy outcomes preservation", () => { + describe("Rule results (consume, place, return)", () => { + it("outcome 'consume' is preserved without modification", () => { + const runtimeEvent: RuntimeEvent = { + type: "onDrop", + outcome: "consume", + itemId: "potion", + interactionId: "cauldron-1", + }; + + const gameEvent = legacyRuntimeEventToGameEvent(runtimeEvent); + expect(gameEvent.type).toBe("item:dropped"); + if (gameEvent.type === "item:dropped") { + expect(gameEvent.outcome).toBe("consume"); + expect(gameEvent.itemId).toBe("potion"); + expect(gameEvent.interactionId).toBe("cauldron-1"); + } + }); + + it("outcome 'place' is preserved without modification", () => { + const runtimeEvent: RuntimeEvent = { + type: "onDrop", + outcome: "place", + itemId: "statue", + interactionId: "pedestal-2", + }; + + const gameEvent = legacyRuntimeEventToGameEvent(runtimeEvent); + expect(gameEvent.type).toBe("item:dropped"); + if (gameEvent.type === "item:dropped") { + expect(gameEvent.outcome).toBe("place"); + expect(gameEvent.itemId).toBe("statue"); + } + }); + + it("outcome 'return' is preserved without modification", () => { + const runtimeEvent: RuntimeEvent = { + type: "onDrop", + outcome: "return", + itemId: "sword", + }; + + const gameEvent = legacyRuntimeEventToGameEvent(runtimeEvent); + expect(gameEvent.type).toBe("item:dropped"); + if (gameEvent.type === "item:dropped") { + expect(gameEvent.outcome).toBe("return"); + } + }); + }); + + describe("No matching rule outcomes (rule-miss, unknown-item, on-player)", () => { + it("outcome 'rule-miss' is preserved without modification", () => { + const runtimeEvent: RuntimeEvent = { + type: "onDrop", + outcome: "rule-miss", + itemId: "key", + interactionId: "door-1", + }; + + const gameEvent = legacyRuntimeEventToGameEvent(runtimeEvent); + expect(gameEvent.type).toBe("item:dropped"); + if (gameEvent.type === "item:dropped") { + expect(gameEvent.outcome).toBe("rule-miss"); + } + }); + + it("outcome 'unknown-item' is preserved without modification", () => { + const runtimeEvent: RuntimeEvent = { + type: "onDrop", + outcome: "unknown-item", + itemId: "mystery-object", + interactionId: "table-1", + }; + + const gameEvent = legacyRuntimeEventToGameEvent(runtimeEvent); + expect(gameEvent.type).toBe("item:dropped"); + if (gameEvent.type === "item:dropped") { + expect(gameEvent.outcome).toBe("unknown-item"); + } + }); + + it("outcome 'on-player' is preserved without modification", () => { + const runtimeEvent: RuntimeEvent = { + type: "onDrop", + outcome: "on-player", + itemId: "coin", + }; + + const gameEvent = legacyRuntimeEventToGameEvent(runtimeEvent); + expect(gameEvent.type).toBe("item:dropped"); + if (gameEvent.type === "item:dropped") { + expect(gameEvent.outcome).toBe("on-player"); + } + }); + }); + + describe("Legacy outcomes (pickup-blocked, item-interact)", () => { + it("deprecated outcome 'pickup-blocked' is preserved for backward compatibility", () => { + const runtimeEvent: RuntimeEvent = { + type: "onDrop", + outcome: "pickup-blocked", + itemId: "vase", + interactionId: "shelf-1", + }; + + const gameEvent = legacyRuntimeEventToGameEvent(runtimeEvent); + expect(gameEvent.type).toBe("item:dropped"); + if (gameEvent.type === "item:dropped") { + expect(gameEvent.outcome).toBe("pickup-blocked"); + expect(gameEvent.itemId).toBe("vase"); + } + }); + + it("deprecated outcome 'item-interact' is preserved for backward compatibility", () => { + const runtimeEvent: RuntimeEvent = { + type: "onDrop", + outcome: "item-interact", + itemId: "painting", + interactionId: "wall-1", + }; + + const gameEvent = legacyRuntimeEventToGameEvent(runtimeEvent); + expect(gameEvent.type).toBe("item:dropped"); + if (gameEvent.type === "item:dropped") { + expect(gameEvent.outcome).toBe("item-interact"); + } + }); + }); + + describe("Reverse mapping preserves all outcomes", () => { + it("reverses item:dropped with consume back to onDrop", () => { + const gameEvent: GameEvent = { + type: "item:dropped", + itemId: "potion", + outcome: "consume", + interactionId: "cauldron", + }; + + const runtimeEvent = gameEventToLegacyRuntimeEvent(gameEvent); + expect(runtimeEvent?.type).toBe("onDrop"); + if (runtimeEvent?.type === "onDrop") { + expect(runtimeEvent.outcome).toBe("consume"); + expect(runtimeEvent.itemId).toBe("potion"); + } + }); + + it("reverses item:dropped with rule-miss back to onDrop", () => { + const gameEvent: GameEvent = { + type: "item:dropped", + itemId: "key", + outcome: "rule-miss", + interactionId: "door", + }; + + const runtimeEvent = gameEventToLegacyRuntimeEvent(gameEvent); + expect(runtimeEvent?.type).toBe("onDrop"); + if (runtimeEvent?.type === "onDrop") { + expect(runtimeEvent.outcome).toBe("rule-miss"); + } + }); + + it("reverses item:dropped with pickup-blocked back to onDrop", () => { + const gameEvent: GameEvent = { + type: "item:dropped", + itemId: "vase", + outcome: "pickup-blocked", + interactionId: "shelf", + }; + + const runtimeEvent = gameEventToLegacyRuntimeEvent(gameEvent); + expect(runtimeEvent?.type).toBe("onDrop"); + if (runtimeEvent?.type === "onDrop") { + expect(runtimeEvent.outcome).toBe("pickup-blocked"); + } + }); + }); +}); diff --git a/packages/engine-core/src/__tests__/miniAdventure.playthrough.test.ts b/packages/engine-core/src/__tests__/miniAdventure.playthrough.test.ts new file mode 100644 index 0000000..646d1b8 --- /dev/null +++ b/packages/engine-core/src/__tests__/miniAdventure.playthrough.test.ts @@ -0,0 +1,254 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { validateContent, type GameSnapshot } from "../index"; +import { createPlaythrough, type Playthrough } from "../testing"; +import { miniAdventure } from "./fixtures/miniAdventure"; + +let pt: Playthrough | null = null; +let credits: unknown[] = []; + +/** Nueva partida del fixture con el manejador `credits` registrado y los bocadillos anotados. */ +function start(snapshot?: GameSnapshot) { + const said: string[] = []; + const p = createPlaythrough(miniAdventure, { + handlers: { credits: (args) => void credits.push(args) }, + onRuntime: (rt) => + void rt.on("dialog:triggered", (e) => { + if (e.dialogKey) said.push(e.dialogKey); + }), + ...(snapshot ? { snapshot } : {}), + }); + pt = p; + return { p, said }; +} + +afterEach(() => { + pt?.dispose(); + pt = null; + credits = []; + vi.restoreAllMocks(); +}); + +/** Resuelve los puzzles 1 a 3 (llave, cofre, mapa, pescador, combinar). */ +async function untilLamp(p: Playthrough) { + await p.pickUp("key-on-sand"); + await p.useItemOn("rusty-key", "chest"); + await p.look("map"); + await p.talk("fisherman"); + await p.choose(0); + await p.choose(2); + await p.combine("lens", "lamp-frame"); +} + +describe("mini-adventure: contenido", () => { + it("validateContent no da errores ni avisos", () => { + expect(validateContent(miniAdventure)).toEqual([]); + }); + + it("un contenido roto lanza al crear la partida", () => { + const broken = { ...miniAdventure, items: miniAdventure.items.slice(1) }; + expect(() => createPlaythrough(broken)).toThrow(/validateContent/); + }); +}); + +describe("mini-adventure: recorrido completo", () => { + it("se resuelve de principio a fin sin renderer", async () => { + const t0 = performance.now(); + const { p, said } = start(); + await p.settle(); + expect(p.state().sceneId).toBe("beach"); + expect(said).toEqual(["beach.intro"]); + expect(p.state().flags["intro.done"]).toBe(true); + + // Puzzle 1: recoger y usar. + await p.pickUp("key-on-sand"); + expect(p.state().inventory).toEqual(["rusty-key"]); + await p.useItemOn("rusty-key", "chest"); + expect(p.state().inventory).toEqual(["lens"]); + expect(p.state().flags["chest.open"]).toBe(true); + + // Puzzle 2: conversacion condicionada por haber mirado el mapa. + await p.look("map"); + expect(p.state().flags["map.seen"]).toBe(true); + await p.talk("fisherman"); + expect(p.state().dialogueActive).toBe(true); + await p.choose(0); + expect(p.state().inventory).toEqual(["lens", "lamp-frame"]); + expect(p.state().dialogueActive).toBe(true); + await p.choose(2); + expect(p.state().dialogueActive).toBe(false); + + // Puzzle 3: combinar. + await p.combine("lens", "lamp-frame"); + expect(p.state().inventory).toEqual(["lamp"]); + + // Cambio de escena: siembra con `when` y pickUp en otra escena. + await p.goThrough("to-cove"); + expect(p.state().sceneId).toBe("cove"); + await p.pickUp("fish-on-rocks"); + expect(p.state().inventory).toEqual(["lamp", "fish"]); + + // Puzzle 4: intercambio con el guardian y transicion final. + await p.useItemOn("lamp", "keeper"); + expect(p.state().inventory).toEqual(["fish"]); + expect(p.state().flags["keeper.lit"]).toBe(true); + await p.goThrough("to-lighthouse"); + expect(p.state().sceneId).toBe("lighthouse"); + expect(p.state().flags["game.finished"]).toBe(true); + expect(credits).toEqual([{ ending: "good" }]); + expect(said).toContain("lighthouse.ending"); + await p.look("beacon"); + expect(said.at(-1)).toBe("beacon.on"); + + const elapsed = performance.now() - t0; + console.log(`[playthrough] recorrido completo: ${elapsed.toFixed(1)} ms`); + expect(elapsed).toBeLessThan(1000); + }); + + it("el onEnter con flag solo se dispara la primera vez", async () => { + const { p, said } = start(); + await p.settle(); + await p.goThrough("to-cove"); + await p.goThrough("to-beach"); + expect(p.state().sceneId).toBe("beach"); + expect(said.filter((k) => k === "beach.intro")).toHaveLength(1); + }); + + it("la opcion once desaparece tras elegirla y la siembra no se repite", async () => { + const { p } = start(); + await p.settle(); + await p.talk("fisherman"); + expect(p.state().dialogueActive).toBe(true); + await p.choose(1); // saludo, once + await expect(p.choose(1)).rejects.toThrow(/no disponible/); + await p.choose(2); + // La llave sigue en la arena una sola vez aunque se reentre en la escena. + await p.goThrough("to-cove"); + await p.goThrough("to-beach"); + await p.pickUp("key-on-sand"); + expect(p.state().inventory).toEqual(["rusty-key"]); + await p.pickUp("key-on-sand"); + expect(p.state().inventory).toEqual(["rusty-key"]); + }); +}); + +describe("mini-adventure: orden equivocado", () => { + it("usar la llave sin tenerla no abre el cofre", async () => { + const { p } = start(); + await p.settle(); + await p.useItemOn("rusty-key", "chest"); + expect(p.state().flags["chest.open"]).toBeUndefined(); + expect(p.state().inventory).toEqual([]); + }); + + it("el cofre cerrado solo dice que esta cerrado; un item cualquiera no lo abre", async () => { + const { p, said } = start(); + await p.settle(); + await p.use("chest"); + expect(said.at(-1)).toBe("chest.locked"); + await p.goThrough("to-cove"); + await p.pickUp("fish-on-rocks"); + await p.goThrough("to-beach"); + await p.useItemOn("fish", "chest"); + expect(said.at(-1)).toBe("chest.nothing"); + expect(p.state().flags["chest.open"]).toBeUndefined(); + }); + + it("el pescador no ofrece la pista antes de mirar el mapa", async () => { + const { p } = start(); + await p.settle(); + await p.talk("fisherman"); + await expect(p.choose(0)).rejects.toThrow(/no disponible/); + await p.choose(2); + expect(p.state().inventory).toEqual([]); + // Tras mirar el mapa, la misma opcion ya aparece. + await p.look("map"); + await p.talk("fisherman"); + await p.choose(0); + expect(p.state().inventory).toEqual(["lamp-frame"]); + }); + + it("combinar sin los dos items, o items sin regla, no produce nada", async () => { + const { p } = start(); + await p.settle(); + await p.combine("lens", "lamp-frame"); + expect(p.state().inventory).toEqual([]); + await p.pickUp("key-on-sand"); + await p.goThrough("to-cove"); + await p.pickUp("fish-on-rocks"); + await p.combine("rusty-key", "fish"); + expect(p.state().inventory).toEqual(["rusty-key", "fish"]); + }); + + it("la transicion final esta bloqueada sin el guardian y corre `blocked`", async () => { + const { p, said } = start(); + await p.settle(); + await p.goThrough("to-cove"); + await p.goThrough("to-lighthouse"); + expect(p.state().sceneId).toBe("cove"); + expect(said.at(-1)).toBe("lighthouse.locked"); + expect(p.state().flags["game.finished"]).toBeUndefined(); + // Dar al guardian otra cosa que la lampara no abre el paso. + await p.pickUp("fish-on-rocks"); + await p.useItemOn("fish", "keeper"); + await p.goThrough("to-lighthouse"); + expect(p.state().sceneId).toBe("cove"); + expect(credits).toEqual([]); + }); + + it("no se puede recoger un item de otra escena ni cruzar una transicion inexistente", async () => { + const { p } = start(); + await p.settle(); + await p.goThrough("to-cove"); + await p.pickUp("key-on-sand"); + expect(p.state().inventory).toEqual([]); + await expect(p.goThrough("nope")).rejects.toThrow(/no tiene la transicion/); + }); +}); + +describe("mini-adventure: guardar y retomar", () => { + it("una partida nueva desde la instantanea a mitad termina el juego", async () => { + const first = start(); + await first.p.settle(); + await untilLamp(first.p); + await first.p.goThrough("to-cove"); + const snapshot = first.p.save(); + expect(snapshot.sceneId).toBe("cove"); + first.p.dispose(); + + const { p, said } = start(snapshot); + // Restaurar no vuelve a correr ningun onEnter. + await p.settle(); + expect(said).toEqual([]); + expect(p.state()).toMatchObject({ sceneId: "cove", inventory: ["lamp"], dialogueActive: false }); + expect(p.state().flags["map.seen"]).toBe(true); + + await p.useItemOn("lamp", "keeper"); + await p.goThrough("to-lighthouse"); + expect(p.state().flags["game.finished"]).toBe(true); + expect(credits).toEqual([{ ending: "good" }]); + }); + + it("dos partidas seguidas en el mismo proceso no se contaminan", async () => { + const a = start(); + await a.p.settle(); + await a.p.pickUp("key-on-sand"); + a.p.dispose(); + const { p, said } = start(); + await p.settle(); + expect(p.state()).toMatchObject({ sceneId: "beach", inventory: [] }); + expect(said).toEqual(["beach.intro"]); + await p.pickUp("key-on-sand"); + expect(p.state().inventory).toEqual(["rusty-key"]); + }); +}); + +describe("settle", () => { + it("lanza un error claro si un guion no termina nunca", async () => { + const p = createPlaythrough(miniAdventure, { + handlers: { credits: () => new Promise(() => {}) }, + }); + pt = p; + p.runtime.runScript([{ call: "credits" }]); + await expect(p.settle()).rejects.toThrow(/no converge/); + }); +}); diff --git a/packages/engine-core/src/__tests__/npcs.test.ts b/packages/engine-core/src/__tests__/npcs.test.ts new file mode 100644 index 0000000..d417146 --- /dev/null +++ b/packages/engine-core/src/__tests__/npcs.test.ts @@ -0,0 +1,172 @@ +import { describe, it, expect, vi, afterEach, beforeEach } from "vitest"; +import { + act, + cond, + createGameRuntime, + dialogue, + getAvailableVerbs, + getConditionContext, + getDefaultVerb, + getSceneState, + getWorldState, + isHotspotVisible, + npcToHotspot, + otherwise, + toRuntimeScene, + useDialogStore, + type GameEvent, + type GameRuntime, + type GameSceneNpc, +} from "../index"; +import { HeadlessClock } from "../ports/headlessClock"; +import { flush, makeScene, resetStores } from "./sequencerHarness"; + +const npc = (extra: Partial = {}): GameSceneNpc => ({ + id: "guard", + name: "npc.guard", + characterId: "guard-char", + position: [2, 0, 3], + ...extra, +}); + +let rt: GameRuntime | undefined; +beforeEach(resetStores); +afterEach(() => { + rt?.dispose(); + rt = undefined; + resetStores(); + vi.restoreAllMocks(); +}); + +describe("npcToHotspot", () => { + it("proyecta id, nombre, posicion y campos opcionales", () => { + const h = npcToHotspot( + npc({ hasCollision: true, approach: [1, 0, 1], visibleWhen: cond.flag("x") }), + ); + expect(h).toMatchObject({ + id: "guard", + label: "npc.guard", + position: [2, 2, 3], + hasCollision: true, + approach: [1, 0, 1], + visibleWhen: { flag: "x" }, + }); + expect(h.halfSize).toHaveLength(3); + expect(h.verbs).toBeUndefined(); + }); + + it("no anade claves opcionales ausentes", () => { + expect(Object.keys(npcToHotspot(npc())).sort()).toEqual(["halfSize", "id", "label", "position"]); + }); + + it("dialogueId equivale a verbs.talk con startDialogue", () => { + const h = npcToHotspot(npc({ dialogueId: "chat" })); + expect(h.verbs?.talk).toEqual([{ do: [{ startDialogue: "chat" }] }]); + expect(getDefaultVerb(h, getConditionContext())).toBe("talk"); + }); + + it("dialogueId conserva los otros verbos propios", () => { + const look = [otherwise(act.emit("looked"))]; + const h = npcToHotspot(npc({ dialogueId: "chat", verbs: { look } })); + expect(h.verbs?.look).toBe(look); + expect(getAvailableVerbs(h, getConditionContext())).toEqual(["talk", "look"]); + }); + + it("un verbs.talk explicito gana sobre dialogueId", () => { + const talk = [otherwise(act.emit("custom-talk"))]; + expect(npcToHotspot(npc({ dialogueId: "chat", verbs: { talk } })).verbs?.talk).toBe(talk); + }); + + it("no muta el NPC y conserva useItem", () => { + const verbs = { look: [otherwise(act.emit("l"))] }; + const useItem = { key: [otherwise(act.emit("k"))] }; + const n = npc({ dialogueId: "chat", verbs, useItem }); + const h = npcToHotspot(n); + expect(n.verbs).toBe(verbs); + expect(verbs).not.toHaveProperty("talk"); + expect(h.useItem).toBe(useItem); + }); + + it("visibleWhen condiciona la visibilidad del hotspot proyectado", () => { + const h = npcToHotspot(npc({ visibleWhen: cond.flag("shown") })); + expect(isHotspotVisible(h, getConditionContext())).toBe(false); + getWorldState().setFlag("shown", true); + expect(isHotspotVisible(h, getConditionContext())).toBe(true); + }); +}); + +describe("toRuntimeScene con npcs", () => { + it("anade los NPCs a hotspots tras los propios y conserva npcs", () => { + const hotspots = [ + { id: "door", label: "d", position: [0, 0, 0], halfSize: [1, 1, 1] }, + ] as never; + const npcs = [npc()]; + const scene = toRuntimeScene(makeScene("s", { hotspots, npcs })); + expect(scene.hotspots?.map((h) => h.id)).toEqual(["door", "guard"]); + expect(scene.npcs).toBe(npcs); + }); + + it("sin npcs, hotspots es la misma referencia y npcs no existe", () => { + const hotspots = [] as never; + const scene = toRuntimeScene(makeScene("s", { hotspots })); + expect(scene.hotspots).toBe(hotspots); + expect(scene.npcs).toBeUndefined(); + expect(toRuntimeScene(makeScene("plain")).hotspots).toBeUndefined(); + }); +}); + +describe("hotspot:interact con un NPC", () => { + function start(npcs: GameSceneNpc[]) { + rt = createGameRuntime({ + scenes: [makeScene("npc-a", { npcs })], + clock: new HeadlessClock(), + instantWalk: true, + }); + rt.executeCommand({ type: "scene:set", sceneId: "npc-a" }); + const events: GameEvent[] = []; + rt.on("hotspot:interacted", (e) => events.push(e as GameEvent)); + rt.on("hotspot:noAction", (e) => events.push(e as GameEvent)); + rt.on("custom", (e) => events.push(e as GameEvent)); + return events; + } + + it("la escena activa lleva el NPC como hotspot", () => { + start([npc()]); + expect(getSceneState().scene.hotspots?.map((h) => h.id)).toEqual(["guard"]); + }); + + it("ejecuta los verbos del NPC", async () => { + const events = start([npc({ verbs: { look: [otherwise(act.emit("looked"))] } })]); + rt!.executeCommand({ type: "hotspot:interact", hotspotId: "guard", verb: "look" }); + await flush(); + expect(events.map((e) => e.type)).toEqual(["hotspot:interacted", "custom"]); + }); + + it("un NPC con visibleWhen falso responde hidden", async () => { + const events = start([npc({ visibleWhen: cond.flag("shown"), verbs: { look: [otherwise()] } })]); + rt!.executeCommand({ type: "hotspot:interact", hotspotId: "guard", verb: "look" }); + await flush(); + expect(events).toEqual([ + { type: "hotspot:noAction", hotspotId: "guard", verb: "look", reason: "hidden" }, + ]); + }); + + it("talk con dialogueId arranca el dialogo del NPC", async () => { + rt = createGameRuntime({ + scenes: [makeScene("npc-d", { npcs: [npc({ dialogueId: "guard-chat" })] })], + dialogues: [ + dialogue.define("guard-chat", "n1", dialogue.node("n1", { speaker: "guard", line: "guard.hi" })), + ], + clock: new HeadlessClock(), + instantWalk: true, + }); + rt.executeCommand({ type: "scene:set", sceneId: "npc-d" }); + rt.executeCommand({ type: "hotspot:interact", hotspotId: "guard", verb: "talk" }); + await flush(); + expect(useDialogStore.getState().visible).toBe(true); + expect(useDialogStore.getState().key).toBe("guard.hi"); + expect(useDialogStore.getState().speaker).toBe("guard"); + rt.executeCommand({ type: "dialog:dismiss" }); + await flush(); + }); +}); diff --git a/packages/engine-core/src/__tests__/reactiveInventoryPlacedStores.test.ts b/packages/engine-core/src/__tests__/reactiveInventoryPlacedStores.test.ts new file mode 100644 index 0000000..cb8ef01 --- /dev/null +++ b/packages/engine-core/src/__tests__/reactiveInventoryPlacedStores.test.ts @@ -0,0 +1,295 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { + useInventoryStateStore, + getInventoryState, + usePlacedItemsStateStore, + getPlacedItemsState, + selectPlacedItemsForScene, + loadInventorySlotsState, + saveInventorySlotsState, + loadPlacedItemsState, + savePlacedItemsState, + type KeyValueStoragePort, + type PlacedSceneItem, +} from "../index"; + +function memStorage(initial: Record = {}): KeyValueStoragePort & { + data: Record; +} { + const data = { ...initial }; + return { + data, + getItem: (k) => (k in data ? data[k] : null), + setItem: (k, v) => { + data[k] = v; + }, + removeItem: (k) => { + delete data[k]; + }, + }; +} + +const gb = { id: "gameboy", name: "Gameboy", spriteUrl: "/assets/gameboy/gameboy.png" }; +const key = { id: "gold-key", name: "Llave dorada", spriteUrl: "/assets/key/gold-key.png" }; + +function placed(id: string, sceneId?: string): PlacedSceneItem { + return { + id, + itemId: "trophy", + interactionId: "x", + name: "Trophy", + spriteUrl: "/t.png", + worldPosition: [1, 2, 3], + canPickup: true, + sceneId, + }; +} + +beforeEach(() => { + useInventoryStateStore.getState().reset(9); + usePlacedItemsStateStore.getState().reset(); +}); + +describe("inventory reactive store", () => { + it("starts with 9 empty slots", () => { + expect(getInventoryState().slots).toHaveLength(9); + expect(getInventoryState().slots.every((s) => s === null)).toBe(true); + }); + + it("addItem puts the item in the first empty slot", () => { + expect(getInventoryState().addItem(gb)).toBe(true); + expect(getInventoryState().slots[0]).toEqual({ ...gb, quantity: 1 }); + }); + + it("addItem stacks an existing id", () => { + getInventoryState().addItem(gb); + getInventoryState().addItem(key); + getInventoryState().addItem(gb); + expect(getInventoryState().slots[0]?.quantity).toBe(2); + expect(getInventoryState().slots[1]?.id).toBe("gold-key"); + }); + + it("addItem returns false when full and leaves state unchanged", () => { + useInventoryStateStore.getState().reset(1); + expect(getInventoryState().addItem(gb)).toBe(true); + const before = getInventoryState().slots; + expect(getInventoryState().addItem(key)).toBe(false); + expect(getInventoryState().slots).toBe(before); + }); + + it("addItem still stacks when otherwise full", () => { + useInventoryStateStore.getState().reset(1); + getInventoryState().addItem(gb); + expect(getInventoryState().addItem(gb)).toBe(true); + expect(getInventoryState().slots[0]?.quantity).toBe(2); + }); + + it("removeOne decrements then empties the slot", () => { + getInventoryState().addItem(gb); + getInventoryState().addItem(gb); + getInventoryState().removeOne(0); + expect(getInventoryState().slots[0]?.quantity).toBe(1); + getInventoryState().removeOne(0); + expect(getInventoryState().slots[0]).toBeNull(); + }); + + it("removeOne on empty/invalid slot is a no-op without notifying", () => { + const listener = vi.fn(); + const unsub = useInventoryStateStore.subscribe(listener); + getInventoryState().removeOne(3); + getInventoryState().removeOne(99); + expect(listener).not.toHaveBeenCalled(); + unsub(); + }); + + it("setSlots replaces all slots", () => { + getInventoryState().setSlots([{ ...gb, quantity: 3 }, null]); + expect(getInventoryState().slots).toHaveLength(2); + expect(getInventoryState().slots[0]?.quantity).toBe(3); + }); + + it("setSlotCount pads and truncates", () => { + getInventoryState().addItem(gb); + getInventoryState().setSlotCount(12); + expect(getInventoryState().slots).toHaveLength(12); + getInventoryState().setSlotCount(2); + expect(getInventoryState().slots).toHaveLength(2); + expect(getInventoryState().slots[0]?.id).toBe("gameboy"); + expect(getInventoryState().slotCount).toBe(2); + }); + + it("reset empties and optionally changes the slot count", () => { + getInventoryState().addItem(gb); + getInventoryState().reset(4); + expect(getInventoryState().slots).toEqual([null, null, null, null]); + }); + + it("subscribers are notified of changes and can unsubscribe", () => { + const listener = vi.fn(); + const unsub = useInventoryStateStore.subscribe(listener); + getInventoryState().addItem(gb); + expect(listener).toHaveBeenCalledTimes(1); + expect(listener.mock.calls[0][0].slots[0].id).toBe("gameboy"); + unsub(); + getInventoryState().addItem(key); + expect(listener).toHaveBeenCalledTimes(1); + }); +}); + +describe("placed items reactive store", () => { + it("add, remove by id and set", () => { + const s = getPlacedItemsState(); + s.addItem(placed("a", "s1")); + s.addItem(placed("b", "s2")); + expect(getPlacedItemsState().items.map((i) => i.id)).toEqual(["a", "b"]); + getPlacedItemsState().removeItem("a"); + expect(getPlacedItemsState().items.map((i) => i.id)).toEqual(["b"]); + getPlacedItemsState().setItems([placed("z")]); + expect(getPlacedItemsState().items.map((i) => i.id)).toEqual(["z"]); + }); + + it("updateItemPosition changes one axis immutably", () => { + getPlacedItemsState().addItem(placed("a", "s1")); + const original = getPlacedItemsState().items[0]; + getPlacedItemsState().updateItemPosition("a", 2, 9); + expect(getPlacedItemsState().items[0].worldPosition).toEqual([1, 2, 9]); + expect(original.worldPosition).toEqual([1, 2, 3]); + }); + + it("setItemPosition replaces the whole position", () => { + getPlacedItemsState().addItem(placed("a", "s1")); + getPlacedItemsState().setItemPosition("a", [7, 8, 9]); + expect(getPlacedItemsState().items[0].worldPosition).toEqual([7, 8, 9]); + }); + + it("selectPlacedItemsForScene filters by sceneId", () => { + const items = [placed("a", "s1"), placed("b", "s2"), placed("c", "s1"), placed("d")]; + expect(selectPlacedItemsForScene(items, "s1").map((i) => i.id)).toEqual(["a", "c"]); + expect(selectPlacedItemsForScene(items, "none")).toEqual([]); + }); + + it("seeded scenes: mark, query, idempotent", () => { + expect(getPlacedItemsState().isSceneSeeded("room")).toBe(false); + getPlacedItemsState().markSceneSeeded("room"); + getPlacedItemsState().markSceneSeeded("room"); + expect(getPlacedItemsState().isSceneSeeded("room")).toBe(true); + expect(getPlacedItemsState().isSceneSeeded("other")).toBe(false); + expect(getPlacedItemsState().seededSceneIds).toEqual(["room"]); + }); + + it("reset clears items and seeded scenes", () => { + getPlacedItemsState().addItem(placed("a", "s1")); + getPlacedItemsState().markSceneSeeded("s1"); + getPlacedItemsState().reset(); + expect(getPlacedItemsState().items).toEqual([]); + expect(getPlacedItemsState().seededSceneIds).toEqual([]); + }); + + it("subscribers are notified of changes", () => { + const listener = vi.fn(); + const unsub = usePlacedItemsStateStore.subscribe(listener); + getPlacedItemsState().addItem(placed("a", "s1")); + getPlacedItemsState().markSceneSeeded("s1"); + expect(listener).toHaveBeenCalledTimes(2); + unsub(); + }); +}); + +describe("persistence by port", () => { + it("round-trips slots", () => { + const st = memStorage(); + const slots = [{ ...gb, quantity: 2 }, null, { ...key, quantity: 1 }]; + saveInventorySlotsState(st, slots); + expect(loadInventorySlotsState(st)).toEqual(slots); + }); + + it("reads the exact legacy slots format (plain JSON array under 'inventory-slots')", () => { + const st = memStorage({ + "inventory-slots": + '[{"id":"gameboy","name":"Gameboy","spriteUrl":"/assets/gameboy/gameboy.png","quantity":1},null,null]', + }); + const slots = loadInventorySlotsState(st); + expect(slots).toHaveLength(3); + expect(slots?.[0]?.id).toBe("gameboy"); + expect(slots?.[1]).toBeNull(); + }); + + it("writes slots as a plain JSON array under 'inventory-slots'", () => { + const st = memStorage(); + saveInventorySlotsState(st, [null, null]); + expect(st.data["inventory-slots"]).toBe("[null,null]"); + }); + + it("slots: corrupt JSON, wrong shape and missing key return null", () => { + expect(loadInventorySlotsState(memStorage({ "inventory-slots": "{oops" }))).toBeNull(); + expect(loadInventorySlotsState(memStorage({ "inventory-slots": '{"a":1}' }))).toBeNull(); + expect(loadInventorySlotsState(memStorage())).toBeNull(); + }); + + it("slots: honours a custom key and a throwing port", () => { + const st = memStorage(); + saveInventorySlotsState(st, [null], "custom"); + expect(loadInventorySlotsState(st, "custom")).toEqual([null]); + const bad: KeyValueStoragePort = { + getItem: () => { + throw new Error("denied"); + }, + setItem: () => {}, + }; + expect(loadInventorySlotsState(bad)).toBeNull(); + }); + + it("reads the exact legacy zustand persist format with initialItemsCreated=true", () => { + const legacy = + '{"state":{"items":[{"id":"trophy-ground","itemId":"trophy","interactionId":"trophy-ground-pickup","name":"Trophy","spriteUrl":"/assets/trophy/trophy.png","worldPosition":[5.5,-1.3,22],"canPickup":true,"hasCollision":true,"collisionHalfSize":[0.5,0.8,0.5],"sceneId":"personalRoom"}],"initialItemsCreated":true},"version":0}'; + const st = memStorage({ "placed-items-state": legacy }); + const loaded = loadPlacedItemsState(st, { legacySeededSceneId: "personalRoom" }); + expect(loaded?.items).toHaveLength(1); + expect(loaded?.items[0].id).toBe("trophy-ground"); + expect(loaded?.seededSceneIds).toEqual(["personalRoom"]); + }); + + it("legacy flag true without legacySeededSceneId seeds nothing; false seeds nothing", () => { + const t = memStorage({ + "placed-items-state": '{"state":{"items":[],"initialItemsCreated":true},"version":0}', + }); + expect(loadPlacedItemsState(t)?.seededSceneIds).toEqual([]); + const f = memStorage({ + "placed-items-state": '{"state":{"items":[],"initialItemsCreated":false},"version":0}', + }); + expect(loadPlacedItemsState(f, { legacySeededSceneId: "room" })?.seededSceneIds).toEqual([]); + }); + + it("round-trips placed items and seeded scenes in the zustand persist wrapper", () => { + const st = memStorage(); + const data = { items: [placed("a", "s1")], seededSceneIds: ["s1"] }; + savePlacedItemsState(st, data); + expect(JSON.parse(st.data["placed-items-state"])).toEqual({ + state: data, + version: 0, + }); + expect(loadPlacedItemsState(st, { legacySeededSceneId: "ignored" })).toEqual(data); + }); + + it("placed items: corrupt JSON and unexpected shapes return null", () => { + const k = "placed-items-state"; + expect(loadPlacedItemsState(memStorage({ [k]: "not json" }))).toBeNull(); + expect(loadPlacedItemsState(memStorage({ [k]: "[]" }))).toBeNull(); + expect(loadPlacedItemsState(memStorage({ [k]: '{"state":{"items":3}}' }))).toBeNull(); + expect(loadPlacedItemsState(memStorage({ [k]: '{"version":0}' }))).toBeNull(); + expect(loadPlacedItemsState(memStorage())).toBeNull(); + }); + + it("hydrates both stores from persisted data", () => { + const st = memStorage(); + saveInventorySlotsState(st, [{ ...gb, quantity: 4 }, null]); + savePlacedItemsState(st, { items: [placed("a", "s1")], seededSceneIds: ["s1"] }); + getInventoryState().setSlots(loadInventorySlotsState(st) ?? []); + const p = loadPlacedItemsState(st); + getPlacedItemsState().setItems(p?.items ?? []); + getPlacedItemsState().setSeededSceneIds(p?.seededSceneIds ?? []); + expect(getInventoryState().slots[0]?.quantity).toBe(4); + expect(getPlacedItemsState().isSceneSeeded("s1")).toBe(true); + expect(selectPlacedItemsForScene(getPlacedItemsState().items, "s1")).toHaveLength(1); + }); +}); diff --git a/packages/engine-core/src/__tests__/saveGame.test.ts b/packages/engine-core/src/__tests__/saveGame.test.ts new file mode 100644 index 0000000..fba40f1 --- /dev/null +++ b/packages/engine-core/src/__tests__/saveGame.test.ts @@ -0,0 +1,459 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { + SAVE_FORMAT_VERSION, + SAVE_STORAGE_KEY, + applySaveMigrations, + applySnapshot, + captureSnapshot, + clearSave, + createGameRuntime, + getInventoryState, + getPlacedItemsState, + getWorldState, + loadGame, + migrateLegacySave, + saveGame, + useInventoryStateStore, + usePlacedItemsStateStore, + useSceneStore, + type GameRuntime, + type GameSceneConfig, + type GameSnapshot, + type KeyValueStoragePort, +} from "../index"; + +function makeScene(id: string, spawn: [number, number, number] = [0, 0, 0]): GameSceneConfig { + return { + id, + label: id, + background: "/bg.png", + playerSpawn: spawn, + ground: { minX: -5, maxX: 5, minZ: -5, maxZ: 5, y: 0 }, + walls: [], + interactions: [], + }; +} + +function memStorage(initial: Record = {}) { + const data: Record = { ...initial }; + const removeItem = vi.fn((k: string) => { + delete data[k]; + }); + const storage: KeyValueStoragePort & { data: Record; clear: () => void } = { + data, + getItem: (k) => (k in data ? data[k]! : null), + setItem: (k, v) => { + data[k] = v; + }, + removeItem, + clear: vi.fn(), + }; + return storage; +} + +const gb = { id: "gameboy", name: "Gameboy", spriteUrl: "/gb.png", quantity: 2 }; +const trophy = { + id: "trophy-ground", + itemId: "trophy", + interactionId: "trophy-ground-pickup", + name: "Trophy", + spriteUrl: "/t.png", + worldPosition: [5.5, -1.3, 22] as [number, number, number], + canPickup: true, + sceneId: "kitchen", +}; + +let rt: GameRuntime | null = null; + +function resetAll() { + useInventoryStateStore.getState().reset(9); + usePlacedItemsStateStore.getState().reset(); + getWorldState().reset(); + useSceneStore.setState({ sceneId: "", playerPosition: [0, 0, 0] }); +} + +function boot(storage?: KeyValueStoragePort) { + rt = createGameRuntime({ + scenes: [makeScene("hall", [1, 0, 1]), makeScene("kitchen", [2, 0, 2])], + storage, + }); + return rt; +} + +beforeEach(resetAll); +afterEach(() => { + rt?.dispose(); + rt = null; + resetAll(); + vi.restoreAllMocks(); +}); + +function fillState() { + useInventoryStateStore.getState().setSlots([gb, null, null]); + getPlacedItemsState().setItems([trophy]); + getPlacedItemsState().setSeededSceneIds(["kitchen"]); + getWorldState().setFlag("metGuard", true); + getWorldState().setFlag("coins", 3); + getWorldState().markSceneVisited("hall"); +} + +describe("captureSnapshot / applySnapshot", () => { + it("version es el primer campo y vale SAVE_FORMAT_VERSION", () => { + boot(); + rt!.executeCommand({ type: "scene:set", sceneId: "hall" }); + const snap = captureSnapshot(); + expect(Object.keys(snap)[0]).toBe("version"); + expect(snap.version).toBe(SAVE_FORMAT_VERSION); + expect(snap.sceneId).toBe("hall"); + expect(snap.playerPosition).toEqual([1, 0, 1]); + expect(snap.extra).toBeUndefined(); + }); + + it("ida y vuelta completa", () => { + boot(); + rt!.executeCommand({ type: "scene:set", sceneId: "kitchen", spawnPosition: [3, 0, -2] }); + fillState(); + const snap = JSON.parse(JSON.stringify(captureSnapshot({ "door-states": { a: 1 } }))); + resetAll(); + rt!.executeCommand({ type: "scene:set", sceneId: "hall" }); + expect(applySnapshot(snap)).toBe(true); + expect(useSceneStore.getState().sceneId).toBe("kitchen"); + expect(useSceneStore.getState().playerPosition).toEqual([3, 0, -2]); + expect(getInventoryState().slots).toEqual([gb, null, null]); + expect(getPlacedItemsState().items).toEqual([trophy]); + expect(getPlacedItemsState().seededSceneIds).toEqual(["kitchen"]); + expect(getWorldState().flags).toEqual({ metGuard: true, coins: 3 }); + expect(getWorldState().visitedSceneIds).toContain("hall"); + }); + + it("restaura el estado ANTES de fijar la escena", () => { + boot(); + const snap: GameSnapshot = { + version: 1, + sceneId: "kitchen", + inventory: [gb], + placedItems: [trophy], + seededSceneIds: ["kitchen"], + flags: { f: 1 }, + visitedSceneIds: [], + }; + const seen: unknown[] = []; + rt!.on("scene:changed", () => { + seen.push({ + flags: { ...getWorldState().flags }, + inv: getInventoryState().slots.length, + items: getPlacedItemsState().items.length, + }); + }); + applySnapshot(snap); + expect(seen).toEqual([{ flags: { f: 1 }, inv: 1, items: 1 }]); + }); + + it("sin playerPosition usa el spawn por defecto de la escena", () => { + boot(); + applySnapshot({ + version: 1, + sceneId: "kitchen", + inventory: [], + placedItems: [], + seededSceneIds: [], + flags: {}, + visitedSceneIds: [], + }); + expect(useSceneStore.getState().playerPosition).toEqual([2, 0, 2]); + }); + + it("escena no registrada: no cambia de escena, avisa y devuelve false", () => { + boot(); + rt!.executeCommand({ type: "scene:set", sceneId: "hall" }); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const ok = applySnapshot({ + version: 1, + sceneId: "ghost", + inventory: [], + placedItems: [], + seededSceneIds: [], + flags: { x: true }, + visitedSceneIds: [], + }); + expect(ok).toBe(false); + expect(warn).toHaveBeenCalled(); + expect(useSceneStore.getState().sceneId).toBe("hall"); + // No se aplica a medias: el resto del estado tampoco cambia. + expect(getWorldState().flags).toEqual({}); + }); +}); + +describe("saveGame / loadGame / clearSave", () => { + it("guarda JSON con version primero bajo pointclick-save", () => { + boot(); + rt!.executeCommand({ type: "scene:set", sceneId: "hall" }); + const st = memStorage(); + saveGame(st, { extra: { k: 1 } }); + expect(Object.keys(st.data)).toEqual([SAVE_STORAGE_KEY]); + expect(st.data["pointclick-save"]!.startsWith('{"version":1,')).toBe(true); + expect(loadGame(st)!.extra).toEqual({ k: 1 }); + }); + + it("clave personalizada", () => { + const st = memStorage(); + saveGame(st, { key: "slot2" }); + expect(Object.keys(st.data)).toEqual(["slot2"]); + expect(loadGame(st)).toBeNull(); + expect(loadGame(st, { key: "slot2" })).not.toBeNull(); + }); + + it("loadGame: sin clave, JSON corrupto, no objeto y forma inesperada dan null sin lanzar", () => { + expect(loadGame(memStorage())).toBeNull(); + expect(loadGame(memStorage({ [SAVE_STORAGE_KEY]: "{no json" }))).toBeNull(); + expect(loadGame(memStorage({ [SAVE_STORAGE_KEY]: "[1,2]" }))).toBeNull(); + expect(loadGame(memStorage({ [SAVE_STORAGE_KEY]: '{"version":1,"sceneId":3}' }))).toBeNull(); + expect(loadGame(memStorage({ [SAVE_STORAGE_KEY]: '{"sceneId":"a"}' }))).toBeNull(); + }); + + it("loadGame: versión futura da null", () => { + const snap = { ...captureSnapshot(), version: SAVE_FORMAT_VERSION + 1 }; + expect(loadGame(memStorage({ [SAVE_STORAGE_KEY]: JSON.stringify(snap) }))).toBeNull(); + }); + + it("loadGame: getItem que lanza da null", () => { + const st: KeyValueStoragePort = { + getItem: () => { + throw new Error("boom"); + }, + setItem: () => {}, + }; + expect(loadGame(st)).toBeNull(); + }); + + it("clearSave borra solo su clave y nunca llama a clear()", () => { + const st = memStorage({ other: "x", [SAVE_STORAGE_KEY]: "{}" }); + clearSave(st); + expect(st.data).toEqual({ other: "x" }); + expect(st.clear).not.toHaveBeenCalled(); + }); + + it("clearSave sin removeItem vacía la clave y loadGame da null", () => { + const data: Record = {}; + const st: KeyValueStoragePort = { + getItem: (k) => data[k] ?? null, + setItem: (k, v) => { + data[k] = v; + }, + }; + saveGame(st); + clearSave(st); + expect(loadGame(st)).toBeNull(); + }); +}); + +describe("tabla de migraciones", () => { + it("la tabla real está vacía y la v1 pasa tal cual", () => { + const raw = { version: 1, a: 1 }; + expect(applySaveMigrations(raw)).toEqual(raw); + }); + + it("encadena migraciones inyectadas hasta el objetivo", () => { + const out = applySaveMigrations({ version: 1, n: 0 }, 3, { + 1: (s) => ({ ...s, n: (s.n as number) + 1, a: true }), + 2: (s) => ({ ...s, n: (s.n as number) + 10 }), + }); + expect(out).toEqual({ version: 3, n: 11, a: true }); + }); + + it("falta un eslabón, versión inválida o superior: null", () => { + expect(applySaveMigrations({ version: 1 }, 3, { 1: (s) => s })).toBeNull(); + expect(applySaveMigrations({ version: 0 }, 1)).toBeNull(); + expect(applySaveMigrations({ version: "1" }, 1)).toBeNull(); + expect(applySaveMigrations({ version: 2 }, 1)).toBeNull(); + }); +}); + +describe("migrateLegacySave", () => { + const legacyItems = + '{"state":{"items":[{"id":"trophy-ground","itemId":"trophy","interactionId":"trophy-ground-pickup","name":"Trophy","spriteUrl":"/t.png","worldPosition":[5.5,-1.3,22],"canPickup":true,"sceneId":"kitchen"}],"initialItemsCreated":true},"version":0}'; + const legacySlots = '[{"id":"gameboy","name":"Gameboy","spriteUrl":"/gb.png","quantity":1},null,null]'; + + it("sin ninguna clave antigua: null (las extraKeys no cuentan)", () => { + const st = memStorage({ "door-states": "{}" }); + expect( + migrateLegacySave(st, { defaultSceneId: "hall", extraKeys: ["door-states"] }), + ).toBeNull(); + }); + + it("lee las tres claves antiguas, texto plano de escena, y no escribe ni borra nada", () => { + boot(); + const st = memStorage({ + "inventory-slots": legacySlots, + "current-scene-id": "kitchen", + "placed-items-state": legacyItems, + }); + const before = { ...st.data }; + const snap = migrateLegacySave(st, { + defaultSceneId: "hall", + legacySeededSceneId: "kitchen", + })!; + expect(snap.version).toBe(SAVE_FORMAT_VERSION); + expect(snap.sceneId).toBe("kitchen"); + expect(snap.inventory).toEqual([ + { id: "gameboy", name: "Gameboy", spriteUrl: "/gb.png", quantity: 1 }, + null, + null, + ]); + expect(snap.placedItems).toHaveLength(1); + expect(snap.seededSceneIds).toEqual(["kitchen"]); + expect(snap.flags).toEqual({}); + expect(snap.playerPosition).toEqual([2, 0, 2]); + expect(st.data).toEqual(before); + expect(st.removeItem).not.toHaveBeenCalled(); + }); + + it("claves ausentes: valores neutros; escena no registrada: sin playerPosition", () => { + const st = memStorage({ "inventory-slots": legacySlots }); + const snap = migrateLegacySave(st, { defaultSceneId: "unknownScene" })!; + expect(snap.sceneId).toBe("unknownScene"); + expect(snap.placedItems).toEqual([]); + expect(snap.seededSceneIds).toEqual([]); + expect("playerPosition" in snap).toBe(false); + const only = migrateLegacySave(memStorage({ "current-scene-id": "hall" }), { + defaultSceneId: "x", + })!; + expect(only.sceneId).toBe("hall"); + expect(only.inventory).toHaveLength(9); + expect(only.inventory.every((s) => s === null)).toBe(true); + }); + + it("contenido ilegible se trata como ausente", () => { + const st = memStorage({ "inventory-slots": "{bad", "placed-items-state": "[]" }); + const snap = migrateLegacySave(st, { defaultSceneId: "hall" })!; + expect(snap.sceneId).toBe("hall"); + expect(snap.inventory).toHaveLength(9); + expect(snap.placedItems).toEqual([]); + }); + + it("extraKeys: JSON parseado, texto si no es JSON, ausentes ignoradas", () => { + const st = memStorage({ + "current-scene-id": "hall", + "door-states": '{"state":{"doors":{"d1":true}},"version":0}', + note: "hola mundo", + }); + const snap = migrateLegacySave(st, { + defaultSceneId: "hall", + extraKeys: ["door-states", "note", "missing"], + })!; + expect(snap.extra).toEqual({ + "door-states": { state: { doors: { d1: true } }, version: 0 }, + note: "hola mundo", + }); + }); + + it("la instantánea migrada se puede guardar, cargar y aplicar", () => { + boot(); + const st = memStorage({ "current-scene-id": "kitchen", "inventory-slots": legacySlots }); + const snap = migrateLegacySave(st, { defaultSceneId: "hall" })!; + st.setItem(SAVE_STORAGE_KEY, JSON.stringify(snap)); + expect(applySnapshot(loadGame(st)!)).toBe(true); + expect(useSceneStore.getState().sceneId).toBe("kitchen"); + expect(getInventoryState().slots).toHaveLength(3); + }); +}); + +describe("comandos y eventos", () => { + it("game:save y game:load sin storage: avisan y no hacen nada", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + boot(); + const loaded = vi.fn(); + const saved = vi.fn(); + rt!.on("game:loaded", loaded); + rt!.on("game:saved", saved); + rt!.executeCommand({ type: "game:save" }); + rt!.executeCommand({ type: "game:load" }); + expect(warn).toHaveBeenCalledTimes(2); + expect(loaded).not.toHaveBeenCalled(); + expect(saved).not.toHaveBeenCalled(); + }); + + it("game:save emite game:saved y escribe; game:load restaura y emite game:loaded con extra", () => { + const st = memStorage(); + boot(st); + rt!.executeCommand({ type: "scene:set", sceneId: "kitchen", spawnPosition: [4, 0, 4] }); + fillState(); + const saved = vi.fn(); + const loaded = vi.fn(); + rt!.on("game:saved", saved); + rt!.on("game:loaded", loaded); + rt!.executeCommand({ type: "game:save", extra: { "door-states": { d: 1 } } }); + expect(saved).toHaveBeenCalledTimes(1); + + resetAll(); + rt!.executeCommand({ type: "scene:set", sceneId: "hall" }); + rt!.executeCommand({ type: "game:load" }); + expect(loaded).toHaveBeenCalledWith({ + type: "game:loaded", + found: true, + applied: true, + extra: { "door-states": { d: 1 } }, + }); + expect(useSceneStore.getState().sceneId).toBe("kitchen"); + expect(useSceneStore.getState().playerPosition).toEqual([4, 0, 4]); + expect(getWorldState().flags).toEqual({ metGuard: true, coins: 3 }); + }); + + it("game:load sin partida emite found:false y no cambia nada", () => { + boot(memStorage()); + rt!.executeCommand({ type: "scene:set", sceneId: "hall" }); + const loaded = vi.fn(); + rt!.on("game:loaded", loaded); + rt!.executeCommand({ type: "game:load" }); + expect(loaded).toHaveBeenCalledWith({ type: "game:loaded", found: false }); + expect(useSceneStore.getState().sceneId).toBe("hall"); + }); + + it("game:load con escena guardada no registrada: found true, applied false", () => { + const st = memStorage({ + [SAVE_STORAGE_KEY]: JSON.stringify({ ...captureSnapshot(), sceneId: "ghost" }), + }); + boot(st); + vi.spyOn(console, "warn").mockImplementation(() => {}); + const loaded = vi.fn(); + rt!.on("game:loaded", loaded); + rt!.executeCommand({ type: "game:load" }); + expect(loaded).toHaveBeenCalledWith({ type: "game:loaded", found: true, applied: false }); + }); + + it("game:reset vacía los stores, borra solo la clave de guardado y no cambia de escena", () => { + const st = memStorage({ other: "keep" }); + boot(st); + rt!.executeCommand({ type: "scene:set", sceneId: "kitchen" }); + fillState(); + rt!.executeCommand({ type: "game:save" }); + const reset = vi.fn(); + rt!.on("game:reset", reset); + rt!.executeCommand({ type: "game:reset" }); + expect(reset).toHaveBeenCalledTimes(1); + expect(getInventoryState().slots).toEqual(Array.from({ length: 9 }, () => null)); + expect(getPlacedItemsState().items).toEqual([]); + expect(getPlacedItemsState().seededSceneIds).toEqual([]); + expect(getWorldState().flags).toEqual({}); + expect(getWorldState().visitedSceneIds).toEqual([]); + expect(st.data).toEqual({ other: "keep" }); + expect(st.clear).not.toHaveBeenCalled(); + expect(useSceneStore.getState().sceneId).toBe("kitchen"); + }); + + it("game:reset sin storage resetea los stores sin fallar", () => { + boot(); + fillState(); + rt!.executeCommand({ type: "game:reset" }); + expect(getWorldState().flags).toEqual({}); + }); + + it("saveKey de la config se usa en save/load/reset", () => { + const st = memStorage(); + rt = createGameRuntime({ scenes: [makeScene("hall")], storage: st, saveKey: "mine" }); + rt.executeCommand({ type: "game:save" }); + expect(Object.keys(st.data)).toEqual(["mine"]); + rt.executeCommand({ type: "game:reset" }); + expect(st.data).toEqual({}); + }); +}); diff --git a/packages/engine-core/src/__tests__/sceneRules.test.ts b/packages/engine-core/src/__tests__/sceneRules.test.ts new file mode 100644 index 0000000..af77257 --- /dev/null +++ b/packages/engine-core/src/__tests__/sceneRules.test.ts @@ -0,0 +1,254 @@ +import { describe, it, expect, vi, afterEach, beforeEach } from "vitest"; +import { + act, + branch, + cond, + createGameRuntime, + evaluateTransitionGate, + getConditionContext, + getDeclaredScene, + getInventoryState, + getPlacedItemsState, + getSceneRuleContext, + getWorldState, + otherwise, + resolveEnterScript, + resolveInitialItems, + toRuntimeScene, + type ConditionContext, + type GameEvent, + type GameRuntime, + type GameSceneConfig, + type PlacedSceneItem, + type SceneInitialItem, +} from "../index"; +import { HeadlessClock } from "../ports/headlessClock"; +import { flush, makeItem, makeScene, resetStores } from "./sequencerHarness"; + +const placed = (itemId: string, extra: Partial = {}): PlacedSceneItem => ({ + id: `p-${itemId}`, + itemId, + interactionId: "spot", + name: itemId, + spriteUrl: `/${itemId}.png`, + worldPosition: [0, 0, 0], + canPickup: true, + ...extra, +}); + +const ctx = (extra: Partial = {}): ConditionContext => ({ + flags: {}, + inventory: [], + placedItems: [], + sceneId: "room", + visitedSceneIds: [], + ...extra, +}); + +const trophyRule = cond.all(cond.not(cond.itemPlaced("trophy")), cond.not(cond.hasItem("trophy"))); + +beforeEach(resetStores); + +describe("resolveInitialItems", () => { + it("devuelve null sin initialItems", () => { + expect(resolveInitialItems("room", undefined, ctx())).toBeNull(); + }); + it("devuelve [] con initialItems vacio", () => { + expect(resolveInitialItems("room", [], ctx())).toEqual([]); + }); + it("incluye items sin when", () => { + const out = resolveInitialItems("room", [{ item: placed("a") }, { item: placed("b") }], ctx()); + expect(out?.map((i) => i.itemId)).toEqual(["a", "b"]); + }); + it("filtra por when", () => { + const entries: SceneInitialItem[] = [ + { item: placed("a"), when: cond.flag("on") }, + { item: placed("b"), when: cond.flag("off") }, + ]; + const out = resolveInitialItems("room", entries, ctx({ flags: { on: true } })); + expect(out?.map((i) => i.itemId)).toEqual(["a"]); + }); + it("asigna sceneId solo si falta", () => { + const out = resolveInitialItems( + "room", + [{ item: placed("a") }, { item: placed("b", { sceneId: "other" }) }], + ctx(), + ); + expect(out?.map((i) => i.sceneId)).toEqual(["room", "other"]); + }); + it("no muta el item original", () => { + const item = placed("a"); + resolveInitialItems("room", [{ item }], ctx()); + expect(item.sceneId).toBeUndefined(); + }); + it("regla del trofeo: se siembra si no existe en ninguna escena ni en el inventario", () => { + const entries: SceneInitialItem[] = [{ item: placed("trophy"), when: trophyRule }]; + expect(resolveInitialItems("room", entries, ctx())).toHaveLength(1); + }); + it("regla del trofeo: no se siembra si ya esta colocado en otra escena", () => { + const entries: SceneInitialItem[] = [{ item: placed("trophy"), when: trophyRule }]; + const placedElsewhere = [placed("trophy", { sceneId: "other" })]; + expect(resolveInitialItems("room", entries, ctx({ placedItems: placedElsewhere }))).toEqual([]); + }); + it("regla del trofeo: no se siembra si el jugador lo lleva", () => { + const entries: SceneInitialItem[] = [{ item: placed("trophy"), when: trophyRule }]; + const inventory = [{ id: "trophy", name: "t", spriteUrl: "/t.png", quantity: 1 }]; + expect(resolveInitialItems("room", entries, ctx({ inventory }))).toEqual([]); + }); + it("ignora entradas mal formadas", () => { + const bad = [null, {}, { item: placed("a") }] as unknown as SceneInitialItem[]; + expect(resolveInitialItems("room", bad, ctx())?.map((i) => i.itemId)).toEqual(["a"]); + }); +}); + +describe("resolveEnterScript", () => { + it("null sin onEnter", () => { + expect(resolveEnterScript(undefined, ctx())).toBeNull(); + }); + it("elige la primera rama que se cumple", () => { + const script = resolveEnterScript( + [branch(cond.flag("x"), act.emit("x")), otherwise(act.emit("default"))], + ctx(), + ); + expect(script).toEqual([act.emit("default")]); + }); + it("null si ninguna rama se cumple", () => { + expect(resolveEnterScript([branch(cond.flag("x"), act.emit("x"))], ctx())).toBeNull(); + }); + it("solo la primera vez con not(visited)", () => { + const onEnter = [branch(cond.not(cond.visited("room")), act.emit("welcome"))]; + expect(resolveEnterScript(onEnter, ctx())).not.toBeNull(); + expect(resolveEnterScript(onEnter, ctx({ visitedSceneIds: ["room"] }))).toBeNull(); + }); +}); + +describe("evaluateTransitionGate", () => { + it("permite sin when", () => { + expect(evaluateTransitionGate({}, ctx())).toEqual({ allowed: true }); + }); + it("permite si when se cumple", () => { + expect(evaluateTransitionGate({ when: cond.flag("ok") }, ctx({ flags: { ok: true } }))).toEqual({ + allowed: true, + }); + }); + it("bloquea con el guion blocked si when no se cumple", () => { + const blocked = [act.emit("nope")]; + expect(evaluateTransitionGate({ when: cond.flag("ok"), blocked }, ctx())).toEqual({ + allowed: false, + blocked, + }); + }); + it("bloquea con guion vacio si no hay blocked", () => { + expect(evaluateTransitionGate({ when: cond.flag("ok") }, ctx())).toEqual({ + allowed: false, + blocked: [], + }); + }); +}); + +describe("integracion con el runtime", () => { + let rt: GameRuntime; + afterEach(() => { + rt?.dispose(); + resetStores(); + vi.restoreAllMocks(); + }); + + const start = (scenes: GameSceneConfig[]) => { + rt = createGameRuntime({ + scenes, + items: [makeItem("trophy")], + clock: new HeadlessClock(), + instantWalk: true, + }); + }; + + it("toRuntimeScene conserva initialItems y onEnter", () => { + const cfg = makeScene("r", { + initialItems: [{ item: placed("a") }], + onEnter: [otherwise(act.emit("hi"))], + }); + const scene = toRuntimeScene(cfg); + expect(scene.initialItems).toEqual(cfg.initialItems); + expect(scene.onEnter).toEqual(cfg.onEnter); + }); + + it("una escena sin campos nuevos no los define", () => { + const scene = toRuntimeScene(makeScene("plain")); + expect(scene.initialItems).toBeUndefined(); + expect(scene.onEnter).toBeUndefined(); + expect(scene.transitions).toBeUndefined(); + }); + + it("getDeclaredScene devuelve la escena activa o la registrada", () => { + start([ + makeScene("sr-a", { onEnter: [otherwise(act.emit("a"))] }), + makeScene("sr-b", { initialItems: [{ item: placed("a") }] }), + ]); + rt.executeCommand({ type: "scene:set", sceneId: "sr-a" }); + expect(getDeclaredScene("sr-a")?.onEnter).toHaveLength(1); + expect(getDeclaredScene("sr-b")?.initialItems).toHaveLength(1); + expect(getDeclaredScene("sr-missing")).toBeUndefined(); + }); + + it("la escena activa en el store lleva los campos declarativos", () => { + start([makeScene("sr-c", { initialItems: [{ item: placed("a") }], onEnter: [otherwise([])] })]); + rt.executeCommand({ type: "scene:set", sceneId: "sr-c" }); + const declared = getDeclaredScene("sr-c"); + expect(declared?.initialItems).toHaveLength(1); + expect(declared?.onEnter).toHaveLength(1); + }); + + it("getSceneRuleContext sustituye sceneId y placedItems", () => { + start([makeScene("sr-d")]); + rt.executeCommand({ type: "scene:set", sceneId: "sr-d" }); + const c = getSceneRuleContext("other", [placed("z")]); + expect(c.sceneId).toBe("other"); + expect(c.placedItems.map((i) => i.itemId)).toEqual(["z"]); + expect(getSceneRuleContext("other").placedItems).toEqual(getConditionContext().placedItems); + }); + + it("el guion de onEnter se ejecuta con runScript", async () => { + start([makeScene("sr-e", { onEnter: [otherwise(act.setFlag("entered"))] })]); + rt.executeCommand({ type: "scene:set", sceneId: "sr-e" }); + const script = resolveEnterScript(getDeclaredScene("sr-e")?.onEnter, getSceneRuleContext("sr-e")); + rt.runScript(script ?? []); + await flush(); + expect(getWorldState().flags.entered).toBe(true); + }); + + it("el guion blocked se ejecuta con runScript", async () => { + start([makeScene("sr-f")]); + rt.executeCommand({ type: "scene:set", sceneId: "sr-f" }); + const events: GameEvent[] = []; + rt.on("custom", (e) => events.push(e as GameEvent)); + const gate = evaluateTransitionGate( + { when: cond.hasItem("trophy"), blocked: [act.emit("locked")] }, + getSceneRuleContext("sr-f"), + ); + expect(gate.allowed).toBe(false); + if (!gate.allowed) rt.runScript(gate.blocked); + await flush(); + expect(events.map((e) => (e as { name: string }).name)).toEqual(["locked"]); + }); + + it("la transicion se permite al cumplirse when con el estado real", () => { + start([makeScene("sr-g")]); + rt.executeCommand({ type: "scene:set", sceneId: "sr-g" }); + const t = { when: cond.hasItem("trophy") }; + expect(evaluateTransitionGate(t, getSceneRuleContext("sr-g")).allowed).toBe(false); + getInventoryState().addItem({ id: "trophy", name: "t", spriteUrl: "/t.png" }); + expect(evaluateTransitionGate(t, getSceneRuleContext("sr-g")).allowed).toBe(true); + }); + + it("la regla del trofeo usa el estado real de los stores", () => { + start([makeScene("sr-h")]); + rt.executeCommand({ type: "scene:set", sceneId: "sr-h" }); + const entries: SceneInitialItem[] = [{ item: placed("trophy"), when: trophyRule }]; + const seed = () => + resolveInitialItems("sr-h", entries, getSceneRuleContext("sr-h", getPlacedItemsState().items)); + expect(seed()).toHaveLength(1); + getPlacedItemsState().setItems([placed("trophy", { sceneId: "sr-other" })]); + expect(seed()).toEqual([]); + }); +}); diff --git a/packages/engine-core/src/__tests__/sequencerActions.test.ts b/packages/engine-core/src/__tests__/sequencerActions.test.ts new file mode 100644 index 0000000..d0a468d --- /dev/null +++ b/packages/engine-core/src/__tests__/sequencerActions.test.ts @@ -0,0 +1,340 @@ +import { describe, it, expect, vi, afterEach, beforeEach } from "vitest"; +import { + act, + getDialogState, + getGameState, + getInventoryState, + getPlacedItemsState, + getWorldState, + type GameRuntime, + type PlacedSceneItem, +} from "../index"; +import { dismissDialog, flush, getInputLockState, resetStores, setup, type Harness } from "./sequencerHarness"; +import type { HeadlessClock } from "../ports/headlessClock"; + +let h: Harness; +let rt: GameRuntime; +let clock: HeadlessClock; + +function start(opts?: Parameters[0]) { + h = setup(opts); + rt = h.rt; + clock = h.clock; +} + +beforeEach(resetStores); +afterEach(() => { + h?.rt.dispose(); + resetStores(); + vi.restoreAllMocks(); +}); + +const placed: PlacedSceneItem = { + id: "p1", + itemId: "seq-key", + interactionId: "table", + name: "Key", + spriteUrl: "/k.png", + worldPosition: [0, 0, 0], + canPickup: true, + sceneId: "seq-a", +}; + +describe("secuenciador: acciones", () => { + it("setFlag pone true por defecto", async () => { + start(); + const run = rt.runScript([act.setFlag("seen")]); + await flush(); + expect(getWorldState().flags.seen).toBe(true); + expect(await run.done).toBe("finished"); + }); + + it("setFlag con valor explicito", async () => { + start(); + rt.runScript([act.setFlag("n", 3), act.setFlag("s", "x")]); + await flush(); + expect(getWorldState().flags).toEqual({ n: 3, s: "x" }); + }); + + it("changeScene sin spawn usa el de la escena", async () => { + start(); + rt.runScript([act.changeScene("seq-b")]); + await flush(); + expect(getGameState().sceneId).toBe("seq-b"); + expect(getGameState().playerPosition).toEqual([-1, 0, -1]); + }); + + it("changeScene con spawnPosition", async () => { + start(); + rt.runScript([act.changeScene("seq-b", [2, 0, 2])]); + await flush(); + expect(getGameState().playerPosition).toEqual([2, 0, 2]); + }); + + it("giveItem toma nombre y sprite del registro y emite item:pickedUp", async () => { + start({ record: ["item:pickedUp"] }); + rt.runScript([act.giveItem("seq-key")]); + await flush(); + expect(getInventoryState().slots[0]).toMatchObject({ id: "seq-key", name: "Name seq-key", spriteUrl: "/seq-key.png" }); + expect(h.events).toEqual([{ type: "item:pickedUp", itemId: "seq-key", quantity: 1 }]); + }); + + it("giveItem de un item no registrado avisa y continua", async () => { + start(); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const run = rt.runScript([act.giveItem("nope"), act.setFlag("after")]); + await flush(); + expect(warn).toHaveBeenCalled(); + expect(getWorldState().flags.after).toBe(true); + expect(await run.done).toBe("finished"); + }); + + it("giveItem con inventario lleno avisa, emite inventory:full y continua", async () => { + start({ record: ["inventory:full", "item:pickedUp"] }); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + getInventoryState().setSlotCount(1); + getInventoryState().addItem({ id: "other", name: "O", spriteUrl: "/o.png" }); + const run = rt.runScript([act.giveItem("seq-key"), act.setFlag("after")]); + await flush(); + expect(warn).toHaveBeenCalled(); + expect(h.events).toEqual([{ type: "inventory:full", itemId: "seq-key" }]); + expect(getWorldState().flags.after).toBe(true); + expect(await run.done).toBe("finished"); + }); + + it("removeItem quita una unidad y emite item:removed", async () => { + start({ record: ["item:removed"] }); + getInventoryState().addItem({ id: "seq-coin", name: "C", spriteUrl: "/c.png" }); + getInventoryState().addItem({ id: "seq-coin", name: "C", spriteUrl: "/c.png" }); + rt.runScript([act.removeItem("seq-coin")]); + await flush(); + expect(getInventoryState().slots[0]?.quantity).toBe(1); + expect(h.events).toEqual([{ type: "item:removed", itemId: "seq-coin" }]); + }); + + it("removeItem de algo que no hay avisa y no emite", async () => { + start({ record: ["item:removed"] }); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + rt.runScript([act.removeItem("seq-coin")]); + await flush(); + expect(warn).toHaveBeenCalled(); + expect(h.events).toEqual([]); + }); + + it("placeItem y removePlacedItem usan el store de items colocados", async () => { + start(); + rt.runScript([act.placeItem(placed)]); + await flush(); + expect(getPlacedItemsState().items).toEqual([placed]); + rt.runScript([act.removePlacedItem("p1")]); + await flush(); + expect(getPlacedItemsState().items).toEqual([]); + }); + + it("playSfx despacha audio:playSfx", async () => { + start(); + const spy = vi.spyOn(rt, "executeCommand").mockImplementation(() => {}); + rt.runScript([act.playSfx("/s.mp3")]); + await flush(); + expect(spy).toHaveBeenCalledWith({ type: "audio:playSfx", soundUrl: "/s.mp3" }); + }); + + it("emit emite un evento custom con name y payload", async () => { + start({ record: ["custom"] }); + rt.runScript([act.emit("boom", { n: 1 }), act.emit("plain")]); + await flush(); + expect(h.events).toEqual([ + { type: "custom", name: "boom", payload: { n: 1 } }, + { type: "custom", name: "plain" }, + ]); + }); + + it("lockInput escribe el store y emite input:lockChanged solo al cambiar", async () => { + start({ record: ["input:lockChanged"] }); + rt.runScript([act.lockInput(true), act.lockInput(true), act.lockInput(false), act.lockInput(false)]); + await flush(); + expect(h.events).toEqual([ + { type: "input:lockChanged", locked: true }, + { type: "input:lockChanged", locked: false }, + ]); + expect(getInputLockState().inputLocked).toBe(false); + }); + + it("startDialogue sin ejecutor avisa y continua", async () => { + start(); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const run = rt.runScript([act.startDialogue("d1"), act.setFlag("after")]); + await flush(); + expect(warn).toHaveBeenCalled(); + expect(getWorldState().flags.after).toBe(true); + expect(await run.done).toBe("finished"); + }); +}); + +describe("secuenciador: orden y esperas", () => { + it("ejecuta en orden estricto", async () => { + start({ record: ["custom"] }); + rt.runScript([act.emit("a"), act.wait(10), act.emit("b"), act.emit("c")]); + await flush(); + expect(h.events.map((e) => (e as { name: string }).name)).toEqual(["a"]); + clock.advance(10); + await flush(); + expect(h.events.map((e) => (e as { name: string }).name)).toEqual(["a", "b", "c"]); + }); + + it("say muestra el texto, pasa el speaker y espera a dialog:dismissed", async () => { + start({ record: ["dialog:triggered"] }); + const run = rt.runScript([act.say("k1", "Ana"), act.setFlag("after")]); + await flush(); + expect(getDialogState()).toMatchObject({ visible: true, key: "k1", text: "k1", speaker: "Ana" }); + expect(h.events[0]).toMatchObject({ type: "dialog:triggered", dialogKey: "k1", speaker: "Ana" }); + expect(getWorldState().flags.after).toBeUndefined(); + dismissDialog(rt); + await flush(); + expect(getWorldState().flags.after).toBe(true); + expect(await run.done).toBe("finished"); + }); + + it("say sin speaker no anade el campo al evento", async () => { + start({ record: ["dialog:triggered"] }); + rt.runScript([act.say("k2")]); + await flush(); + expect("speaker" in h.events[0]!).toBe(false); + expect(getDialogState().speaker).toBeUndefined(); + }); + + it("wait espera al reloj", async () => { + start(); + const run = rt.runScript([act.wait(100), act.setFlag("after")]); + await flush(); + clock.advance(99); + await flush(); + expect(getWorldState().flags.after).toBeUndefined(); + clock.advance(1); + await flush(); + expect(getWorldState().flags.after).toBe(true); + expect(await run.done).toBe("finished"); + }); + + it("wait 0 se resuelve con advance(0)", async () => { + start(); + const run = rt.runScript([act.wait(0), act.setFlag("after")]); + await flush(); + clock.advance(0); + await flush(); + expect(getWorldState().flags.after).toBe(true); + expect(await run.done).toBe("finished"); + }); + + it("walkTo con instantWalk mueve al jugador y emite walkCompleted", async () => { + start({ record: ["player:walkCompleted"] }); + const run = rt.runScript([act.walkTo([3, 0, 3]), act.setFlag("after")]); + await flush(); + expect(getGameState().playerPosition).toEqual([3, 0, 3]); + expect(h.events).toEqual([{ type: "player:walkCompleted", position: [3, 0, 3] }]); + expect(getWorldState().flags.after).toBe(true); + expect(await run.done).toBe("finished"); + }); + + it("walkTo sin instantWalk espera a player:walkCompleted", async () => { + start({ instantWalk: false }); + const run = rt.runScript([act.walkTo([3, 0, 3]), act.setFlag("after")]); + await flush(); + expect(getWorldState().flags.after).toBeUndefined(); + rt.emit({ type: "player:walkCompleted", position: [3, 0, 3] }); + await flush(); + expect(getWorldState().flags.after).toBe(true); + expect(await run.done).toBe("finished"); + }); + + it("walkTo sin instantWalk: player:walkAborted termina la accion y el guion continua", async () => { + start({ instantWalk: false }); + const run = rt.runScript([act.walkTo([3, 0, 3]), act.setFlag("after")]); + await flush(); + rt.emit({ type: "player:walkAborted", reason: "user-input" }); + await flush(); + expect(getWorldState().flags.after).toBe(true); + expect(await run.done).toBe("finished"); + }); + + it("walkTo a destino inalcanzable aborta y el guion continua (instantWalk)", async () => { + start({ record: ["player:walkAborted", "player:walkCompleted"] }); + rt.executeCommand({ type: "scene:set", sceneId: "seq-blocked" }); + const run = rt.runScript([act.walkTo([3, 0, 3]), act.setFlag("after")]); + await flush(); + expect(h.events).toEqual([{ type: "player:walkAborted", reason: "unreachable" }]); + expect(getGameState().playerPosition).toEqual([1, 0, 1]); + expect(getWorldState().flags.after).toBe(true); + expect(await run.done).toBe("finished"); + }); +}); + +describe("secuenciador: call", () => { + it("manejador sincrono con args", async () => { + start(); + const fn = vi.fn(); + rt.registerHandler("h", fn); + const run = rt.runScript([act.call("h", { a: 1 }), act.setFlag("after")]); + await flush(); + expect(fn).toHaveBeenCalledWith({ a: 1 }); + expect(getWorldState().flags.after).toBe(true); + expect(await run.done).toBe("finished"); + }); + + it("manejador asincrono: se espera a la promesa", async () => { + start(); + let release!: () => void; + rt.registerHandler("slow", () => new Promise((r) => (release = r))); + rt.runScript([act.call("slow"), act.setFlag("after")]); + await flush(); + expect(getWorldState().flags.after).toBeUndefined(); + release(); + await flush(); + expect(getWorldState().flags.after).toBe(true); + }); + + it("sin manejador: warn y continua", async () => { + start(); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const run = rt.runScript([act.call("ghost"), act.setFlag("after")]); + await flush(); + expect(warn).toHaveBeenCalled(); + expect(getWorldState().flags.after).toBe(true); + expect(await run.done).toBe("finished"); + }); + + it("manejador que lanza: error y continua", async () => { + start(); + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + rt.registerHandler("bad", () => { + throw new Error("x"); + }); + const run = rt.runScript([act.call("bad"), act.setFlag("after")]); + await flush(); + expect(error).toHaveBeenCalled(); + expect(getWorldState().flags.after).toBe(true); + expect(await run.done).toBe("finished"); + }); + + it("manejador que rechaza: error y continua", async () => { + start(); + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + rt.registerHandler("rej", () => Promise.reject(new Error("x"))); + const run = rt.runScript([act.call("rej"), act.setFlag("after")]); + await flush(); + expect(error).toHaveBeenCalled(); + expect(getWorldState().flags.after).toBe(true); + expect(await run.done).toBe("finished"); + }); + + it("registerHandler devuelve la funcion que lo quita", async () => { + start(); + vi.spyOn(console, "warn").mockImplementation(() => {}); + const fn = vi.fn(); + const off = rt.registerHandler("h", fn); + off(); + rt.runScript([act.call("h")]); + await flush(); + expect(fn).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/engine-core/src/__tests__/sequencerFlow.test.ts b/packages/engine-core/src/__tests__/sequencerFlow.test.ts new file mode 100644 index 0000000..0cdc3b9 --- /dev/null +++ b/packages/engine-core/src/__tests__/sequencerFlow.test.ts @@ -0,0 +1,389 @@ +import { describe, it, expect, vi, afterEach, beforeEach } from "vitest"; +import { + act, + branch, + cond, + createGameRuntime, + getConditionContext, + getWorldState, + otherwise, + pickBranch, + type Branch, + type ConditionContext, + type GameRuntime, +} from "../index"; +import { HeadlessClock } from "../ports/headlessClock"; +import { + dismissDialog, + flush, + getInputLockState, + makeScene, + resetStores, + setup, + trackBusSubscriptions, + type Harness, +} from "./sequencerHarness"; + +let h: Harness; +let rt: GameRuntime; +let clock: HeadlessClock; + +function start(opts?: Parameters[0]) { + h = setup(opts); + rt = h.rt; + clock = h.clock; +} + +const names = () => h.events.filter((e) => e.type === "custom").map((e) => (e as { name: string }).name); + +beforeEach(resetStores); +afterEach(() => { + h?.rt.dispose(); + resetStores(); + vi.restoreAllMocks(); +}); + +describe("secuenciador: cola e interrupcion", () => { + it("guion vacio termina y emite started/finished", async () => { + start({ record: ["script:started", "script:finished"] }); + const run = rt.runScript([]); + expect(await run.done).toBe("finished"); + expect(h.events).toEqual([ + { type: "script:started", id: 1 }, + { type: "script:finished", id: 1, result: "finished" }, + ]); + }); + + it("los ids son incrementales", async () => { + start({ record: ["script:started"] }); + await rt.runScript([]).done; + await rt.runScript([]).done; + expect(h.events).toEqual([ + { type: "script:started", id: 1 }, + { type: "script:started", id: 2 }, + ]); + }); + + it("un segundo guion espera en cola (FIFO)", async () => { + start({ record: ["custom", "script:started"] }); + const a = rt.runScript([act.wait(10), act.emit("a")]); + const b = rt.runScript([act.emit("b")]); + const c = rt.runScript([act.emit("c")]); + await flush(); + expect(names()).toEqual([]); + expect(h.events.filter((e) => e.type === "script:started")).toHaveLength(1); + clock.advance(10); + await flush(); + expect(names()).toEqual(["a", "b", "c"]); + expect(await Promise.all([a.done, b.done, c.done])).toEqual(["finished", "finished", "finished"]); + }); + + it("interrupt cancela el actual y vacia la cola", async () => { + start({ record: ["custom"] }); + const a = rt.runScript([act.wait(10), act.emit("a")]); + const queued = rt.runScript([act.emit("queued")]); + const urgent = rt.runScript([act.emit("urgent")], { interrupt: true }); + await flush(); + expect(await a.done).toBe("cancelled"); + expect(await queued.done).toBe("cancelled"); + expect(await urgent.done).toBe("finished"); + clock.advance(10); + await flush(); + expect(names()).toEqual(["urgent"]); + }); + + it("interrupt sin nada en curso se comporta como un run normal", async () => { + start(); + const run = rt.runScript([act.setFlag("x")], { interrupt: true }); + expect(await run.done).toBe("finished"); + expect(getWorldState().flags.x).toBe(true); + }); + + it("script:run despacha el guion; interrupt viaja en el comando", async () => { + start({ record: ["custom"] }); + rt.executeCommand({ type: "script:run", script: [act.wait(5), act.emit("slow")] }); + rt.executeCommand({ type: "script:run", script: [act.emit("fast")], interrupt: true }); + await flush(); + clock.advance(5); + await flush(); + expect(names()).toEqual(["fast"]); + }); +}); + +describe("secuenciador: cancelacion", () => { + it("cancel() a mitad de say suelta la suscripcion y resuelve cancelled", async () => { + start({ record: ["custom"] }); + const run = rt.runScript([act.say("k"), act.emit("after")]); + await flush(); + run.cancel(); + expect(await run.done).toBe("cancelled"); + dismissDialog(rt); + await flush(); + expect(names()).toEqual([]); + }); + + it("cancel() a mitad de wait cancela el temporizador", async () => { + start({ record: ["custom"] }); + const run = rt.runScript([act.wait(50), act.emit("after")]); + await flush(); + expect(clock.pending()).toBe(1); + run.cancel(); + expect(clock.pending()).toBe(0); + expect(await run.done).toBe("cancelled"); + clock.advance(100); + await flush(); + expect(names()).toEqual([]); + }); + + it("cancel() a mitad de walkTo ignora el walkCompleted posterior", async () => { + start({ instantWalk: false, record: ["custom"] }); + const run = rt.runScript([act.walkTo([3, 0, 3]), act.emit("after")]); + await flush(); + run.cancel(); + expect(await run.done).toBe("cancelled"); + rt.emit({ type: "player:walkCompleted", position: [3, 0, 3] }); + await flush(); + expect(names()).toEqual([]); + }); + + it("cancel() es idempotente y no afecta a guiones ya terminados", async () => { + start({ record: ["script:finished"] }); + const run = rt.runScript([]); + await run.done; + run.cancel(); + run.cancel(); + expect(h.events).toHaveLength(1); + expect(await run.done).toBe("finished"); + }); + + it("cancel() de un guion en cola lo saca de la cola sin ejecutarlo", async () => { + start({ record: ["custom", "script:started", "script:finished"] }); + rt.runScript([act.wait(10)]); + const queued = rt.runScript([act.emit("queued")]); + queued.cancel(); + expect(await queued.done).toBe("cancelled"); + clock.advance(10); + await flush(); + expect(names()).toEqual([]); + // El cancelado en cola nunca arranco: no hay started/finished suyos. + expect(h.events.filter((e) => e.type === "script:started")).toHaveLength(1); + }); + + it("script:cancelAll cancela el actual y la cola", async () => { + start({ record: ["custom"] }); + const a = rt.runScript([act.wait(10), act.emit("a")]); + const b = rt.runScript([act.emit("b")]); + rt.executeCommand({ type: "script:cancelAll" }); + expect(await a.done).toBe("cancelled"); + expect(await b.done).toBe("cancelled"); + clock.advance(10); + await flush(); + expect(names()).toEqual([]); + }); + + it("tras cancelAll se puede lanzar otro guion", async () => { + start(); + rt.runScript([act.wait(10)]); + rt.executeCommand({ type: "script:cancelAll" }); + const run = rt.runScript([act.setFlag("again")]); + expect(await run.done).toBe("finished"); + expect(getWorldState().flags.again).toBe(true); + }); +}); + +describe("secuenciador: bloqueo de entrada", () => { + it("se libera al terminar aunque el guion no lo libere", async () => { + start({ record: ["input:lockChanged"] }); + const run = rt.runScript([act.lockInput(true), act.wait(5)]); + await flush(); + expect(getInputLockState().inputLocked).toBe(true); + clock.advance(5); + await flush(); + expect(await run.done).toBe("finished"); + expect(getInputLockState().inputLocked).toBe(false); + expect(h.events).toEqual([ + { type: "input:lockChanged", locked: true }, + { type: "input:lockChanged", locked: false }, + ]); + }); + + it("se libera al cancelar", async () => { + start({ record: ["input:lockChanged"] }); + const run = rt.runScript([act.lockInput(true), act.say("k")]); + await flush(); + expect(getInputLockState().inputLocked).toBe(true); + run.cancel(); + expect(getInputLockState().inputLocked).toBe(false); + expect(await run.done).toBe("cancelled"); + expect(h.events.at(-1)).toEqual({ type: "input:lockChanged", locked: false }); + }); + + it("se libera al interrumpir con otro guion", async () => { + start(); + rt.runScript([act.lockInput(true), act.wait(100)]); + await flush(); + const next = rt.runScript([act.setFlag("x")], { interrupt: true }); + expect(await next.done).toBe("finished"); + expect(getInputLockState().inputLocked).toBe(false); + }); +}); + +describe("secuenciador: acciones desconocidas", () => { + it("avisa una vez por forma, la salta y continua", async () => { + start(); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const bad = { teleport: 1 } as never; + const run = rt.runScript([bad, bad, { other: 2 } as never, act.setFlag("after")]); + await flush(); + expect(warn).toHaveBeenCalledTimes(2); + expect(getWorldState().flags.after).toBe(true); + expect(await run.done).toBe("finished"); + }); + + it("null, numeros y guion no-array no lanzan", async () => { + start(); + vi.spyOn(console, "warn").mockImplementation(() => {}); + expect(await rt.runScript([null as never, 5 as never, act.setFlag("ok")]).done).toBe("finished"); + expect(await rt.runScript(undefined as never).done).toBe("finished"); + expect(getWorldState().flags.ok).toBe(true); + }); +}); + +describe("pickBranch y constructores", () => { + const ctx = (flags: Record = {}): ConditionContext => ({ + flags, + inventory: [], + placedItems: [], + sceneId: "s", + visitedSceneIds: [], + }); + + it("devuelve la primera rama que cumple", () => { + const branches: Branch[] = [ + branch(cond.flag("a"), act.emit("A")), + branch(cond.flag("b"), act.emit("B")), + otherwise(act.emit("D")), + ]; + expect(pickBranch(branches, ctx({ b: true }))).toEqual([act.emit("B")]); + expect(pickBranch(branches, ctx({ a: true, b: true }))).toEqual([act.emit("A")]); + expect(pickBranch(branches, ctx())).toEqual([act.emit("D")]); + }); + + it("sin when se cumple siempre", () => { + expect(pickBranch([{ do: [act.wait(1)] }], ctx())).toEqual([act.wait(1)]); + }); + + it("undefined, vacio o ninguna rama -> null", () => { + expect(pickBranch(undefined, ctx())).toBeNull(); + expect(pickBranch([], ctx())).toBeNull(); + expect(pickBranch([branch(cond.flag("a"), act.wait(1))], ctx())).toBeNull(); + }); + + it("funciona con getConditionContext y el resultado se puede ejecutar", async () => { + start(); + getWorldState().setFlag("door", true); + const script = pickBranch([branch(cond.flag("door"), act.setFlag("opened"))], getConditionContext()); + expect(script).not.toBeNull(); + expect(await rt.runScript(script!).done).toBe("finished"); + expect(getWorldState().flags.opened).toBe(true); + }); + + it("los constructores producen objetos planos serializables", () => { + const script = [ + act.say("k", "Ana"), + act.setFlag("f", 2), + act.giveItem("i"), + act.changeScene("s", [1, 0, 1]), + act.emit("e", { x: 1 }), + act.call("c", [1]), + act.startDialogue("d"), + ]; + expect(JSON.parse(JSON.stringify(script))).toEqual(script); + expect(act.say("k")).toEqual({ say: "k" }); + expect(act.setFlag("f")).toEqual({ setFlag: "f" }); + }); +}); + +describe("secuenciador: ciclo de vida del runtime", () => { + it("dispose con un guion en curso lo cancela, libera el bloqueo y emite finished", async () => { + start({ record: ["script:finished"] }); + const run = rt.runScript([act.lockInput(true), act.wait(100)]); + const queued = rt.runScript([act.setFlag("never")]); + await flush(); + rt.dispose(); + expect(await run.done).toBe("cancelled"); + expect(await queued.done).toBe("cancelled"); + expect(getInputLockState().inputLocked).toBe(false); + expect(h.events).toEqual([{ type: "script:finished", id: 1, result: "cancelled" }]); + expect(clock.pending()).toBe(0); + clock.advance(100); + await flush(); + expect(getWorldState().flags.never).toBeUndefined(); + }); + + it("runScript tras dispose resuelve cancelled sin ejecutar", async () => { + start(); + rt.dispose(); + expect(await rt.runScript([act.setFlag("x")]).done).toBe("cancelled"); + expect(getWorldState().flags.x).toBeUndefined(); + }); + + it("dos runtimes consecutivos no dejan suscripciones", async () => { + const tracker = trackBusSubscriptions(); + for (let i = 0; i < 2; i++) { + const clk = new HeadlessClock(); + const r = createGameRuntime({ scenes: [makeScene("seq-a")], clock: clk, instantWalk: true }); + r.executeCommand({ type: "scene:set", sceneId: "seq-a" }); + const base = tracker.active(); + const s1 = r.runScript([act.say("k"), act.walkTo([2, 0, 2])]); + await flush(); + expect(tracker.active()).toBeGreaterThan(base); + s1.cancel(); + expect(tracker.active()).toBe(base); + const s2 = r.runScript([act.walkTo([3, 0, 3]), act.wait(1)]); + await flush(); + clk.advance(1); + await flush(); + expect(await s2.done).toBe("finished"); + expect(tracker.active()).toBe(base); + r.dispose(); + } + expect(tracker.active()).toBe(0); + }); + + it("el guion del runtime anterior no se mezcla con el del siguiente", async () => { + start(); + rt.runScript([act.say("old"), act.setFlag("old-after")]); + await flush(); + rt.dispose(); + h = setup(); + rt = h.rt; + const run = rt.runScript([act.setFlag("new")]); + expect(await run.done).toBe("finished"); + dismissDialog(rt); + await flush(); + expect(getWorldState().flags["old-after"]).toBeUndefined(); + }); + + it("registerExecutor permite sustituir startDialogue sin tocar el bucle", async () => { + start(); + // Punto de extension interno: se ejercita via createSequencer en el test de la tarea 07; + // aqui se comprueba el contrato con un secuenciador independiente. + const { createSequencer } = await import("../game/narrative/sequencer"); + const emitted: unknown[] = []; + const seq = createSequencer({ + execute: () => {}, + emit: (e) => emitted.push(e), + on: () => () => {}, + clock: new HeadlessClock(), + instantWalk: true, + getItem: () => undefined, + }); + const seen: string[] = []; + seq.registerExecutor("startDialogue", (a) => { + seen.push((a as { startDialogue: string }).startDialogue); + }); + expect(await seq.run([act.startDialogue("tree-1")]).done).toBe("finished"); + expect(seen).toEqual(["tree-1"]); + }); +}); diff --git a/packages/engine-core/src/__tests__/sequencerHarness.ts b/packages/engine-core/src/__tests__/sequencerHarness.ts new file mode 100644 index 0000000..58f8b22 --- /dev/null +++ b/packages/engine-core/src/__tests__/sequencerHarness.ts @@ -0,0 +1,116 @@ +import { vi } from "vitest"; +import { EventBus } from "../events"; +import { + createGameRuntime, + getInputLockState, + getInventoryState, + getPlacedItemsState, + getWorldState, + useDialogStore, + useInputLockStore, + useSceneStore, + type GameEvent, + type GameEventType, + type GameItemConfig, + type GameRuntime, + type GameSceneConfig, +} from "../index"; +import { HeadlessClock } from "../ports/headlessClock"; + +/** Avanza microtareas (no hay tiempo real: solo cola de promesas). */ +export async function flush(times = 40): Promise { + for (let i = 0; i < times; i++) await Promise.resolve(); +} + +export function makeScene(id: string, extra: Partial = {}): GameSceneConfig { + return { + id, + label: `Scene ${id}`, + background: "/bg.png", + playerSpawn: [1, 0, 1], + ground: { minX: -5, maxX: 5, minZ: -5, maxZ: 5, y: 0 }, + walls: [], + interactions: [], + ...extra, + }; +} + +export function makeItem(id: string): GameItemConfig { + return { + id, + name: `Name ${id}`, + spriteUrl: `/${id}.png`, + interactionRules: {}, + defaultRule: { outcome: "return" }, + }; +} + +export function resetStores(): void { + useDialogStore.setState({ text: "", key: undefined, speaker: undefined, visible: false, triggerCount: 0 }); + useInputLockStore.setState({ inputLocked: false }); + getInventoryState().reset(); + getPlacedItemsState().reset(); + getWorldState().reset(); + useSceneStore.setState({ sceneId: "", playerWalkingState: null }); +} + +export interface Harness { + rt: GameRuntime; + clock: HeadlessClock; + events: GameEvent[]; +} + +/** Crea un runtime headless con escena "seq-a" activa y registra los eventos pedidos. */ +export function setup( + opts: { instantWalk?: boolean; record?: GameEventType[] } = {}, +): Harness { + const clock = new HeadlessClock(); + const rt = createGameRuntime({ + scenes: [ + makeScene("seq-a"), + makeScene("seq-b", { playerSpawn: [-1, 0, -1] }), + // Un bloque con colision cubre todo el suelo: ningun destino es alcanzable. + makeScene("seq-blocked", { + interactions: [ + { id: "blocker", position: [0, 0, 0], halfSize: [20, 1, 20], hasCollision: true }, + ] as unknown as GameSceneConfig["interactions"], + }), + ], + items: [makeItem("seq-key"), makeItem("seq-coin")], + clock, + instantWalk: opts.instantWalk ?? true, + }); + rt.executeCommand({ type: "scene:set", sceneId: "seq-a" }); + const events: GameEvent[] = []; + for (const type of opts.record ?? []) rt.on(type, (e) => events.push(e as GameEvent)); + return { rt, clock, events }; +} + +export function dismissDialog(rt: GameRuntime): void { + rt.executeCommand({ type: "dialog:dismiss" }); +} + +/** Cuenta suscripciones activas del EventBus (de cualquier instancia). */ +export function trackBusSubscriptions(): { active: () => number } { + let active = 0; + const original = EventBus.prototype.on; + vi.spyOn(EventBus.prototype, "on").mockImplementation(function ( + this: EventBus, + event: string, + handler: (data: never) => void, + ) { + const off = original.call(this, event, handler as (data: unknown) => void); + active++; + let released = false; + return () => { + if (!released) { + released = true; + active--; + } + off(); + }; + }); + return { active: () => active }; +} + +export { getInputLockState }; diff --git a/packages/engine-core/src/__tests__/sequencerInline.test.ts b/packages/engine-core/src/__tests__/sequencerInline.test.ts new file mode 100644 index 0000000..4c8f10b --- /dev/null +++ b/packages/engine-core/src/__tests__/sequencerInline.test.ts @@ -0,0 +1,89 @@ +import { describe, it, expect } from "vitest"; +import { createSequencer, type Sequencer } from "../game/narrative"; +import type { GameEvent } from "../game/events/types"; +import { HeadlessClock } from "../ports/headlessClock"; +import { flush } from "./sequencerHarness"; + +function make(): { seq: Sequencer; clock: HeadlessClock; events: GameEvent[]; log: string[] } { + const clock = new HeadlessClock(); + const events: GameEvent[] = []; + const log: string[] = []; + const seq = createSequencer({ + execute: () => {}, + emit: (e) => events.push(e), + on: () => () => {}, + clock, + instantWalk: true, + getItem: () => undefined, + }); + seq.registerHandler("log", (a) => { + log.push(String(a)); + }); + return { seq, clock, events, log }; +} + +const log = (s: string) => ({ call: "log", args: s }); + +describe("ActionContext.runInline", () => { + it("ejecuta el sub-guion en orden dentro de la accion", async () => { + const { seq, log: out } = make(); + seq.registerExecutor("startDialogue", async (_a, ctx) => { + out.push("antes"); + await ctx.runInline([log("a"), log("b")]); + out.push("despues"); + }); + const run = seq.run([log("0"), { startDialogue: "x" }, log("z")]); + expect(await run.done).toBe("finished"); + expect(out).toEqual(["0", "antes", "a", "b", "despues", "z"]); + }); + + it("no emite script:started/finished extra ni usa la cola (sin interbloqueo)", async () => { + const { seq, events } = make(); + seq.registerExecutor("startDialogue", (_a, ctx) => ctx.runInline([{ emit: "dentro" }])); + const run = seq.run([{ startDialogue: "x" }]); + await run.done; + const types = events.map((e) => e.type); + expect(types.filter((t) => t === "script:started")).toHaveLength(1); + expect(types.filter((t) => t === "script:finished")).toHaveLength(1); + expect(types).toContain("custom"); + }); + + it("espera las acciones asincronas del sub-guion", async () => { + const { seq, clock, log: out } = make(); + seq.registerExecutor("startDialogue", async (_a, ctx) => { + await ctx.runInline([{ wait: 50 }, log("tras-espera")]); + out.push("fin"); + }); + const run = seq.run([{ startDialogue: "x" }]); + await flush(); + expect(out).toEqual([]); + clock.advance(50); + await run.done; + expect(out).toEqual(["tras-espera", "fin"]); + }); + + it("la cancelacion a mitad corta el sub-guion y el guion", async () => { + const { seq, clock, log: out } = make(); + let inlineReturned = false; + seq.registerExecutor("startDialogue", async (_a, ctx) => { + await ctx.runInline([log("1"), { wait: 100 }, log("2")]); + inlineReturned = true; + }); + const run = seq.run([{ startDialogue: "x" }, log("3")]); + await flush(); + run.cancel(); + clock.advance(100); + expect(await run.done).toBe("cancelled"); + await flush(); + expect(inlineReturned).toBe(true); + expect(out).toEqual(["1"]); + }); + + it("un script no valido se trata como vacio", async () => { + const { seq } = make(); + seq.registerExecutor("startDialogue", (_a, ctx) => + ctx.runInline(undefined as unknown as never[]), + ); + expect(await seq.run([{ startDialogue: "x" }]).done).toBe("finished"); + }); +}); diff --git a/packages/engine-core/src/__tests__/validateContent.test.ts b/packages/engine-core/src/__tests__/validateContent.test.ts new file mode 100644 index 0000000..e3ffc5c --- /dev/null +++ b/packages/engine-core/src/__tests__/validateContent.test.ts @@ -0,0 +1,350 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { validateContent, type ContentIssue, type GameContent } from "../game/narrative/validateContent"; +import { createGameRuntime } from "../game/runtime/createGameRuntime"; +import type { GameItemConfig, GameSceneConfig } from "../game/runtime/types"; +import type { DialogueDefinition } from "../game/narrative/dialogueTypes"; +import type { Action, Branch } from "../game/narrative/actions"; +import type { Condition } from "../game/narrative/conditions"; + +const rule = { outcome: "return" as const }; +const item = (id: string, extra: Partial = {}): GameItemConfig => ({ + id, + name: id, + spriteUrl: "", + interactionRules: {}, + defaultRule: rule, + ...extra, +}); +const scene = (id: string, extra: Partial = {}): GameSceneConfig => ({ + id, + label: id, + background: "", + playerSpawn: [0, 0, 0], + ground: {} as GameSceneConfig["ground"], + walls: [], + interactions: [], + ...extra, +}); +const hotspot = (id: string, extra: Record = {}) => ({ + id, + label: id, + position: [0, 0, 0] as [number, number, number], + halfSize: [1, 1, 1] as [number, number, number], + ...extra, +}); +const dlg = (id: string, start: string, nodes: DialogueDefinition["nodes"]): DialogueDefinition => ({ + id, + start, + nodes, +}); +const drop = (id: string) => ({ + id, + kind: "drop-target" as const, + position: [0, 0, 0] as [number, number, number], + halfSize: [1, 1, 1] as [number, number, number], + dialogKeys: { hit: "a", miss: "b" }, + label: id, +}); +const run = (a: Action[]): Branch[] => [{ do: a }]; + +const find = (issues: ContentIssue[], code: string) => issues.filter((i) => i.code === code); +const codes = (c: GameContent) => validateContent(c).map((i) => i.code); + +/** Contenido completo y coherente: no produce ninguna incidencia. */ +function validContent(): GameContent { + return { + scenes: [ + scene("town", { + interactions: [drop("slot")], + hotspots: [ + hotspot("well", { + visibleWhen: { not: { flag: "wellBroken" } }, + verbs: { look: run([{ say: "k.well" }]), use: [{ when: { hasItem: "key" }, do: [{ setFlag: "wellBroken" }, { changeScene: "cave" }] }] }, + useItem: { key: run([{ removeItem: "key" }, { giveItem: "coin" }]) }, + useItemDefault: run([{ call: "nope" }]), + }), + ], + npcs: [{ id: "guard", name: "k.guard", characterId: "c", position: [0, 0, 0], dialogueId: "chat" }], + initialItems: [{ item: { id: "p1", itemId: "key", interactionId: "slot", name: "", spriteUrl: "", worldPosition: [0, 0, 0], canPickup: true }, when: { flag: "wellBroken" } }], + onEnter: [{ when: { not: { visited: "cave" } }, do: [{ setFlag: "intro" }, { startDialogue: "chat" }] }], + transitions: [{ id: "t1", kind: "collision", targetSceneId: "cave", position: [0, 0, 0], halfSize: [1, 1, 1], when: { flag: "intro" }, blocked: [{ say: "k.no" }] }], + }), + scene("cave", { transitions: [{ id: "back", kind: "collision", targetSceneId: "town", position: [0, 0, 0], halfSize: [1, 1, 1] }] }), + ], + items: [item("key", { combine: { coin: run([{ giveItem: "key" }]) } }), item("coin")], + dialogues: [ + dlg("chat", "a", [ + { id: "a", line: "k.hi", choices: [{ text: "k.c1", next: "b", when: { flag: "intro" } }, { text: "k.c2" }] }, + { id: "b", line: "k.b", do: [{ setFlag: "wellBroken" }], next: "c" }, + { id: "c", line: "k.bye" }, + ]), + ], + dialogKeys: new Set(["k.well", "k.guard", "k.no", "k.hi", "k.c1", "k.c2", "k.b", "k.bye", "well", "guard", "town", "cave"]), + handlers: new Set(["nope"]), + }; +} + +describe("validateContent", () => { + it("un contenido valido no produce incidencias", () => { + expect(validateContent(validContent())).toEqual([]); + }); + + it("es pura: no muta el contenido", () => { + const c = validContent(); + const before = JSON.stringify([c.scenes, c.items, c.dialogues]); + validateContent(c); + expect(JSON.stringify([c.scenes, c.items, c.dialogues])).toBe(before); + }); + + it("contenido vacio no produce incidencias", () => { + expect(validateContent({ scenes: [], items: [] })).toEqual([]); + }); + + describe("duplicados", () => { + it("duplicate-id: escenas, items, dialogos", () => { + const c = { scenes: [scene("a"), scene("a")], items: [item("i"), item("i")], dialogues: [dlg("d", "n", [{ id: "n", line: "x" }]), dlg("d", "n", [{ id: "n", line: "x" }])] }; + expect(find(validateContent(c), "duplicate-id")).toHaveLength(3); + }); + it("duplicate-id: hotspot y NPC comparten espacio de ids", () => { + const s = scene("a", { hotspots: [hotspot("x")], npcs: [{ id: "x", name: "n", characterId: "c", position: [0, 0, 0] }] }); + expect(find(validateContent({ scenes: [s], items: [] }), "duplicate-id")).toHaveLength(1); + }); + it("duplicate-id: transiciones e interacciones", () => { + const t = { id: "t", kind: "collision" as const, targetSceneId: "a", position: [0, 0, 0] as [number, number, number], halfSize: [1, 1, 1] as [number, number, number] }; + const s = scene("a", { transitions: [t, t], interactions: [drop("i"), drop("i")] }); + expect(find(validateContent({ scenes: [s], items: [] }), "duplicate-id")).toHaveLength(2); + }); + it("duplicate-id: nodos de un dialogo", () => { + const c = { scenes: [], items: [], dialogues: [dlg("d", "n", [{ id: "n", line: "x" }, { id: "n", line: "y" }])] }; + expect(codes(c)).toContain("duplicate-id"); + }); + }); + + describe("referencias rotas", () => { + const withAction = (a: Action): GameContent => ({ + scenes: [scene("a", { hotspots: [hotspot("h", { verbs: { look: run([a]) } })] })], + items: [item("i")], + }); + it("unknown-item: giveItem y removeItem", () => { + expect(find(validateContent(withAction({ giveItem: "ghost" })), "unknown-item")).toHaveLength(1); + expect(find(validateContent(withAction({ removeItem: "ghost" })), "unknown-item")).toHaveLength(1); + }); + it("unknown-item: placeItem", () => { + const a: Action = { placeItem: { id: "p", itemId: "ghost", interactionId: "", name: "", spriteUrl: "", worldPosition: [0, 0, 0], canPickup: true } }; + expect(codes(withAction(a))).toContain("unknown-item"); + }); + it("unknown-scene: changeScene", () => { + const issues = validateContent(withAction({ changeScene: "nowhere" })); + expect(find(issues, "unknown-scene")).toHaveLength(1); + expect(find(issues, "unknown-scene")[0].severity).toBe("error"); + }); + it("unknown-dialogue: startDialogue", () => { + expect(codes(withAction({ startDialogue: "ghost" }))).toContain("unknown-dialogue"); + }); + it("unknown-dialogue: dialogueId de un NPC", () => { + const s = scene("a", { npcs: [{ id: "n", name: "n", characterId: "c", position: [0, 0, 0], dialogueId: "ghost" }] }); + const issue = find(validateContent({ scenes: [s], items: [] }), "unknown-dialogue")[0]; + expect(issue.where).toBe("scene:a > npc:n > dialogueId"); + }); + it("placeItem: el interactionId del item es una etiqueta libre y no se valida", () => { + const a: Action = { placeItem: { id: "p", itemId: "i", interactionId: "ghost", name: "", spriteUrl: "", worldPosition: [0, 0, 0], canPickup: true } }; + expect(codes(withAction(a))).not.toContain("unknown-interaction"); + }); + it("unknown-interaction: condicion itemPlaced.at", () => { + const c: Condition = { itemPlaced: "i", inScene: "a", at: "ghost" }; + const content: GameContent = { scenes: [scene("a", { hotspots: [hotspot("h", { visibleWhen: c })] })], items: [item("i")] }; + expect(codes(content)).toContain("unknown-interaction"); + }); + it("unknown-interaction: requiresInteractionId de una transicion", () => { + const t = { id: "t", kind: "item-interaction" as const, requiresItemId: "i", requiresInteractionId: "ghost", targetSceneId: "a", position: [0, 0, 0] as [number, number, number], halfSize: [1, 1, 1] as [number, number, number] }; + expect(codes({ scenes: [scene("a", { transitions: [t] })], items: [item("i")] })).toContain("unknown-interaction"); + }); + it("initialItems: el interactionId del item es una etiqueta libre y no se valida", () => { + const s = scene("a", { initialItems: [{ item: { id: "p", itemId: "i", interactionId: "ghost", name: "", spriteUrl: "", worldPosition: [0, 0, 0], canPickup: true } }] }); + expect(codes({ scenes: [s], items: [item("i")] })).not.toContain("unknown-interaction"); + }); + it("referencias en condiciones: hasItem, inScene, visited, anidadas", () => { + const c: Condition = { all: [{ hasItem: "ghost" }, { any: [{ not: { inScene: "ghost" } }, { visited: "ghost" }] }] }; + const content: GameContent = { scenes: [scene("a", { hotspots: [hotspot("h", { visibleWhen: c })] })], items: [] }; + const issues = validateContent(content); + expect(find(issues, "unknown-item")).toHaveLength(1); + expect(find(issues, "unknown-scene")).toHaveLength(2); + }); + it("unknown-item: claves de useItem y de combine, acceptsItemIds, requiresItemId", () => { + const t = { id: "t", kind: "item-consume" as const, requiresItemId: "g4", targetSceneId: "a", position: [0, 0, 0] as [number, number, number], halfSize: [1, 1, 1] as [number, number, number] }; + const s = scene("a", { + hotspots: [hotspot("h", { useItem: { g1: run([]) } })], + interactions: [{ ...drop("d"), acceptsItemIds: ["g3"] }], + transitions: [t], + }); + const issues = validateContent({ scenes: [s], items: [item("i", { combine: { g2: run([]) } })] }); + expect(find(issues, "unknown-item")).toHaveLength(4); + }); + it("unknown-scene: targetSceneId de una transicion", () => { + const t = { id: "t", kind: "collision" as const, targetSceneId: "ghost", position: [0, 0, 0] as [number, number, number], halfSize: [1, 1, 1] as [number, number, number] }; + expect(find(validateContent({ scenes: [scene("a", { transitions: [t] })], items: [] }), "unknown-scene")[0].where).toBe("scene:a > transition:t > targetSceneId"); + }); + it("recorre when/blocked de transiciones, onEnter y combine", () => { + const t = { id: "t", kind: "collision" as const, targetSceneId: "a", position: [0, 0, 0] as [number, number, number], halfSize: [1, 1, 1] as [number, number, number], when: { hasItem: "g1" }, blocked: [{ giveItem: "g2" }] }; + const s = scene("a", { transitions: [t], onEnter: run([{ giveItem: "g3" }]) }); + const issues = validateContent({ scenes: [s], items: [item("i", { combine: { i: run([{ giveItem: "g4" }]) } })] }); + expect(find(issues, "unknown-item")).toHaveLength(4); + }); + }); + + describe("forma desconocida", () => { + it("unknown-verb", () => { + const s = scene("a", { hotspots: [hotspot("h", { verbs: { shout: run([]) } })] }); + expect(codes({ scenes: [s], items: [] })).toContain("unknown-verb"); + }); + it("unknown-action", () => { + const s = scene("a", { hotspots: [hotspot("h", { verbs: { look: [{ do: [{ explode: 1 }] }] } })] }); + const issue = find(validateContent({ scenes: [s], items: [] }), "unknown-action")[0]; + expect(issue.where).toBe("scene:a > hotspot:h > verbs.look[0].do[0]"); + }); + it("unknown-condition", () => { + const s = scene("a", { hotspots: [hotspot("h", { visibleWhen: { wat: 1 } })] }); + expect(codes({ scenes: [s], items: [] })).toContain("unknown-condition"); + }); + it("unknown-branch", () => { + const s = scene("a", { hotspots: [hotspot("h", { verbs: { look: [null] } })] }); + expect(codes({ scenes: [s], items: [] })).toContain("unknown-branch"); + }); + }); + + describe("dialogos", () => { + it("unknown-dialogue-start", () => { + const c = { scenes: [], items: [], dialogues: [dlg("d", "ghost", [{ id: "n", line: "x" }])] }; + expect(codes(c)).toContain("unknown-dialogue-start"); + }); + it("unknown-dialogue-node: next de un nodo y de una opcion", () => { + const d = dlg("d", "n", [{ id: "n", line: "x", next: "g1", choices: [{ text: "t", next: "g2" }] }]); + const issues = validateContent({ scenes: [], items: [], dialogues: [d] }); + expect(find(issues, "unknown-dialogue-node").map((i) => i.where)).toEqual([ + "dialogue:d > node:n > next", + "dialogue:d > node:n > choices[0].next", + ]); + }); + it("dialogue-dead-end: nodo vacio", () => { + const d = dlg("d", "n", [{ id: "n", line: "x", next: "m" }, { id: "m" }]); + expect(find(validateContent({ scenes: [], items: [], dialogues: [d] }), "dialogue-dead-end")[0].severity).toBe("error"); + }); + it("un nodo final con linea no es dead-end", () => { + const d = dlg("d", "n", [{ id: "n", line: "x" }]); + expect(codes({ scenes: [], items: [], dialogues: [d] })).not.toContain("dialogue-dead-end"); + }); + it("unreachable-dialogue-node (aviso)", () => { + const d = dlg("d", "n", [{ id: "n", line: "x" }, { id: "orphan", line: "y" }]); + const issue = find(validateContent({ scenes: [], items: [], dialogues: [d] }), "unreachable-dialogue-node")[0]; + expect(issue).toMatchObject({ severity: "warning", where: "dialogue:d > node:orphan" }); + }); + it("recorre when/do de las opciones", () => { + const d = dlg("d", "n", [{ id: "n", choices: [{ text: "t", when: { hasItem: "g1" }, do: [{ giveItem: "g2" }] }] }]); + expect(find(validateContent({ scenes: [], items: [], dialogues: [d] }), "unknown-item")).toHaveLength(2); + }); + }); + + describe("avisos", () => { + it("unreachable-scene", () => { + const issues = validateContent({ scenes: [scene("a"), scene("b")], items: [] }); + expect(find(issues, "unreachable-scene")).toEqual([expect.objectContaining({ severity: "warning", where: "scene:b" })]); + }); + it("una escena alcanzable solo por un dialogo no se avisa", () => { + const d = dlg("d", "n", [{ id: "n", do: [{ changeScene: "b" }] }]); + expect(codes({ scenes: [scene("a"), scene("b")], items: [], dialogues: [d] })).not.toContain("unreachable-scene"); + }); + it("una sola escena no avisa", () => { + expect(codes({ scenes: [scene("a")], items: [] })).not.toContain("unreachable-scene"); + }); + it("unused-item", () => { + const issues = validateContent({ scenes: [scene("a")], items: [item("lonely")] }); + expect(find(issues, "unused-item")).toEqual([expect.objectContaining({ severity: "warning", where: "item:lonely" })]); + }); + it("un item dado por un guion no es unused-item", () => { + const s = scene("a", { onEnter: run([{ giveItem: "i" }]) }); + expect(codes({ scenes: [s], items: [item("i")] })).not.toContain("unused-item"); + }); + it("flag-never-set", () => { + const s = scene("a", { hotspots: [hotspot("h", { visibleWhen: { flag: "x" } })] }); + expect(find(validateContent({ scenes: [s], items: [] }), "flag-never-set")).toEqual([expect.objectContaining({ severity: "warning" })]); + }); + it("flag-never-read", () => { + const s = scene("a", { onEnter: run([{ setFlag: "x" }]) }); + expect(find(validateContent({ scenes: [s], items: [] }), "flag-never-read")).toEqual([expect.objectContaining({ severity: "warning" })]); + }); + it("un flag escrito y leido no avisa", () => { + const s = scene("a", { onEnter: [{ when: { flag: "x" }, do: [{ setFlag: "x" }] }] }); + const c = codes({ scenes: [s], items: [] }); + expect(c).not.toContain("flag-never-set"); + expect(c).not.toContain("flag-never-read"); + }); + it("unknown-dialog-key solo si se pasa dialogKeys", () => { + const s = scene("a", { onEnter: run([{ say: "k.missing" }]) }); + expect(codes({ scenes: [s], items: [] })).not.toContain("unknown-dialog-key"); + const issues = validateContent({ scenes: [s], items: [], dialogKeys: new Set(["a"]) }); + expect(find(issues, "unknown-dialog-key")[0]).toMatchObject({ severity: "warning", where: "scene:a > onEnter[0].do[0].say" }); + }); + it("unknown-dialog-key en line y text de dialogos, label de hotspots", () => { + const d = dlg("d", "n", [{ id: "n", line: "k.l", choices: [{ text: "k.t" }] }]); + const s = scene("a", { hotspots: [hotspot("h", { label: "k.label" })] }); + const issues = validateContent({ scenes: [s], items: [], dialogues: [d], dialogKeys: new Set() }); + expect(find(issues, "unknown-dialog-key")).toHaveLength(3); + }); + it("unknown-handler solo si se pasa handlers", () => { + const s = scene("a", { onEnter: run([{ call: "mystery" }]) }); + expect(codes({ scenes: [s], items: [] })).not.toContain("unknown-handler"); + const issues = validateContent({ scenes: [s], items: [], handlers: new Set(["other"]) }); + expect(find(issues, "unknown-handler")).toEqual([expect.objectContaining({ severity: "warning" })]); + }); + }); + + it("where permite localizar el dato", () => { + const s = scene("town", { hotspots: [hotspot("well", { verbs: { use: [{ do: [{ say: "x" }, { setFlag: "a" }, { giveItem: "ghost" }] }] } })] }); + expect(find(validateContent({ scenes: [s], items: [] }), "unknown-item")[0].where).toBe("scene:town > hotspot:well > verbs.use[0].do[2].giveItem"); + }); +}); + +describe("createGameRuntime validate", () => { + afterEach(() => vi.restoreAllMocks()); + const broken = (): GameSceneConfig => scene("vsc", { onEnter: run([{ giveItem: "ghost" }, { changeScene: "ghost" }]) }); + + it("por defecto no valida fuera de desarrollo (NODE_ENV=test)", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + createGameRuntime({ scenes: [broken()] }).dispose(); + expect(warn).not.toHaveBeenCalled(); + }); + + it("validate: true avisa con un unico console.warn agrupado", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + createGameRuntime({ scenes: [broken()], validate: true }).dispose(); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0][0])).toContain("unknown-item"); + expect(String(warn.mock.calls[0][0])).toContain("unknown-scene"); + }); + + it("validate: 'throw' lanza si hay errores", () => { + expect(() => createGameRuntime({ scenes: [broken()], validate: "throw" })).toThrow(/unknown-item/); + }); + + it("validate: 'throw' no lanza sin errores", () => { + const rt = createGameRuntime({ scenes: [scene("ok")], validate: "throw" }); + rt.dispose(); + }); + + it("validate: false no valida", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + createGameRuntime({ scenes: [broken()], validate: false }).dispose(); + expect(warn).not.toHaveBeenCalled(); + }); + + it("en desarrollo valida por defecto", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + vi.stubEnv("NODE_ENV", "development"); + try { + createGameRuntime({ scenes: [broken()] }).dispose(); + } finally { + vi.unstubAllEnvs(); + } + expect(warn).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/engine-core/src/__tests__/worldState.test.ts b/packages/engine-core/src/__tests__/worldState.test.ts new file mode 100644 index 0000000..3a3daec --- /dev/null +++ b/packages/engine-core/src/__tests__/worldState.test.ts @@ -0,0 +1,194 @@ +import { describe, it, expect, vi, afterEach, beforeEach } from "vitest"; +import { + createGameRuntime, + getWorldState, + useWorldStateStore, + useSceneStore, + type GameRuntime, + type GameSceneConfig, +} from "../index"; + +function makeScene(id: string): GameSceneConfig { + return { + id, + label: `Scene ${id}`, + background: "/bg.png", + playerSpawn: [0, 0, 0], + ground: { minX: -5, maxX: 5, minZ: -5, maxZ: 5, y: 0 }, + walls: [], + interactions: [], + }; +} + +const resetAll = () => { + getWorldState().reset(); + useSceneStore.setState({ sceneId: "" }); +}; + +let rt: GameRuntime | null = null; +beforeEach(resetAll); +afterEach(() => { + rt?.dispose(); + rt = null; + resetAll(); + vi.restoreAllMocks(); +}); + +describe("worldStateStore (sin runtime)", () => { + it("setFlag guarda y clearFlag borra", () => { + getWorldState().setFlag("a", true); + getWorldState().setFlag("n", 3); + getWorldState().setFlag("s", "x"); + expect(getWorldState().flags).toEqual({ a: true, n: 3, s: "x" }); + getWorldState().clearFlag("n"); + expect(getWorldState().flags).toEqual({ a: true, s: "x" }); + }); + + it("setFlag con el mismo valor no notifica a suscriptores", () => { + getWorldState().setFlag("a", 1); + const spy = vi.fn(); + const unsub = useWorldStateStore.subscribe(spy); + getWorldState().setFlag("a", 1); + expect(spy).not.toHaveBeenCalled(); + unsub(); + }); + + it("clearFlag de un flag inexistente no notifica", () => { + const spy = vi.fn(); + const unsub = useWorldStateStore.subscribe(spy); + getWorldState().clearFlag("nope"); + expect(spy).not.toHaveBeenCalled(); + unsub(); + }); + + it("markSceneVisited no duplica y conserva el orden", () => { + const w = getWorldState(); + w.markSceneVisited("b"); + w.markSceneVisited("a"); + w.markSceneVisited("b"); + expect(getWorldState().visitedSceneIds).toEqual(["b", "a"]); + }); + + it("setAll reemplaza flags y escenas (sin duplicados)", () => { + getWorldState().setFlag("old", 1); + getWorldState().setAll({ flags: { k: "v" }, visitedSceneIds: ["x", "y", "x"] }); + expect(getWorldState().flags).toEqual({ k: "v" }); + expect(getWorldState().visitedSceneIds).toEqual(["x", "y"]); + }); + + it("reset vacía todo", () => { + getWorldState().setFlag("a", true); + getWorldState().markSceneVisited("s"); + getWorldState().reset(); + expect(getWorldState().flags).toEqual({}); + expect(getWorldState().visitedSceneIds).toEqual([]); + }); +}); + +describe("runtime: comandos y evento state:flagChanged", () => { + it("state:setFlag escribe y emite sin previous la primera vez", () => { + rt = createGameRuntime(); + const spy = vi.fn(); + rt.on("state:flagChanged", spy); + rt.executeCommand({ type: "state:setFlag", name: "door", value: true }); + expect(getWorldState().flags.door).toBe(true); + expect(spy).toHaveBeenCalledTimes(1); + const ev = spy.mock.calls[0]![0]; + expect(ev).toEqual({ type: "state:flagChanged", name: "door", value: true }); + expect("previous" in ev).toBe(false); + }); + + it("el evento trae previous al cambiar el valor", () => { + rt = createGameRuntime(); + rt.executeCommand({ type: "state:setFlag", name: "n", value: 1 }); + const spy = vi.fn(); + rt.on("state:flagChanged", spy); + rt.executeCommand({ type: "state:setFlag", name: "n", value: 2 }); + expect(spy).toHaveBeenCalledWith({ type: "state:flagChanged", name: "n", value: 2, previous: 1 }); + }); + + it("mismo valor no emite", () => { + rt = createGameRuntime(); + rt.executeCommand({ type: "state:setFlag", name: "n", value: 1 }); + const spy = vi.fn(); + rt.on("state:flagChanged", spy); + rt.executeCommand({ type: "state:setFlag", name: "n", value: 1 }); + expect(spy).not.toHaveBeenCalled(); + }); + + it("state:clearFlag emite con previous y sin value", () => { + rt = createGameRuntime(); + rt.executeCommand({ type: "state:setFlag", name: "s", value: "x" }); + const spy = vi.fn(); + rt.on("state:flagChanged", spy); + rt.executeCommand({ type: "state:clearFlag", name: "s" }); + expect(getWorldState().flags).toEqual({}); + expect(spy).toHaveBeenCalledWith({ type: "state:flagChanged", name: "s", previous: "x" }); + }); + + it("clearFlag de flag inexistente no emite", () => { + rt = createGameRuntime(); + const spy = vi.fn(); + rt.on("state:flagChanged", spy); + rt.executeCommand({ type: "state:clearFlag", name: "zz" }); + expect(spy).not.toHaveBeenCalled(); + }); + + it("emite también con getWorldState().setFlag directo", () => { + rt = createGameRuntime(); + const spy = vi.fn(); + rt.on("state:flagChanged", spy); + getWorldState().setFlag("direct", 7); + expect(spy).toHaveBeenCalledWith({ type: "state:flagChanged", name: "direct", value: 7 }); + }); + + it("setAll emite un evento por cada flag que difiere", () => { + rt = createGameRuntime(); + getWorldState().setFlag("a", 1); + getWorldState().setFlag("b", 1); + const spy = vi.fn(); + rt.on("state:flagChanged", spy); + getWorldState().setAll({ flags: { b: 1, c: 2 }, visitedSceneIds: [] }); + const names = spy.mock.calls.map((c) => c[0].name).sort(); + expect(names).toEqual(["a", "c"]); + }); +}); + +describe("runtime: escenas visitadas y dispose", () => { + it("scene:set marca visitadas sin duplicados y en orden", () => { + rt = createGameRuntime({ scenes: [makeScene("w-a"), makeScene("w-b")] }); + rt.executeCommand({ type: "scene:set", sceneId: "w-a" }); + rt.executeCommand({ type: "scene:set", sceneId: "w-b" }); + rt.executeCommand({ type: "scene:set", sceneId: "w-a" }); + expect(getWorldState().visitedSceneIds).toEqual(["w-a", "w-b"]); + }); + + it("marca la escena ya activa al crear el runtime", () => { + useSceneStore.setState({ sceneId: "pre-active" }); + rt = createGameRuntime(); + expect(getWorldState().visitedSceneIds).toEqual(["pre-active"]); + }); + + it("tras dispose no se emite ni se marca nada", () => { + rt = createGameRuntime({ scenes: [makeScene("w-c")] }); + const spy = vi.fn(); + rt.on("state:flagChanged", spy); + const scene = rt.getScenes()["w-c"]!; + rt.dispose(); + getWorldState().setFlag("late", true); + useSceneStore.getState().setScene("w-c", scene as never); + expect(spy).not.toHaveBeenCalled(); + expect(getWorldState().visitedSceneIds).toEqual([]); + rt = null; + }); + + it("un segundo runtime tras dispose no duplica eventos", () => { + const first = createGameRuntime(); + first.dispose(); + rt = createGameRuntime(); + const spy = vi.fn(); + rt.on("state:flagChanged", spy); + getWorldState().setFlag("once", true); + expect(spy).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/engine-core/src/game/commands/types.ts b/packages/engine-core/src/game/commands/types.ts index db3bf41..2e98662 100644 --- a/packages/engine-core/src/game/commands/types.ts +++ b/packages/engine-core/src/game/commands/types.ts @@ -1,4 +1,5 @@ -import type { DialogDictionary, GameVec3, Locale, SoundCategory } from "../types"; +import type { Script } from "../narrative/actions"; +import type { DialogDictionary, GameVec3, Locale, SoundCategory, Verb } from "../types"; // Duplicated from ports/audio.ts to avoid circular imports. type AudioMuteTarget = "master" | SoundCategory; @@ -9,7 +10,7 @@ type AudioMuteTarget = "master" | SoundCategory; */ export type GameCommand = // Scene - | { type: "scene:set"; sceneId: string } + | { type: "scene:set"; sceneId: string; spawnPosition?: GameVec3 } | { type: "scene:respawn" } // Player | { type: "player:move"; position: GameVec3 } @@ -17,10 +18,19 @@ export type GameCommand = | { type: "player:walkTo"; position: GameVec3 } // Inventory | { type: "inventory:toggle" } - | { type: "inventory:pickup"; itemId: string } - | { type: "inventory:drop"; itemId: string; slotIndex: number } + | { type: "inventory:pickup"; itemId: string; placedItemId?: string } + | { + type: "inventory:drop"; + itemId: string; + slotIndex: number; + /** Destino: una interaccion de la escena activa. Como mucho uno de los dos. */ + interactionId?: string; + /** Destino: un hotspot (equivale a hotspot:interact con verb "useItem"). */ + hotspotId?: string; + } + | { type: "inventory:combine"; itemId: string; withItemId: string } // Dialog - | { type: "dialog:trigger"; dialogKey: string } + | { type: "dialog:trigger"; dialogKey: string; speaker?: string } | { type: "dialog:dismiss" } // Transitions | { type: "transition:activate"; transitionId: string } @@ -31,6 +41,23 @@ export type GameCommand = | { type: "audio:setVolume"; target: AudioMuteTarget; volume: number } // i18n | { type: "i18n:setLocale"; locale: Locale } - | { type: "i18n:registerDictionary"; locale: Locale; dict: DialogDictionary }; + | { type: "i18n:registerDictionary"; locale: Locale; dict: DialogDictionary } + // World state + | { type: "state:setFlag"; name: string; value: boolean | number | string } + | { type: "state:clearFlag"; name: string } + // Save / load + | { type: "game:save"; extra?: Record } + | { type: "game:load" } + | { type: "game:reset" } + // Narrative scripts + | { type: "script:run"; script: Script; interrupt?: boolean } + | { type: "script:cancelAll" } + // Hotspots + | { type: "hotspot:interact"; hotspotId: string; verb: Verb | "useItem"; itemId?: string } + // Dialogue trees (conversaciones; `dialog:*` es el bocadillo de una frase) + | { type: "dialogue:start"; dialogueId: string } + | { type: "dialogue:choose"; index: number } + | { type: "dialogue:advance" } + | { type: "dialogue:end" }; export type GameCommandType = GameCommand["type"]; diff --git a/packages/engine-core/src/game/events/legacyAdapter.ts b/packages/engine-core/src/game/events/legacyAdapter.ts index ef8f1ed..00e1d1e 100644 --- a/packages/engine-core/src/game/events/legacyAdapter.ts +++ b/packages/engine-core/src/game/events/legacyAdapter.ts @@ -2,6 +2,11 @@ import type { GameEvent } from "./types"; import type { RuntimeEvent } from "../types"; /** + * Deuda conocida: el resto de outcomes legacy de `onDrop` ("rule-miss", + * "on-player", "pickup-blocked", "item-interact", "unknown-item") siguen + * viajando como `item:dropped` con un `outcome` fuera del tipo (cast abajo). + * Los consumidores deben filtrar por `outcome`. + * * Mapea un RuntimeEvent legacy (onMove/onCollide/onDrop/onDialog) * al nuevo GameEvent equivalente. Permite mantener el callback * `onRuntimeEvent` mientras el bus es la fuente de verdad. @@ -17,10 +22,15 @@ export function legacyRuntimeEventToGameEvent(ev: RuntimeEvent): GameEvent { position: ev.position, }; case "onDrop": + // Recoger un ítem no es soltarlo: el outcome legacy "pickup-success" + // viaja por el bus como `item:pickedUp` (el callback legacy no cambia). + if (ev.outcome === "pickup-success") { + return { type: "item:pickedUp", itemId: ev.itemId, quantity: 1 }; + } return { type: "item:dropped", itemId: ev.itemId, - outcome: ev.outcome as "consume" | "place" | "return", + outcome: ev.outcome, interactionId: ev.interactionId, }; case "onDialog": diff --git a/packages/engine-core/src/game/events/types.ts b/packages/engine-core/src/game/events/types.ts index ad205f4..71e8284 100644 --- a/packages/engine-core/src/game/events/types.ts +++ b/packages/engine-core/src/game/events/types.ts @@ -1,4 +1,4 @@ -import type { AudioSettings, GameScene, GameVec3, Locale, SoundCategory } from "../types"; +import type { AudioSettings, GameScene, GameVec3, Locale, SoundCategory, Verb } from "../types"; /** * Union exhaustiva de todos los eventos que el motor puede emitir. @@ -20,11 +20,38 @@ export type GameEvent = | { type: "item:dropped"; itemId: string; - outcome: "consume" | "place" | "return"; + /** + * Outcome of the drop interaction. + * + * Rule results: + * - "consume": Item was consumed by the rule + * - "place": Item was placed in the world + * - "return": Item returned to inventory (fallback) + * + * No matching rule: + * - "rule-miss": Drop target exists but no rule matched + * - "unknown-item": Item not registered in the system + * - "on-player": Item was dropped on the player character + * + * @deprecated Legacy outcomes (do not use in new code): + * - "pickup-blocked": Attempted pickup was blocked (use `inventory:pickupFailed` instead) + * - "item-interact": Item click (use `hotspot:interacted` instead) + */ + outcome: + | "consume" + | "place" + | "return" + | "rule-miss" + | "unknown-item" + | "on-player" + | "pickup-blocked" + | "item-interact"; interactionId?: string; } + | { type: "item:removed"; itemId: string } + | { type: "inventory:full"; itemId: string } // Dialog - | { type: "dialog:triggered"; text: string; dialogKey?: string; source: string } + | { type: "dialog:triggered"; text: string; dialogKey?: string; source: string; speaker?: string } | { type: "dialog:dismissed"; dialogKey?: string } // Transitions | { type: "transition:triggered"; transitionId: string; targetSceneId: string } @@ -45,7 +72,53 @@ export type GameEvent = | { type: "audio:settingsChanged"; settings: AudioSettings } // i18n | { type: "i18n:localeChanged"; locale: Locale; previous: Locale } - | { type: "i18n:dictionaryUpdated"; locale: Locale; keysAdded: number }; + | { type: "i18n:dictionaryUpdated"; locale: Locale; keysAdded: number } + // World state + | { + type: "state:flagChanged"; + name: string; + value?: boolean | number | string; + previous?: boolean | number | string; + } + // Save / load + | { type: "game:saved" } + | { + type: "game:loaded"; + found: boolean; + /** true si se aplicó todo (la escena guardada estaba registrada). Solo con found. */ + applied?: boolean; + /** Estado propio del host guardado en la instantánea. Solo con found. */ + extra?: Record; + } + | { type: "game:reset" } + // Narrative scripts + | { type: "script:started"; id: number } + | { type: "script:finished"; id: number; result: "finished" | "cancelled" } + | { type: "input:lockChanged"; locked: boolean } + | { type: "custom"; name: string; payload?: unknown } + // Hotspots + | { type: "hotspot:interacted"; hotspotId: string; verb: Verb | "useItem"; itemId?: string } + | { + type: "hotspot:noAction"; + hotspotId: string; + verb: Verb | "useItem"; + itemId?: string; + reason: "not-found" | "hidden" | "missing-item" | "no-rule"; + } + // Dialogue trees + | { type: "dialogue:started"; dialogueId: string } + | { type: "dialogue:nodeEntered"; dialogueId: string; nodeId: string } + | { type: "dialogue:choiceMade"; dialogueId: string; nodeId: string; index: number } + | { type: "dialogue:ended"; dialogueId: string; reason: "finished" | "ended" | "cancelled" } + // Inventory (comandos inventory:pickup / inventory:drop) + | { + type: "inventory:pickupFailed"; + itemId: string; + reason: "not-found" | "blocked" | "full" | "unknown-item"; + } + // Item combination + | { type: "item:combined"; itemId: string; withItemId: string } + | { type: "item:combineFailed"; itemId: string; withItemId: string }; export type GameEventType = GameEvent["type"]; diff --git a/packages/engine-core/src/game/logic/rules/audioRules.ts b/packages/engine-core/src/game/logic/rules/audioRules.ts index 6c9c48a..554d2eb 100644 --- a/packages/engine-core/src/game/logic/rules/audioRules.ts +++ b/packages/engine-core/src/game/logic/rules/audioRules.ts @@ -58,6 +58,10 @@ export function resolveAudioEvents( } case "item:dropped": { + // Solo colocar suena. Devolver, consumir y los outcomes legacy que + // viajan fuera del tipo (rule-miss, on-player, pickup-blocked...) son + // silenciosos. + if (event.outcome !== "place") return []; const item = ctx.items[event.itemId]; // Prioridad: interacción específica > item > default const url = item?.dropSoundUrl ?? ctx.defaults.dropSoundUrl; diff --git a/packages/engine-core/src/game/logic/rules/inventoryRules.ts b/packages/engine-core/src/game/logic/rules/inventoryRules.ts index 056a246..1007fa4 100644 --- a/packages/engine-core/src/game/logic/rules/inventoryRules.ts +++ b/packages/engine-core/src/game/logic/rules/inventoryRules.ts @@ -1,5 +1,6 @@ import type { GameSceneInteraction, + GameSceneInteractionDialogKeys, DialogKey, ItemDefinition, ItemInteractionRule, @@ -113,7 +114,7 @@ export function addOneToInventory( return { slots: next, added: true }; } -type InventoryRuleContext = { +export type InventoryRuleContext = { getItemDefinition: (itemId: string) => ItemDefinition | null; resolveItemRule: (itemId: string, interactionId: string) => ItemInteractionRule | null; }; @@ -125,7 +126,7 @@ export function resolveInventoryDropHitDecision( payload, now, }: { - interaction: GameSceneInteraction & { dialogKeys?: Record; id?: string }; + interaction: GameSceneInteraction & { dialogKeys?: Partial; id?: string }; payload: DraggedPayloadState; now: number; }, @@ -138,12 +139,12 @@ export function resolveInventoryDropHitDecision( }; } - const interactionId = (interaction as any).id || ""; + const interactionId = (interaction as any).id ?? ""; const rule = context.resolveItemRule(itemDefinition.id, interactionId); if (!rule) { return { kind: "rule-miss", - dialogKey: (interaction as any).dialogKeys?.miss || DEFAULT_DROP_MISS_DIALOG_KEY, + dialogKey: (interaction as any).dialogKeys?.miss ?? DEFAULT_DROP_MISS_DIALOG_KEY, }; } @@ -168,7 +169,7 @@ export function resolveInventoryDropHitDecision( pickupSuccessDialogKey: rule.pickupSuccessDialogKey, pickupBlockedDialogKey: rule.pickupBlockedDialogKey, }, - dialogKey: rule.hitDialogKey || (interaction as any).dialogKeys?.hit || DEFAULT_DROP_MISS_DIALOG_KEY, + dialogKey: rule.hitDialogKey ?? (interaction as any).dialogKeys?.hit ?? DEFAULT_DROP_MISS_DIALOG_KEY, }; } @@ -176,14 +177,14 @@ export function resolveInventoryDropHitDecision( return { kind: "consume", fromSlotIndex: payload.fromSlotIndex, - dialogKey: rule.hitDialogKey || (interaction as any).dialogKeys?.hit || DEFAULT_DROP_MISS_DIALOG_KEY, + dialogKey: rule.hitDialogKey ?? (interaction as any).dialogKeys?.hit ?? DEFAULT_DROP_MISS_DIALOG_KEY, }; } return { kind: "return", dialogKey: - rule.hitDialogKey || rule.missDialogKey || (interaction as any).dialogKeys?.miss || DEFAULT_DROP_MISS_DIALOG_KEY, + rule.hitDialogKey ?? rule.missDialogKey ?? (interaction as any).dialogKeys?.miss ?? DEFAULT_DROP_MISS_DIALOG_KEY, }; } @@ -195,17 +196,17 @@ export function resolveInventoryDropMissDialogKey( sceneInteractions, }: { payload: DraggedPayloadState; - interaction?: GameSceneInteraction & { dialogKeys?: Record; id?: string }; - sceneInteractions: (GameSceneInteraction & { dialogKeys?: Record; id?: string; kind?: string })[]; + interaction?: GameSceneInteraction & { dialogKeys?: Partial; id?: string }; + sceneInteractions: (GameSceneInteraction & { dialogKeys?: Partial; id?: string; kind?: string })[]; }, ): DialogKey { const interactionId = (interaction as any)?.id; const itemRule = interactionId ? context.resolveItemRule(payload.stack.id, interactionId) : null; return ( - itemRule?.missDialogKey || - (interaction as any)?.dialogKeys?.miss || - sceneInteractions.find((currentInteraction) => currentInteraction.kind === "drop-target")?.dialogKeys?.miss || + itemRule?.missDialogKey ?? + (interaction as any)?.dialogKeys?.miss ?? + sceneInteractions.find((currentInteraction) => currentInteraction.kind === "drop-target")?.dialogKeys?.miss ?? DEFAULT_DROP_MISS_DIALOG_KEY ); } @@ -264,7 +265,7 @@ export function resolvePickupPlacedItemDecision( return { kind: "blocked", dialogKey: - placedItem.pickupBlockedDialogKey || getDefaultPickupDialogKey(placedItem.itemId, "blocked"), + placedItem.pickupBlockedDialogKey ?? getDefaultPickupDialogKey(placedItem.itemId, "blocked"), }; } @@ -277,7 +278,7 @@ export function resolvePickupPlacedItemDecision( spriteUrl: itemDefinition.spriteUrl, }, successDialogKey: - placedItem.pickupSuccessDialogKey || getDefaultPickupDialogKey(placedItem.itemId, "allowed"), + placedItem.pickupSuccessDialogKey ?? getDefaultPickupDialogKey(placedItem.itemId, "allowed"), }; } diff --git a/packages/engine-core/src/game/narrative/actionExecutors.ts b/packages/engine-core/src/game/narrative/actionExecutors.ts new file mode 100644 index 0000000..1a9a0cb --- /dev/null +++ b/packages/engine-core/src/game/narrative/actionExecutors.ts @@ -0,0 +1,234 @@ +import type { ClockPort } from "../../ports/clock"; +import type { GameCommand } from "../commands/types"; +import type { GameEvent, GameEventHandler, GameEventType } from "../events/types"; +import type { ScriptHandler } from "../runtime/types"; +import { + getInputLockState, + getInventoryState, + getSceneState, + usePlacedItemsStateStore, +} from "../state"; +import type { GameVec3 } from "../types"; +import type { Action, Script } from "./actions"; + +/** Lo que el secuenciador necesita del runtime (todo inyectado: sin acoplarse a el). */ +export interface SequencerEnv { + execute(cmd: GameCommand): void; + emit(event: GameEvent): void; + on(type: T, handler: GameEventHandler): () => void; + clock: ClockPort; + instantWalk: boolean; + getItem(id: string): { name: string; spriteUrl: string } | undefined; + getHandler(name: string): ScriptHandler | undefined; +} + +/** Contexto de la accion en curso. Todo lo que espere debe pasar por `wait`. */ +export interface ActionContext { + env: SequencerEnv; + /** true si el guion fue cancelado: tras cualquier espera, comprobarlo antes de actuar. */ + isCancelled(): boolean; + /** + * Espera hasta que `arm` llame a su `resolve`. `arm` devuelve la limpieza + * (quitar suscripcion / temporizador), que se ejecuta al resolver o al cancelar. + */ + wait(arm: (resolve: () => void) => () => void): Promise; + /** Fija el bloqueo de entrada; emite `input:lockChanged` solo si cambia. */ + setInputLock(locked: boolean): void; + /** + * Ejecuta un sub-guion "en linea": mismo bucle y misma cancelacion que el guion en + * curso, sin `script:started`/`finished` ni tocar la cola. Se resuelve al terminar + * las acciones o al cancelarse el guion. Seguro de llamar desde un ejecutor. + */ + runInline(script: Script): Promise; +} + +/** + * Ejecutor de una accion. Se registra por clave (`say`, `walkTo`...) con + * `Sequencer.registerExecutor`; el bucle del secuenciador no sabe nada de cada accion. + */ +export type ActionExecutor = (action: Action, ctx: ActionContext) => void | Promise; + +const noop = () => {}; + +function field(action: Action, key: string): T { + return (action as unknown as Record)[key] as T; +} + +function sayExecutor(action: Action, ctx: ActionContext): Promise { + const speaker = field(action, "speaker"); + return ctx.wait((resolve) => { + // Suscribir antes de despachar: el cierre podria ser sincrono. + const off = ctx.env.on("dialog:dismissed", () => resolve()); + ctx.env.execute({ + type: "dialog:trigger", + dialogKey: field(action, "say"), + ...(speaker !== undefined ? { speaker } : {}), + }); + return off; + }); +} + +/** + * walkTo: despacha `player:walkTo` y espera `player:walkCompleted` o `player:walkAborted`. + * Si se aborta (p. ej. destino inalcanzable) la accion termina y el guion CONTINUA. + * Con `instantWalk` el propio secuenciador coloca al jugador y emite `walkCompleted`. + */ +function walkToExecutor(action: Action, ctx: ActionContext): Promise { + const position = field(action, "walkTo"); + return ctx.wait((resolve) => { + let settled = false; + const end = () => { + settled = true; + resolve(); + }; + const offs = [ + ctx.env.on("player:walkCompleted", end), + ctx.env.on("player:walkAborted", end), + ]; + ctx.env.execute({ type: "player:walkTo", position }); + if (!settled && ctx.env.instantWalk) { + const scene = getSceneState(); + scene.setPlayerPosition(position); + scene.setPlayerWalkingState(null); + ctx.env.emit({ type: "player:walkCompleted", position }); + } + return () => offs.forEach((off) => off()); + }); +} + +function giveItemExecutor(action: Action, ctx: ActionContext): void { + const itemId = field(action, "giveItem"); + const item = ctx.env.getItem(itemId); + if (!item) { + console.warn(`[sequencer] giveItem: item no registrado: ${itemId}`); + return; + } + const added = getInventoryState().addItem({ + id: itemId, + name: item.name, + spriteUrl: item.spriteUrl, + }); + if (added) { + ctx.env.emit({ type: "item:pickedUp", itemId, quantity: 1 }); + } else { + console.warn(`[sequencer] giveItem: inventario lleno, no cabe: ${itemId}`); + ctx.env.emit({ type: "inventory:full", itemId }); + } +} + +function removeItemExecutor(action: Action, ctx: ActionContext): void { + const itemId = field(action, "removeItem"); + const inv = getInventoryState(); + const index = inv.slots.findIndex((s) => s !== null && s.id === itemId); + if (index < 0) { + console.warn(`[sequencer] removeItem: el inventario no tiene: ${itemId}`); + return; + } + inv.removeOne(index); + ctx.env.emit({ type: "item:removed", itemId }); +} + +async function callExecutor(action: Action, ctx: ActionContext): Promise { + const name = field(action, "call"); + const handler = ctx.env.getHandler(name); + if (!handler) { + console.warn(`[sequencer] call: sin manejador registrado: ${name}`); + return; + } + let result: void | Promise; + try { + result = handler(field(action, "args")); + } catch (error) { + console.error(`[sequencer] call: el manejador "${name}" lanzo:`, error); + return; + } + if (result && typeof (result as Promise).then === "function") { + const pending = result as Promise; + await ctx.wait((resolve) => { + pending.then( + () => resolve(), + (error) => { + console.error(`[sequencer] call: el manejador "${name}" rechazo:`, error); + resolve(); + }, + ); + return noop; + }); + } +} + +/** startDialogue: la tarea 07 lo sustituye con `registerExecutor("startDialogue", ...)`. */ +function startDialogueFallback(action: Action): void { + console.warn( + `[sequencer] startDialogue: no hay ejecutor de dialogos registrado: ${field(action, "startDialogue")}`, + ); +} + +/** Ejecutores por defecto, por clave de accion. */ +export function createDefaultExecutors(): Map { + return new Map([ + ["say", sayExecutor], + ["walkTo", walkToExecutor], + ["giveItem", giveItemExecutor], + ["removeItem", removeItemExecutor], + ["call", callExecutor], + ["startDialogue", startDialogueFallback], + [ + "setFlag", + (a, ctx) => + ctx.env.execute({ + type: "state:setFlag", + name: field(a, "setFlag"), + value: field(a, "value") ?? true, + }), + ], + [ + "changeScene", + (a, ctx) => { + const spawnPosition = field(a, "spawnPosition"); + ctx.env.execute({ + type: "scene:set", + sceneId: field(a, "changeScene"), + ...(spawnPosition ? { spawnPosition } : {}), + }); + }, + ], + ["placeItem", (a) => usePlacedItemsStateStore.getState().addItem(field(a, "placeItem"))], + [ + "removePlacedItem", + (a) => usePlacedItemsStateStore.getState().removeItem(field(a, "removePlacedItem")), + ], + [ + "wait", + (a, ctx) => { + const ms = field(a, "wait"); + const delay = typeof ms === "number" && Number.isFinite(ms) && ms > 0 ? ms : 0; + return ctx.wait((resolve) => ctx.env.clock.setTimeout(resolve, delay)); + }, + ], + [ + "playSfx", + (a, ctx) => ctx.env.execute({ type: "audio:playSfx", soundUrl: field(a, "playSfx") }), + ], + ["lockInput", (a, ctx) => ctx.setInputLock(field(a, "lockInput") === true)], + [ + "emit", + (a, ctx) => { + const payload = field(a, "payload"); + ctx.env.emit({ + type: "custom", + name: field(a, "emit"), + ...(payload !== undefined ? { payload } : {}), + }); + }, + ], + ]); +} + +/** Aplica el bloqueo al store y emite el evento solo si cambia. */ +export function applyInputLock(env: SequencerEnv, locked: boolean): void { + const lock = getInputLockState(); + if (lock.inputLocked === locked) return; + lock.setInputLocked(locked); + env.emit({ type: "input:lockChanged", locked }); +} diff --git a/packages/engine-core/src/game/narrative/actions.ts b/packages/engine-core/src/game/narrative/actions.ts new file mode 100644 index 0000000..27794e3 --- /dev/null +++ b/packages/engine-core/src/game/narrative/actions.ts @@ -0,0 +1,64 @@ +import type { GameVec3, PlacedSceneItem } from "../types"; +import type { FlagValue } from "../state/worldStateStore"; +import type { Condition } from "./conditions"; + +/** + * Acciones: dato serializable que describe QUE pasa, en orden. El secuenciador + * (sequencer.ts) las ejecuta despachando comandos existentes y esperando eventos. + */ +export type Action = + | { say: string; speaker?: string } // clave de dialogo; espera al cierre + | { setFlag: string; value?: FlagValue } // por defecto true + | { giveItem: string } + | { removeItem: string } + | { placeItem: PlacedSceneItem } + | { removePlacedItem: string } + | { changeScene: string; spawnPosition?: GameVec3 } + | { walkTo: GameVec3 } // espera al fin o al aborto de la caminata + | { wait: number } // ms, via ClockPort + | { playSfx: string } + | { startDialogue: string } // tarea 07; espera al final + | { lockInput: boolean } + | { emit: string; payload?: unknown } // evento { type: "custom", name, payload } + | { call: string; args?: unknown }; // manejador registrado por el host + +export type Script = Action[]; + +/** Rama condicional: sin `when` se cumple siempre. */ +export type Branch = { when?: Condition; do: Script }; + +export interface ScriptRun { + /** Resuelve cuando el guion termina o se cancela (nunca rechaza). */ + done: Promise<"finished" | "cancelled">; + /** Cancela el guion (en curso o en cola). Idempotente. */ + cancel(): void; +} + +/** Constructores: devuelven objetos planos serializables. */ +export const act = { + say: (key: string, speaker?: string): Action => + speaker === undefined ? { say: key } : { say: key, speaker }, + setFlag: (name: string, value?: FlagValue): Action => + value === undefined ? { setFlag: name } : { setFlag: name, value }, + giveItem: (id: string): Action => ({ giveItem: id }), + removeItem: (id: string): Action => ({ removeItem: id }), + placeItem: (item: PlacedSceneItem): Action => ({ placeItem: item }), + removePlacedItem: (id: string): Action => ({ removePlacedItem: id }), + changeScene: (sceneId: string, spawnPosition?: GameVec3): Action => + spawnPosition === undefined ? { changeScene: sceneId } : { changeScene: sceneId, spawnPosition }, + walkTo: (position: GameVec3): Action => ({ walkTo: position }), + wait: (ms: number): Action => ({ wait: ms }), + playSfx: (url: string): Action => ({ playSfx: url }), + lockInput: (locked: boolean): Action => ({ lockInput: locked }), + emit: (name: string, payload?: unknown): Action => + payload === undefined ? { emit: name } : { emit: name, payload }, + call: (name: string, args?: unknown): Action => + args === undefined ? { call: name } : { call: name, args }, + startDialogue: (id: string): Action => ({ startDialogue: id }), +}; + +/** Rama con condicion: `branch(cond.flag("x"), act.say("a"), act.wait(10))`. */ +export const branch = (when: Condition, ...actions: Action[]): Branch => ({ when, do: actions }); + +/** Rama por defecto (sin condicion); ponla la ultima. */ +export const otherwise = (...actions: Action[]): Branch => ({ do: actions }); diff --git a/packages/engine-core/src/game/narrative/branches.ts b/packages/engine-core/src/game/narrative/branches.ts new file mode 100644 index 0000000..f2ca956 --- /dev/null +++ b/packages/engine-core/src/game/narrative/branches.ts @@ -0,0 +1,11 @@ +import { evaluateCondition, type ConditionContext } from "./conditions"; +import type { Branch, Script } from "./actions"; + +/** Guion de la primera rama que se cumple (sin `when` = siempre), o `null`. */ +export function pickBranch(branches: Branch[] | undefined, ctx: ConditionContext): Script | null { + if (!Array.isArray(branches)) return null; + for (const b of branches) { + if (evaluateCondition(b?.when, ctx)) return Array.isArray(b?.do) ? b.do : []; + } + return null; +} diff --git a/packages/engine-core/src/game/narrative/combine.ts b/packages/engine-core/src/game/narrative/combine.ts new file mode 100644 index 0000000..c20cf4f --- /dev/null +++ b/packages/engine-core/src/game/narrative/combine.ts @@ -0,0 +1,62 @@ +import type { CommandHandler } from "../commands/CommandHandler"; +import type { GameEvent } from "../events/types"; +import { getInventoryState } from "../state/inventoryStore"; +import type { Branch, Script, ScriptRun } from "./actions"; +import { pickBranch } from "./branches"; +import { getConditionContext, type ConditionContext } from "./conditions"; + +/** Lo minimo que `resolveCombine` necesita de un item (`ItemDefinition` y `GameItemConfig` lo cumplen). */ +export type CombinableItem = { id: string; combine?: Record }; + +function hasOwn(obj: object, key: string): boolean { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +/** + * Busca la regla en `a.combine[b]` y, si no existe, en `b.combine[a]`. + * Devuelve el guion de la primera rama aplicable, o `null` si no hay ninguna. + */ +export function resolveCombine( + a: CombinableItem, + b: CombinableItem, + ctx: ConditionContext, +): Script | null { + if (a.combine && hasOwn(a.combine, b.id)) return pickBranch(a.combine[b.id], ctx); + if (b.combine && hasOwn(b.combine, a.id)) return pickBranch(b.combine[a.id], ctx); + return null; +} + +/** Lo que necesita el comando de combinacion (inyectado desde createGameRuntime). */ +export interface CombineCommandDeps { + emit(event: GameEvent): void; + runScript(script: Script): ScriptRun; + getItem(id: string): CombinableItem | undefined; +} + +/** + * Registra `inventory:combine`. El guion decide el resultado (`removeItem`, + * `giveItem`, `say`): el comando no quita ni anade items por su cuenta. + */ +export function registerCombineCommands(commands: CommandHandler, deps: CombineCommandDeps): void { + commands.register("inventory:combine", (cmd) => { + const { itemId, withItemId } = cmd; + const base = { itemId, withItemId }; + const fail = () => deps.emit({ type: "item:combineFailed", ...base }); + + if (itemId === withItemId) return fail(); + + const slots = getInventoryState().slots; + const inInventory = (id: string) => slots.some((slot) => slot?.id === id); + if (!inInventory(itemId) || !inInventory(withItemId)) return fail(); + + const a = deps.getItem(itemId); + const b = deps.getItem(withItemId); + if (!a || !b) return fail(); + + const script = resolveCombine(a, b, getConditionContext()); + if (script === null) return fail(); + + deps.emit({ type: "item:combined", ...base }); + deps.runScript(script); + }); +} diff --git a/packages/engine-core/src/game/narrative/conditions.ts b/packages/engine-core/src/game/narrative/conditions.ts new file mode 100644 index 0000000..25636bf --- /dev/null +++ b/packages/engine-core/src/game/narrative/conditions.ts @@ -0,0 +1,131 @@ +import type { InventorySlotsState, PlacedSceneItem } from "../types"; +import { getInventoryState } from "../state/inventoryStore"; +import { getPlacedItemsState } from "../state/placedItemsReactiveStore"; +import { getSceneState } from "../state/sceneStore"; +import { getWorldState, type FlagValue } from "../state/worldStateStore"; + +/** + * Condiciones: dato serializable para preguntar por el estado del juego sin efectos. + * El contenido es dato y puede venir mal escrito: una forma desconocida es `false`. + */ +export type Condition = + | { flag: string; equals?: FlagValue; gte?: number; lte?: number } // sin operador: "es verdadero" + | { hasItem: string; atLeast?: number } + | { itemPlaced: string; inScene?: string; at?: string } // at = interactionId + | { inScene: string } + | { visited: string } + | { all: Condition[] } + | { any: Condition[] } + | { not: Condition }; + +/** Todo lo que `evaluateCondition` necesita; se construye desde los stores o se inyecta. */ +export interface ConditionContext { + flags: Record; + inventory: InventorySlotsState; + placedItems: PlacedSceneItem[]; + sceneId: string; + visitedSceneIds: string[]; +} + +let warnedUnknown = false; + +function has(obj: object, key: string): boolean { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +function warnUnknown(condition: unknown): false { + if (!warnedUnknown) { + warnedUnknown = true; + console.warn("[conditions] Condicion con forma desconocida, se evalua a false:", condition); + } + return false; +} + +function evalFlag(c: Record, ctx: ConditionContext): boolean { + const name = c.flag as string; + const value: FlagValue | undefined = has(ctx.flags, name) ? ctx.flags[name] : undefined; + const hasEquals = has(c, "equals"); + const hasGte = c.gte !== undefined; + const hasLte = c.lte !== undefined; + if (!hasEquals && !hasGte && !hasLte) { + return ( + value === true || + (typeof value === "number" && value !== 0) || + (typeof value === "string" && value !== "") + ); + } + if (hasEquals && value !== c.equals) return false; + if (hasGte && !(typeof value === "number" && value >= (c.gte as number))) return false; + if (hasLte && !(typeof value === "number" && value <= (c.lte as number))) return false; + return true; +} + +function evalPlaced(c: Record, ctx: ConditionContext): boolean { + const { itemPlaced, inScene, at } = c as { itemPlaced: string; inScene?: string; at?: string }; + return ctx.placedItems.some( + (p) => + p.itemId === itemPlaced && + (inScene === undefined || p.sceneId === inScene) && + (at === undefined || p.interactionId === at), + ); +} + +/** Evalua una condicion. Pura: no lee stores. `undefined` cuenta como verdadero. */ +export function evaluateCondition( + condition: Condition | undefined, + ctx: ConditionContext, +): boolean { + if (condition === undefined) return true; + const c = condition as unknown as Record; + if (c === null || typeof c !== "object") return warnUnknown(condition); + if ("flag" in c) return evalFlag(c, ctx); + if ("hasItem" in c) { + const min = typeof c.atLeast === "number" ? c.atLeast : 1; + const total = ctx.inventory.reduce( + (n, s) => (s && s.id === c.hasItem ? n + s.quantity : n), + 0, + ); + return total >= min; + } + if ("itemPlaced" in c) return evalPlaced(c, ctx); + if ("inScene" in c) return ctx.sceneId === c.inScene; + if ("visited" in c) return ctx.visitedSceneIds.includes(c.visited as string); + if ("all" in c && Array.isArray(c.all)) { + return (c.all as Condition[]).every((x) => evaluateCondition(x, ctx)); + } + if ("any" in c && Array.isArray(c.any)) { + return (c.any as Condition[]).some((x) => evaluateCondition(x, ctx)); + } + if ("not" in c) return !evaluateCondition(c.not as Condition, ctx); + return warnUnknown(condition); +} + +/** Lee los stores actuales y construye el contexto. */ +export function getConditionContext(): ConditionContext { + const world = getWorldState(); + return { + flags: world.flags, + inventory: getInventoryState().slots, + placedItems: getPlacedItemsState().items, + sceneId: getSceneState().sceneId, + visitedSceneIds: world.visitedSceneIds, + }; +} + +/** Constructores: devuelven objetos planos serializables. */ +export const cond = { + flag: ( + name: string, + op: { equals?: FlagValue; gte?: number; lte?: number } = {}, + ): Condition => ({ flag: name, ...op }), + hasItem: (id: string, op: { atLeast?: number } = {}): Condition => ({ hasItem: id, ...op }), + itemPlaced: (id: string, op: { inScene?: string; at?: string } = {}): Condition => ({ + itemPlaced: id, + ...op, + }), + inScene: (sceneId: string): Condition => ({ inScene: sceneId }), + visited: (sceneId: string): Condition => ({ visited: sceneId }), + all: (...conditions: Condition[]): Condition => ({ all: conditions }), + any: (...conditions: Condition[]): Condition => ({ any: conditions }), + not: (condition: Condition): Condition => ({ not: condition }), +}; diff --git a/packages/engine-core/src/game/narrative/dialogue.ts b/packages/engine-core/src/game/narrative/dialogue.ts new file mode 100644 index 0000000..88efca0 --- /dev/null +++ b/packages/engine-core/src/game/narrative/dialogue.ts @@ -0,0 +1,228 @@ +import type { CommandHandler } from "../commands/CommandHandler"; +import type { GameEvent } from "../events/types"; +import { dialogueRegistry } from "../runtime/registry"; +import { useDialogueStore, type DialogueChoiceView } from "../state/dialogueStore"; +import { getInputLockState } from "../state/inputLockStore"; +import { getWorldState } from "../state/worldStateStore"; +import type { Action, Script, ScriptRun } from "./actions"; +import type { ActionContext, ActionExecutor } from "./actionExecutors"; +import { evaluateCondition, getConditionContext } from "./conditions"; +import type { + DialogueChoice, + DialogueDefinition, + DialogueEndReason, + DialogueNode, +} from "./dialogueTypes"; + +/** Nodos seguidos sin esperar al jugador antes de cortar (proteccion contra bucles). */ +export const MAX_DIALOGUE_STEPS = 500; + +export interface DialogueEngineDeps { + emit(event: GameEvent): void; + runScript(script: Script): ScriptRun; + registerExecutor(key: string, executor: ActionExecutor): () => void; +} + +export interface DialogueEngine { + /** Termina la conversacion activa (reason "cancelled") y suelta el ejecutor. */ + dispose(): void; +} + +type Waiting = "dismiss" | "choice"; +type VisibleChoice = { view: DialogueChoiceView; choice: DialogueChoice }; + +interface Session { + def: DialogueDefinition; + ctx: ActionContext; + over: boolean; + steps: number; + bubbleOpen: boolean; + visible: VisibleChoice[]; + waiting: { kind: Waiting; release: () => void } | null; + chosen: number | null; + wasLocked: boolean; + offDismissed: () => void; +} + +const onceFlag = (d: string, n: string, i: number) => `dlg.${d}.${n}.${i}`; + +function computeVisible(def: DialogueDefinition, node: DialogueNode): VisibleChoice[] { + if (!Array.isArray(node.choices)) return []; + const ctx = getConditionContext(); + const flags = getWorldState().flags; + const out: VisibleChoice[] = []; + node.choices.forEach((choice, index) => { + if (!choice || typeof choice !== "object") return; + if (choice.once && flags[onceFlag(def.id, node.id, index)] === true) return; + if (!evaluateCondition(choice.when, ctx)) return; + out.push({ view: { index, textKey: choice.text }, choice }); + }); + return out; +} + +/** + * Motor de conversaciones. Corre SIEMPRE dentro de un guion (accion `startDialogue`): + * los `do` de nodos y opciones se ejecutan "en linea" (`ctx.runInline`), sin pasar por + * la cola del secuenciador, asi que no hay interbloqueo con el guion contenedor. + */ +export function registerDialogueCommands( + commands: CommandHandler, + deps: DialogueEngineDeps, +): DialogueEngine { + let session: Session | null = null; + + function finish(s: Session, reason: DialogueEndReason): void { + if (s.over) return; + s.over = true; + s.offDismissed(); + if (session === s) session = null; + if (s.bubbleOpen) { + s.bubbleOpen = false; + s.ctx.env.execute({ type: "dialog:dismiss" }); + } + useDialogueStore.getState().clear(); + if (!s.wasLocked) s.ctx.setInputLock(false); + deps.emit({ type: "dialogue:ended", dialogueId: s.def.id, reason }); + s.waiting?.release(); + } + + /** Espera una entrada del jugador (cierre del bocadillo o eleccion). */ + async function awaitInput(s: Session, kind: Waiting, arm: () => void): Promise { + await s.ctx.wait((resolve) => { + s.waiting = { kind, release: resolve }; + arm(); + return () => { + s.waiting = null; + }; + }); + s.steps = 0; + } + + const stopped = (s: Session) => s.over || s.ctx.isCancelled(); + + /** Entra en un nodo; devuelve el id del siguiente o undefined si termina. */ + async function enterNode(s: Session, node: DialogueNode): Promise { + const { def, ctx } = s; + const store = useDialogueStore.getState(); + store.enterNode(def.id, node.id, node.speaker, node.line); + deps.emit({ type: "dialogue:nodeEntered", dialogueId: def.id, nodeId: node.id }); + if (Array.isArray(node.do)) { + await ctx.runInline(node.do); + if (stopped(s)) return undefined; + } + s.visible = computeVisible(def, node); + store.setChoices(s.visible.map((v) => v.view)); + const showLine = () => { + if (typeof node.line !== "string") return; + s.bubbleOpen = true; + ctx.env.execute({ + type: "dialog:trigger", + dialogKey: node.line!, + ...(node.speaker !== undefined ? { speaker: node.speaker } : {}), + }); + }; + if (s.visible.length === 0) { + if (typeof node.line === "string") await awaitInput(s, "dismiss", showLine); + return stopped(s) ? undefined : node.next; + } + s.chosen = null; + await awaitInput(s, "choice", showLine); + if (stopped(s) || s.chosen === null) return undefined; + const picked = s.visible.find((v) => v.view.index === s.chosen)!; + const index = picked.view.index; + store.setChoices([]); + deps.emit({ type: "dialogue:choiceMade", dialogueId: def.id, nodeId: node.id, index }); + if (picked.choice.once) { + ctx.env.execute({ type: "state:setFlag", name: onceFlag(def.id, node.id, index), value: true }); + } + if (s.bubbleOpen) { + s.bubbleOpen = false; + ctx.env.execute({ type: "dialog:dismiss" }); + } + if (Array.isArray(picked.choice.do)) { + await ctx.runInline(picked.choice.do); + if (stopped(s)) return undefined; + } + return picked.choice.next; + } + + async function runDialogue(id: string, ctx: ActionContext): Promise { + if (session) { + console.warn(`[dialogue] startDialogue: ya hay un dialogo activo, se ignora: ${id}`); + return; + } + const def = dialogueRegistry.get(id); + const s: Session = { + def: def ?? { id, start: "", nodes: [] }, + ctx, + over: false, + steps: 0, + bubbleOpen: false, + visible: [], + waiting: null, + chosen: null, + wasLocked: getInputLockState().inputLocked, + offDismissed: () => {}, + }; + session = s; + deps.emit({ type: "dialogue:started", dialogueId: id }); + if (!def) { + console.warn(`[dialogue] dialogo no registrado: ${id}`); + return finish(s, "finished"); + } + ctx.setInputLock(true); + s.offDismissed = ctx.env.on("dialog:dismissed", () => { + s.bubbleOpen = false; + if (s.waiting?.kind === "dismiss") s.waiting.release(); + }); + const nodes = Array.isArray(def.nodes) ? def.nodes : []; + let nodeId: string | undefined = def.start; + while (nodeId !== undefined && !stopped(s)) { + if (++s.steps > MAX_DIALOGUE_STEPS) { + console.warn(`[dialogue] ${id}: mas de ${MAX_DIALOGUE_STEPS} nodos sin entrada del jugador, se corta`); + break; + } + const node = nodes.find((n) => n?.id === nodeId); + if (!node) { + console.warn(`[dialogue] ${id}: nodo inexistente: ${nodeId}`); + break; + } + nodeId = await enterNode(s, node); + } + finish(s, ctx.isCancelled() ? "cancelled" : "finished"); + } + + const restore = deps.registerExecutor("startDialogue", (action: Action, ctx) => + runDialogue(String((action as { startDialogue: string }).startDialogue), ctx), + ); + + commands.register("dialogue:start", (cmd) => { + if (session) { + console.warn(`[dialogue] dialogue:start: ya hay un dialogo activo, se ignora: ${cmd.dialogueId}`); + return; + } + deps.runScript([{ startDialogue: cmd.dialogueId }]); + }); + commands.register("dialogue:choose", (cmd) => { + const s = session; + if (!s || s.waiting?.kind !== "choice" || !s.visible.some((v) => v.view.index === cmd.index)) { + console.warn(`[dialogue] dialogue:choose: eleccion no valida: ${String(cmd.index)}`); + return; + } + s.chosen = cmd.index; + s.waiting.release(); + }); + commands.register("dialogue:advance", () => { + if (session?.waiting?.kind === "dismiss") session.ctx.env.execute({ type: "dialog:dismiss" }); + }); + commands.register("dialogue:end", () => { + if (session) finish(session, "ended"); + }); + + return { + dispose() { + if (session) finish(session, "cancelled"); + restore(); + }, + }; +} diff --git a/packages/engine-core/src/game/narrative/dialogueTypes.ts b/packages/engine-core/src/game/narrative/dialogueTypes.ts new file mode 100644 index 0000000..0da5fed --- /dev/null +++ b/packages/engine-core/src/game/narrative/dialogueTypes.ts @@ -0,0 +1,54 @@ +import type { Condition } from "./conditions"; +import type { Script } from "./actions"; + +/** + * Arboles de dialogo: dato serializable. `dialog*` es el bocadillo de una frase; + * `dialogue*` es la conversacion con varios turnos y opciones. + */ +export interface DialogueChoice { + /** Clave de i18n del texto de la opcion. */ + text: string; + /** Opcion oculta si no se cumple. */ + when?: Condition; + /** Desaparece tras elegirla (se recuerda con el flag `dlg...`). */ + once?: boolean; + do?: Script; + next?: string; +} + +export interface DialogueNode { + id: string; + /** Id de NPC o "player". */ + speaker?: string; + /** Clave de i18n; sin linea, el nodo solo ejecuta `do`. */ + line?: string; + /** Efectos al entrar en el nodo (se esperan antes de seguir). */ + do?: Script; + /** Sin opciones visibles, avanza a `next`. */ + choices?: DialogueChoice[]; + /** Sin next ni opciones visibles, el dialogo termina. */ + next?: string; +} + +export interface DialogueDefinition { + id: string; + start: string; + nodes: DialogueNode[]; +} + +/** Motivo del fin de una conversacion. */ +export type DialogueEndReason = "finished" | "ended" | "cancelled"; + +/** Constructores opcionales (como `cond` / `act`): devuelven objetos planos. */ +export const dialogue = { + define: (id: string, start: string, ...nodes: DialogueNode[]): DialogueDefinition => ({ + id, + start, + nodes, + }), + node: (id: string, props: Omit = {}): DialogueNode => ({ id, ...props }), + choice: (text: string, props: Omit = {}): DialogueChoice => ({ + text, + ...props, + }), +}; diff --git a/packages/engine-core/src/game/narrative/hotspots.ts b/packages/engine-core/src/game/narrative/hotspots.ts new file mode 100644 index 0000000..d099141 --- /dev/null +++ b/packages/engine-core/src/game/narrative/hotspots.ts @@ -0,0 +1,79 @@ +import type { CommandHandler } from "../commands/CommandHandler"; +import type { GameEvent } from "../events/types"; +import type { ScriptRun, Script } from "./actions"; +import { getInventoryState } from "../state/inventoryStore"; +import { getSceneState } from "../state/sceneStore"; +import type { GameSceneHotspot, Verb } from "../types"; +import { pickBranch } from "./branches"; +import { evaluateCondition, getConditionContext, type ConditionContext } from "./conditions"; + +/** Orden de preferencia del verbo por defecto (y del menu de verbos). */ +const VERB_ORDER: readonly Verb[] = ["talk", "use", "look"]; + +/** Verbos del hotspot que tienen una rama aplicable en este contexto, en orden talk, use, look. */ +export function getAvailableVerbs(hotspot: GameSceneHotspot, ctx: ConditionContext): Verb[] { + return VERB_ORDER.filter((verb) => pickBranch(hotspot.verbs?.[verb], ctx) !== null); +} + +/** Entre los verbos con una rama aplicable: talk, luego use, luego look; `null` si ninguno. */ +export function getDefaultVerb(hotspot: GameSceneHotspot, ctx: ConditionContext): Verb | null { + return getAvailableVerbs(hotspot, ctx)[0] ?? null; +} + +/** true si el hotspot es visible (sin `visibleWhen` siempre lo es). */ +export function isHotspotVisible(hotspot: GameSceneHotspot, ctx: ConditionContext): boolean { + return evaluateCondition(hotspot.visibleWhen, ctx); +} + +function hasOwn(obj: object, key: string): boolean { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +/** Lo que necesitan los comandos de hotspot (inyectado desde createGameRuntime). */ +export interface HotspotCommandDeps { + emit(event: GameEvent): void; + runScript(script: Script): ScriptRun; +} + +/** + * Registra `hotspot:interact`. Recibe `runScript` del secuenciador en lugar de + * ampliar `registerRuntimeExecutors`: asi el secuenciador no sale del cierre de + * `createGameRuntime` y cada modulo narrativo (hotspots, dialogos) se cablea igual. + */ +export function registerHotspotCommands(commands: CommandHandler, deps: HotspotCommandDeps): void { + commands.register("hotspot:interact", (cmd) => { + const { hotspotId, verb } = cmd; + const itemId = cmd.itemId; + const base = { hotspotId, verb, ...(itemId !== undefined ? { itemId } : {}) }; + const noAction = (reason: "not-found" | "hidden" | "missing-item" | "no-rule") => + deps.emit({ type: "hotspot:noAction", ...base, reason }); + + const hotspot = getSceneState().scene.hotspots?.find((h) => h.id === hotspotId); + if (!hotspot) { + console.warn(`[hotspots] hotspot:interact — hotspot no encontrado en la escena activa: ${hotspotId}`); + return noAction("not-found"); + } + const ctx = getConditionContext(); + if (!isHotspotVisible(hotspot, ctx)) return noAction("hidden"); + + let branches; + if (verb === "useItem") { + if (itemId === undefined || !getInventoryState().slots.some((s) => s?.id === itemId)) { + return noAction("missing-item"); + } + branches = + hotspot.useItem && hasOwn(hotspot.useItem, itemId) + ? hotspot.useItem[itemId] + : hotspot.useItemDefault; + } else { + branches = hotspot.verbs?.[verb]; + } + + const body = pickBranch(branches, ctx); + if (body === null) return noAction("no-rule"); + + deps.emit({ type: "hotspot:interacted", ...base }); + const script: Script = hotspot.approach ? [{ walkTo: hotspot.approach }, ...body] : body; + deps.runScript(script); + }); +} diff --git a/packages/engine-core/src/game/narrative/index.ts b/packages/engine-core/src/game/narrative/index.ts new file mode 100644 index 0000000..e30e650 --- /dev/null +++ b/packages/engine-core/src/game/narrative/index.ts @@ -0,0 +1,51 @@ +export { + cond, + evaluateCondition, + getConditionContext, + type Condition, + type ConditionContext, +} from "./conditions"; +export { + act, + branch, + otherwise, + type Action, + type Script, + type Branch, + type ScriptRun, +} from "./actions"; +export { pickBranch } from "./branches"; +export { + evaluateTransitionGate, + getDeclaredScene, + getSceneRuleContext, + resolveEnterScript, + resolveInitialItems, + type DeclaredSceneRules, + type TransitionGate, +} from "./sceneRules"; +export { resolveCombine, type CombinableItem } from "./combine"; +export { + getAvailableVerbs, + getDefaultVerb, + isHotspotVisible, + registerHotspotCommands, + type HotspotCommandDeps, +} from "./hotspots"; +export { npcToHotspot, NPC_HOTSPOT_HALF_SIZE } from "./npcs"; +export { + dialogue, + type DialogueChoice, + type DialogueDefinition, + type DialogueEndReason, + type DialogueNode, +} from "./dialogueTypes"; +export { + registerDialogueCommands, + MAX_DIALOGUE_STEPS, + type DialogueEngine, + type DialogueEngineDeps, +} from "./dialogue"; +export { createSequencer, type Sequencer, type SequencerEnvInput } from "./sequencer"; +export type { ActionContext, ActionExecutor, SequencerEnv } from "./actionExecutors"; +export { validateContent, type ContentIssue, type GameContent } from "./validateContent"; diff --git a/packages/engine-core/src/game/narrative/npcs.ts b/packages/engine-core/src/game/narrative/npcs.ts new file mode 100644 index 0000000..4a23c22 --- /dev/null +++ b/packages/engine-core/src/game/narrative/npcs.ts @@ -0,0 +1,34 @@ +import type { GameSceneHotspot, GameSceneNpc, GameVec3, Verb } from "../types"; +import type { Branch } from "./actions"; + +/** + * Caja de interaccion por defecto de un NPC proyectado a hotspot (semi-extensiones en mundo). + * Cubre de los pies a la cabeza un sprite del tamano por defecto; `npc.clickBox` la sustituye. + */ +export const NPC_HOTSPOT_HALF_SIZE: GameVec3 = [1.1, 2.9, 0.5]; +/** Desplazamiento por defecto del centro de la caja respecto a `npc.position` (que esta a la altura de la cadera). */ +export const NPC_HOTSPOT_OFFSET: GameVec3 = [0, 2, 0]; + +/** + * Proyecta un NPC a hotspot para reutilizar `hotspot:interact` (verbos, ramas, approach). + * Pura. `dialogueId` equivale a `verbs.talk = [{ do: [{ startDialogue }] }]`; un + * `verbs.talk` explicito del NPC tiene prioridad sobre el atajo. + */ +export function npcToHotspot(npc: GameSceneNpc): GameSceneHotspot { + let verbs: Partial> | undefined = npc.verbs; + if (npc.dialogueId !== undefined && !npc.verbs?.talk) { + verbs = { ...npc.verbs, talk: [{ do: [{ startDialogue: npc.dialogueId }] }] }; + } + const offset = npc.clickBox?.offset ?? NPC_HOTSPOT_OFFSET; + return { + id: npc.id, + label: npc.name, + position: [npc.position[0] + offset[0], npc.position[1] + offset[1], npc.position[2] + offset[2]], + halfSize: npc.clickBox?.halfSize ?? NPC_HOTSPOT_HALF_SIZE, + ...(npc.visibleWhen !== undefined ? { visibleWhen: npc.visibleWhen } : {}), + ...(npc.hasCollision !== undefined ? { hasCollision: npc.hasCollision } : {}), + ...(npc.approach !== undefined ? { approach: npc.approach } : {}), + ...(verbs !== undefined ? { verbs } : {}), + ...(npc.useItem !== undefined ? { useItem: npc.useItem } : {}), + }; +} diff --git a/packages/engine-core/src/game/narrative/sceneRules.ts b/packages/engine-core/src/game/narrative/sceneRules.ts new file mode 100644 index 0000000..63d1c9f --- /dev/null +++ b/packages/engine-core/src/game/narrative/sceneRules.ts @@ -0,0 +1,81 @@ +import type { GameScene, GameSceneTransition, PlacedSceneItem, SceneInitialItem } from "../types"; +import { getSceneState } from "../state/sceneStore"; +import { sceneRegistry } from "../runtime/registry"; +import type { Script } from "./actions"; +import { pickBranch } from "./branches"; +import { evaluateCondition, getConditionContext, type ConditionContext } from "./conditions"; + +/** + * Reglas de escena declarativas: tres reglas que antes eran callbacks del host + * (siembra inicial, guion de entrada y permiso/bloqueo de transiciones) pasan a ser + * dato de la escena. Todo lo de este modulo es puro salvo `getDeclaredScene`. + * + * Orden de evaluacion cuando el host ademas pasa los callbacks de la Fase 16: + * - Siembra: primero `scene.initialItems`; despues `getInitialPlacedItems`, que ve + * los items declarativos ya anadidos y cuyos items se anaden tras ellos. + * - Entrada: primero el guion de `scene.onEnter`; despues `onSceneEnter`. + * - Transicion: primero `transition.when`/`blocked`; solo si deja pasar se evalua + * `canLeaveScene`, que puede vetar. Si `when` falla, `canLeaveScene` no se llama. + */ + +/** Los campos declarativos de una escena que consumen los hosts. */ +export type DeclaredSceneRules = Pick; + +/** + * Items iniciales cuyo `when` se cumple en `ctx` (sin `when`, siempre), en orden. + * `null` si la escena no declara `initialItems` (el host puede usar su callback). + * Todos los `when` se evaluan contra el mismo `ctx` (el estado previo a la siembra). + * Un item sin `sceneId` recibe `sceneId`. + */ +export function resolveInitialItems( + sceneId: string, + initialItems: SceneInitialItem[] | undefined, + ctx: ConditionContext, +): PlacedSceneItem[] | null { + if (!Array.isArray(initialItems)) return null; + const out: PlacedSceneItem[] = []; + for (const entry of initialItems) { + if (!entry || !entry.item) continue; + if (!evaluateCondition(entry.when, ctx)) continue; + out.push(entry.item.sceneId === undefined ? { ...entry.item, sceneId } : entry.item); + } + return out; +} + +/** Guion de la primera rama de `onEnter` que se cumple, o `null` (sin `onEnter` o ninguna). */ +export function resolveEnterScript( + onEnter: DeclaredSceneRules["onEnter"], + ctx: ConditionContext, +): Script | null { + return pickBranch(onEnter, ctx); +} + +export type TransitionGate = { allowed: true } | { allowed: false; blocked: Script }; + +/** + * Decide si una transicion esta permitida por su `when` (aplica a todos los tipos). + * Sin `when` -> permitida. Si no se cumple, devuelve el guion `blocked` (o `[]`). + */ +export function evaluateTransitionGate( + transition: Pick, + ctx: ConditionContext, +): TransitionGate { + if (evaluateCondition(transition.when, ctx)) return { allowed: true }; + return { allowed: false, blocked: Array.isArray(transition.blocked) ? transition.blocked : [] }; +} + +/** + * Reglas declarativas de la escena `sceneId`: la escena activa si coincide el id, + * o la registrada en el runtime. `undefined` si no se conoce. + */ +export function getDeclaredScene(sceneId: string): DeclaredSceneRules | undefined { + const active = getSceneState(); + if (active.sceneId === sceneId) return active.scene; + return sceneRegistry.get(sceneId); +} + +/** Contexto de condiciones para `sceneId`, con los items colocados dados (p. ej. antes de sembrar). */ +export function getSceneRuleContext(sceneId: string, placedItems?: PlacedSceneItem[]): ConditionContext { + const ctx = getConditionContext(); + return { ...ctx, sceneId, ...(placedItems ? { placedItems } : {}) }; +} diff --git a/packages/engine-core/src/game/narrative/sequencer.ts b/packages/engine-core/src/game/narrative/sequencer.ts new file mode 100644 index 0000000..1e1cefc --- /dev/null +++ b/packages/engine-core/src/game/narrative/sequencer.ts @@ -0,0 +1,202 @@ +import type { ScriptHandler } from "../runtime/types"; +import type { Action, Script, ScriptRun } from "./actions"; +import { + applyInputLock, + createDefaultExecutors, + type ActionContext, + type ActionExecutor, + type SequencerEnv, +} from "./actionExecutors"; + +type Result = "finished" | "cancelled"; + +interface Entry { + id: number; + script: Script; + started: boolean; + settled: boolean; + cancelled: boolean; + /** true si este guion dejo el bloqueo de entrada activo. */ + lockedByMe: boolean; + /** Esperas pendientes de la accion en curso; cancelar las resuelve y limpia. */ + aborts: Set<() => void>; + resolve: (result: Result) => void; +} + +export type SequencerEnvInput = Omit; + +export interface Sequencer { + /** Ejecuta un guion: uno a la vez, el resto en cola FIFO. */ + run(script: Script, opts?: { interrupt?: boolean }): ScriptRun; + /** Cancela el guion en curso y vacia la cola. */ + cancelAll(): void; + /** + * Punto de extension: registra (o sustituye) el ejecutor de una clave de accion. + * Devuelve la funcion que restaura el ejecutor anterior. + */ + registerExecutor(key: string, executor: ActionExecutor): () => void; + /** Manejadores de la accion `call`. Devuelve la funcion que lo quita. */ + registerHandler(name: string, fn: ScriptHandler): () => void; + /** Cancela todo y deja de aceptar guiones. */ + dispose(): void; +} + +export function createSequencer(input: SequencerEnvInput): Sequencer { + const handlers = new Map(); + const executors = createDefaultExecutors(); + const env: SequencerEnv = { ...input, getHandler: (name) => handlers.get(name) }; + const queue: Entry[] = []; + const warnedShapes = new Set(); + let current: Entry | null = null; + let nextId = 1; + let disposed = false; + + function settle(entry: Entry, result: Result): void { + if (entry.settled) return; + entry.settled = true; + if (result === "cancelled") { + entry.cancelled = true; + for (const abort of [...entry.aborts]) abort(); + } + if (entry.lockedByMe) { + entry.lockedByMe = false; + applyInputLock(env, false); + } + if (current === entry) current = null; + if (entry.started) env.emit({ type: "script:finished", id: entry.id, result }); + entry.resolve(result); + pump(); + } + + function makeContext(entry: Entry): ActionContext { + const ctx: ActionContext = { + env, + isCancelled: () => entry.cancelled, + setInputLock: (locked) => { + if (entry.cancelled) return; + entry.lockedByMe = locked; + applyInputLock(env, locked); + }, + wait: (arm) => + new Promise((resolve) => { + if (entry.cancelled) return resolve(); + let done = false; + let cleanup: (() => void) | null = null; + const finish = () => { + if (done) return; + done = true; + entry.aborts.delete(finish); + cleanup?.(); + resolve(); + }; + entry.aborts.add(finish); + cleanup = arm(finish); + if (done) cleanup(); + }), + runInline: async (script) => { + for (const action of Array.isArray(script) ? script : []) { + if (entry.cancelled) return; + await runAction(action, ctx); + } + }, + }; + return ctx; + } + + async function runAction(action: Action, ctx: ActionContext): Promise { + const shape = + action !== null && typeof action === "object" + ? Object.keys(action).find((k) => executors.has(k)) + : undefined; + if (shape === undefined) { + const label = + action !== null && typeof action === "object" ? Object.keys(action).sort().join(",") : String(action); + if (!warnedShapes.has(label)) { + warnedShapes.add(label); + console.warn("[sequencer] Accion con forma desconocida, se salta:", action); + } + return; + } + try { + await executors.get(shape)!(action, ctx); + } catch (error) { + console.error(`[sequencer] la accion "${shape}" fallo, el guion continua:`, error); + } + } + + async function loop(entry: Entry): Promise { + const ctx = makeContext(entry); + await ctx.runInline(entry.script); + if (entry.cancelled) return; + settle(entry, "finished"); + } + + function pump(): void { + if (current || disposed) return; + const next = queue.shift(); + if (!next) return; + current = next; + next.started = true; + env.emit({ type: "script:started", id: next.id }); + void loop(next); + } + + function cancelAll(): void { + const pending = queue.splice(0); + for (const entry of pending) settle(entry, "cancelled"); + if (current) settle(current, "cancelled"); + } + + function run(script: Script, opts?: { interrupt?: boolean }): ScriptRun { + if (disposed) return { done: Promise.resolve("cancelled"), cancel: () => {} }; + let resolve!: (r: Result) => void; + const done = new Promise((r) => (resolve = r)); + const entry: Entry = { + id: nextId++, + script, + started: false, + settled: false, + cancelled: false, + lockedByMe: false, + aborts: new Set(), + resolve, + }; + // Interrumpir antes de encolar: el nuevo no se cancela a si mismo. + if (opts?.interrupt) cancelAll(); + queue.push(entry); + pump(); + return { + done, + cancel: () => { + const i = queue.indexOf(entry); + if (i >= 0) queue.splice(i, 1); + settle(entry, "cancelled"); + }, + }; + } + + return { + run, + cancelAll, + registerExecutor(key, executor) { + const previous = executors.get(key); + executors.set(key, executor); + return () => { + if (executors.get(key) !== executor) return; + if (previous) executors.set(key, previous); + else executors.delete(key); + }; + }, + registerHandler(name, fn) { + handlers.set(name, fn); + return () => { + if (handlers.get(name) === fn) handlers.delete(name); + }; + }, + dispose() { + cancelAll(); + disposed = true; + handlers.clear(); + }, + }; +} diff --git a/packages/engine-core/src/game/narrative/validateContent.ts b/packages/engine-core/src/game/narrative/validateContent.ts new file mode 100644 index 0000000..e34849f --- /dev/null +++ b/packages/engine-core/src/game/narrative/validateContent.ts @@ -0,0 +1,188 @@ +import type { GameItemConfig, GameSceneConfig } from "../runtime/types"; +import type { Branch } from "./actions"; +import { validateDialogue } from "./validateDialogues"; +import { + addEdge, + ANY_SCENE, + refDialogKey, + refInteraction, + refItem, + refScene, + scanBranches, + scanCondition, + scanScript, +} from "./validateScan"; +import { + checkDuplicates, + report, + type ContentIssue, + type GameContent, + type ValidationCtx, +} from "./validateTypes"; + +export type { ContentIssue, GameContent } from "./validateTypes"; + +const VERBS = ["look", "use", "talk"]; + +type Scope = { sceneId: string }; + +type Interactive = { + verbs?: Partial>; + useItem?: Record; + useItemDefault?: Branch[]; + visibleWhen?: unknown; +}; + +/** `verbs`, `useItem`, `useItemDefault` y `visibleWhen` son iguales en hotspots y NPCs. */ +function validateInteractive(ctx: ValidationCtx, at: string, e: Interactive, scope: Scope): void { + scanCondition(ctx, e.visibleWhen, `${at} > visibleWhen`, scope); + for (const [verb, branches] of Object.entries(e.verbs ?? {})) { + if (!VERBS.includes(verb)) { + report(ctx, "error", "unknown-verb", `${at} > verbs.${verb}`, `verbo desconocido: "${verb}" (validos: ${VERBS.join(", ")})`); + } + scanBranches(ctx, branches, `${at} > verbs.${verb}`, scope); + } + for (const [itemId, branches] of Object.entries(e.useItem ?? {})) { + refItem(ctx, itemId, `${at} > useItem.${itemId}`, "useItem"); + scanBranches(ctx, branches, `${at} > useItem.${itemId}`, scope); + } + scanBranches(ctx, e.useItemDefault, `${at} > useItemDefault`, scope); +} + +function validateTransitions(ctx: ValidationCtx, scene: GameSceneConfig, base: string): void { + const scope = { sceneId: scene.id }; + const list = scene.transitions ?? []; + checkDuplicates(ctx, "transicion", base, list.map((t) => t.id)); + for (const t of list) { + const at = `${base} > transition:${t.id}`; + refScene(ctx, t.targetSceneId, `${at} > targetSceneId`, "la transicion"); + addEdge(ctx, scope, t.targetSceneId); + const req = t as { requiresItemId?: string; requiresInteractionId?: string }; + refItem(ctx, req.requiresItemId, `${at} > requiresItemId`, "la transicion"); + refInteraction(ctx, scene.id, req.requiresInteractionId, `${at} > requiresInteractionId`, "la transicion"); + scanCondition(ctx, t.when, `${at} > when`, scope); + scanScript(ctx, t.blocked, `${at} > blocked`, scope); + } +} + +function validateScene(ctx: ValidationCtx, scene: GameSceneConfig): void { + const base = `scene:${scene.id}`; + const scope = { sceneId: scene.id }; + checkDuplicates(ctx, "interaccion", base, (scene.interactions ?? []).map((i) => i.id)); + for (const i of scene.interactions ?? []) { + for (const id of i.acceptsItemIds ?? []) { + refItem(ctx, id, `${base} > interaction:${i.id} > acceptsItemIds`, "la interaccion"); + } + } + const hotspots = scene.hotspots ?? []; + const npcs = scene.npcs ?? []; + // Los NPC se proyectan a hotspots: comparten espacio de ids. + checkDuplicates(ctx, "hotspot/NPC", base, [...hotspots.map((h) => h.id), ...npcs.map((n) => n.id)]); + + for (const h of hotspots) { + const at = `${base} > hotspot:${h.id}`; + refDialogKey(ctx, h.label, `${at} > label`); + validateInteractive(ctx, at, h, scope); + } + for (const n of npcs) { + const at = `${base} > npc:${n.id}`; + refDialogKey(ctx, n.name, `${at} > name`); + if (n.dialogueId !== undefined && !ctx.dialogueIds.has(n.dialogueId)) { + report(ctx, "error", "unknown-dialogue", `${at} > dialogueId`, `dialogueId referencia un dialogo inexistente: "${n.dialogueId}"`); + } + validateInteractive(ctx, at, n, scope); + } + + (scene.initialItems ?? []).forEach((entry, i) => { + const at = `${base} > initialItems[${i}]`; + const item = entry?.item; + scanCondition(ctx, entry?.when, `${at}.when`, scope); + if (!item) return; + refItem(ctx, item.itemId, `${at}.item`, "initialItems"); + if (typeof item.itemId === "string") ctx.provided.add(item.itemId); + refScene(ctx, item.sceneId, `${at}.item`, "initialItems"); + // `interactionId` de un item colocado es una etiqueta libre (p. ej. la de su recogida): no se valida. + }); + scanBranches(ctx, scene.onEnter, `${base} > onEnter`, scope); + validateTransitions(ctx, scene, base); +} + +function validateItem(ctx: ValidationCtx, item: GameItemConfig): void { + for (const [other, branches] of Object.entries(item.combine ?? {})) { + const at = `item:${item.id} > combine.${other}`; + refItem(ctx, other, at, "combine"); + scanBranches(ctx, branches, at); + } +} + +function reachableScenes(ctx: ValidationCtx, first: string): Set { + const seen = new Set(); + const stack = [first]; + while (stack.length) { + const id = stack.pop()!; + if (seen.has(id)) continue; + seen.add(id); + const next = [...(ctx.sceneEdges.get(id) ?? []), ...(ctx.sceneEdges.get(ANY_SCENE) ?? [])]; + for (const n of next) if (ctx.sceneIds.has(n)) stack.push(n); + } + return seen; +} + +function globalWarnings(ctx: ValidationCtx): void { + const { scenes, items } = ctx.content; + if (scenes.length > 1) { + const seen = reachableScenes(ctx, scenes[0].id); + for (const s of scenes) { + if (!seen.has(s.id)) { + report(ctx, "warning", "unreachable-scene", `scene:${s.id}`, `escena inalcanzable desde la inicial ("${scenes[0].id}")`); + } + } + } + for (const item of items) { + if (!ctx.provided.has(item.id)) { + report(ctx, "warning", "unused-item", `item:${item.id}`, "ningun guion lo da ni lo coloca (ni giveItem, ni placeItem, ni initialItems)"); + } + } + for (const [flag, where] of ctx.flagsRead) { + if (!ctx.flagsWritten.has(flag)) { + report(ctx, "warning", "flag-never-set", where, `el flag "${flag}" se lee pero ningun guion lo escribe`); + } + } + for (const [flag, where] of ctx.flagsWritten) { + if (!ctx.flagsRead.has(flag)) { + report(ctx, "warning", "flag-never-read", where, `el flag "${flag}" se escribe pero nada lo lee`); + } + } +} + +/** + * Valida el contenido declarativo: referencias rotas, duplicados y huecos del grafo. + * Pura: solo mira `content`, no stores ni registros. La escena inicial es `scenes[0]`. + * Los avisos (flags, escenas, items) pueden ser intencionados si los gestiona el host. + */ +export function validateContent(content: GameContent): ContentIssue[] { + const scenes = content.scenes ?? []; + const items = content.items ?? []; + const dialogues = content.dialogues ?? []; + const ctx: ValidationCtx = { + issues: [], + content: { ...content, scenes, items }, + sceneIds: new Set(scenes.map((s) => s.id)), + itemIds: new Set(items.map((i) => i.id)), + dialogueIds: new Set(dialogues.map((d) => d.id)), + interactions: new Map(scenes.map((s) => [s.id, new Set((s.interactions ?? []).map((i) => i.id))])), + provided: new Set(), + flagsRead: new Map(), + flagsWritten: new Map(), + sceneEdges: new Map(), + }; + checkDuplicates(ctx, "escena", "scenes", scenes.map((s) => s.id)); + checkDuplicates(ctx, "item", "items", items.map((i) => i.id)); + checkDuplicates(ctx, "dialogo", "dialogues", dialogues.map((d) => d.id)); + + for (const scene of scenes) validateScene(ctx, scene); + for (const dlg of dialogues) validateDialogue(ctx, dlg); + for (const item of items) validateItem(ctx, item); + globalWarnings(ctx); + return ctx.issues; +} diff --git a/packages/engine-core/src/game/narrative/validateDialogues.ts b/packages/engine-core/src/game/narrative/validateDialogues.ts new file mode 100644 index 0000000..729bafb --- /dev/null +++ b/packages/engine-core/src/game/narrative/validateDialogues.ts @@ -0,0 +1,60 @@ +import type { DialogueDefinition } from "./dialogueTypes"; +import { checkDuplicates, report, type ValidationCtx } from "./validateTypes"; +import { refDialogKey, scanCondition, scanScript } from "./validateScan"; + +/** Comprueba un arbol de dialogo: nodos, saltos, `start`, salidas y alcanzabilidad. */ +export function validateDialogue(ctx: ValidationCtx, def: DialogueDefinition): void { + const base = `dialogue:${def.id}`; + const nodes = Array.isArray(def.nodes) ? def.nodes : []; + checkDuplicates(ctx, "nodo de dialogo", base, nodes.map((n) => n?.id)); + const ids = new Set(nodes.map((n) => n?.id)); + + const jump = (target: unknown, where: string): void => { + if (typeof target === "string" && !ids.has(target)) { + report(ctx, "error", "unknown-dialogue-node", where, `salta a un nodo inexistente: "${target}"`); + } + }; + + if (!ids.has(def.start)) { + report(ctx, "error", "unknown-dialogue-start", `${base} > start`, `el nodo inicial no existe: "${String(def.start)}"`); + } + + const edges = new Map(); + for (const node of nodes) { + if (!node) continue; + const at = `${base} > node:${node.id}`; + const out: string[] = []; + refDialogKey(ctx, node.line, `${at} > line`); + scanScript(ctx, node.do, `${at} > do`); + jump(node.next, `${at} > next`); + if (typeof node.next === "string") out.push(node.next); + const choices = Array.isArray(node.choices) ? node.choices : []; + choices.forEach((choice, i) => { + const cat = `${at} > choices[${i}]`; + refDialogKey(ctx, choice?.text, `${cat}.text`); + scanCondition(ctx, choice?.when, `${cat}.when`); + scanScript(ctx, choice?.do, `${cat}.do`); + jump(choice?.next, `${cat}.next`); + if (typeof choice?.next === "string") out.push(choice.next); + }); + // Un nodo vacio no dice, ni hace, ni ofrece, ni enlaza: casi seguro un olvido. + if (node.line === undefined && !node.do?.length && !choices.length && node.next === undefined) { + report(ctx, "error", "dialogue-dead-end", at, "nodo sin linea, efectos, opciones ni salida (no es un final intencionado)"); + } + edges.set(node.id, out); + } + + const reached = new Set(); + const stack = ids.has(def.start) ? [def.start] : []; + while (stack.length) { + const id = stack.pop()!; + if (reached.has(id)) continue; + reached.add(id); + for (const next of edges.get(id) ?? []) if (ids.has(next)) stack.push(next); + } + for (const node of nodes) { + if (node && !reached.has(node.id)) { + report(ctx, "warning", "unreachable-dialogue-node", `${base} > node:${node.id}`, "nodo inalcanzable desde el inicial"); + } + } +} diff --git a/packages/engine-core/src/game/narrative/validateScan.ts b/packages/engine-core/src/game/narrative/validateScan.ts new file mode 100644 index 0000000..bd8a862 --- /dev/null +++ b/packages/engine-core/src/game/narrative/validateScan.ts @@ -0,0 +1,155 @@ +import { report, type ValidationCtx } from "./validateTypes"; +import { walkBranches, walkCondition, walkScript, type WalkVisitor } from "./validateWalkers"; + +/** Escena donde vive el guion (si se conoce): resuelve interacciones y aristas del grafo. */ +export interface ScanScope { + sceneId?: string; +} + +const str = (x: unknown): x is string => typeof x === "string"; + +export function refItem(ctx: ValidationCtx, id: unknown, where: string, what: string): void { + if (str(id) && !ctx.itemIds.has(id)) { + report(ctx, "error", "unknown-item", where, `${what} referencia un item inexistente: "${id}"`); + } +} + +export function refScene(ctx: ValidationCtx, id: unknown, where: string, what: string): void { + if (str(id) && !ctx.sceneIds.has(id)) { + report(ctx, "error", "unknown-scene", where, `${what} referencia una escena inexistente: "${id}"`); + } +} + +export function refDialogue(ctx: ValidationCtx, id: unknown, where: string, what: string): void { + if (str(id) && !ctx.dialogueIds.has(id)) { + report(ctx, "error", "unknown-dialogue", where, `${what} referencia un dialogo inexistente: "${id}"`); + } +} + +/** `sceneId` indefinido = cualquier escena. */ +export function refInteraction( + ctx: ValidationCtx, + sceneId: string | undefined, + id: unknown, + where: string, + what: string, +): void { + if (!str(id)) return; + let found = false; + if (sceneId !== undefined && ctx.interactions.has(sceneId)) { + found = ctx.interactions.get(sceneId)!.has(id); + } else if (sceneId === undefined) { + found = [...ctx.interactions.values()].some((s) => s.has(id)); + } else return; // escena desconocida: ya se avisa como unknown-scene + if (!found) { + const place = sceneId !== undefined ? ` en la escena "${sceneId}"` : ""; + report(ctx, "error", "unknown-interaction", where, `${what} referencia una interaccion inexistente${place}: "${id}"`); + } +} + +export function refDialogKey(ctx: ValidationCtx, key: unknown, where: string): void { + const known = ctx.content.dialogKeys; + if (known && str(key) && !known.has(key)) { + report(ctx, "warning", "unknown-dialog-key", where, `clave de dialogo desconocida: "${key}"`); + } +} + +export const ANY_SCENE = "*"; + +export function addEdge(ctx: ValidationCtx, scope: ScanScope, target: unknown): void { + if (!str(target)) return; + // Sin escena (dialogos, combine): la arista cuenta desde cualquier escena ("*"). + const from = scope.sceneId ?? ANY_SCENE; + const set = ctx.sceneEdges.get(from) ?? new Set(); + set.add(target); + ctx.sceneEdges.set(from, set); +} + +export function noteFlag(map: Map, name: unknown, where: string): void { + if (str(name) && !map.has(name)) map.set(name, where); +} + +function placedChecks(ctx: ValidationCtx, scope: ScanScope, placed: unknown, where: string): void { + const p = (placed ?? {}) as Record; + refItem(ctx, p.itemId, where, "placeItem"); + if (str(p.itemId)) ctx.provided.add(p.itemId); + refScene(ctx, p.sceneId, where, "placeItem"); +} + +function makeVisitor(ctx: ValidationCtx, scope: ScanScope): WalkVisitor { + return { + action(kind, a, where) { + const at = `${where}.${kind}`; + switch (kind) { + case "say": + refDialogKey(ctx, a.say, at); + break; + case "setFlag": + noteFlag(ctx.flagsWritten, a.setFlag, at); + break; + case "giveItem": + refItem(ctx, a.giveItem, at, "giveItem"); + if (str(a.giveItem)) ctx.provided.add(a.giveItem); + break; + case "removeItem": + refItem(ctx, a.removeItem, at, "removeItem"); + break; + case "placeItem": + placedChecks(ctx, scope, a.placeItem, at); + break; + case "changeScene": + refScene(ctx, a.changeScene, at, "changeScene"); + addEdge(ctx, scope, a.changeScene); + break; + case "startDialogue": + refDialogue(ctx, a.startDialogue, at, "startDialogue"); + break; + case "call": + if (ctx.content.handlers && str(a.call) && !ctx.content.handlers.has(a.call)) { + report(ctx, "warning", "unknown-handler", at, `call a un manejador no declarado: "${a.call}"`); + } + break; + } + }, + condition(kind, c, where) { + const at = `${where}.${kind}`; + switch (kind) { + case "flag": + noteFlag(ctx.flagsRead, c.flag, at); + break; + case "hasItem": + refItem(ctx, c.hasItem, at, "hasItem"); + break; + case "itemPlaced": + refItem(ctx, c.itemPlaced, at, "itemPlaced"); + refScene(ctx, c.inScene, at, "itemPlaced.inScene"); + refInteraction(ctx, str(c.inScene) ? c.inScene : undefined, c.at, at, "itemPlaced.at"); + break; + case "inScene": + refScene(ctx, c.inScene, at, "inScene"); + break; + case "visited": + refScene(ctx, c.visited, at, "visited"); + break; + } + }, + unknown(what, node, where) { + report(ctx, "error", `unknown-${what}`, where, `${what === "action" ? "accion" : what === "branch" ? "rama" : "condicion"} con forma desconocida: ${safeJson(node)}`); + }, + }; +} + +function safeJson(x: unknown): string { + try { + return JSON.stringify(x) ?? String(x); + } catch { + return String(x); + } +} + +export const scanScript = (ctx: ValidationCtx, script: unknown, where: string, scope: ScanScope = {}) => + walkScript(script, where, makeVisitor(ctx, scope)); +export const scanBranches = (ctx: ValidationCtx, branches: unknown, where: string, scope: ScanScope = {}) => + walkBranches(branches, where, makeVisitor(ctx, scope)); +export const scanCondition = (ctx: ValidationCtx, cond: unknown, where: string, scope: ScanScope = {}) => + walkCondition(cond, where, makeVisitor(ctx, scope)); diff --git a/packages/engine-core/src/game/narrative/validateTypes.ts b/packages/engine-core/src/game/narrative/validateTypes.ts new file mode 100644 index 0000000..748a47e --- /dev/null +++ b/packages/engine-core/src/game/narrative/validateTypes.ts @@ -0,0 +1,70 @@ +import type { DialogueDefinition } from "./dialogueTypes"; +import type { GameItemConfig, GameSceneConfig } from "../runtime/types"; + +/** Una incidencia del contenido: un error rompe el juego, un aviso huele mal. */ +export interface ContentIssue { + severity: "error" | "warning"; + /** Codigo estable, p. ej. "unknown-item", "unknown-scene", "unknown-dialogue-node". */ + code: string; + /** Ruta legible: "scene:town > hotspot:well > verbs.use[0].do[2]". */ + where: string; + message: string; +} + +/** Todo el contenido declarativo de un juego, tal como se pasa a `createGameRuntime`. */ +export interface GameContent { + scenes: GameSceneConfig[]; + items: GameItemConfig[]; + dialogues?: DialogueDefinition[]; + /** Claves de dialogo conocidas; si se pasa, se validan las claves de `say`, `label`, `line` y `text`. */ + dialogKeys?: ReadonlySet; + /** Nombres de manejadores `call` que el host registra. */ + handlers?: ReadonlySet; +} + +/** Estado compartido de un recorrido de validacion (privado del validador). */ +export interface ValidationCtx { + issues: ContentIssue[]; + content: GameContent; + sceneIds: Set; + itemIds: Set; + dialogueIds: Set; + /** Ids de interaccion por escena. */ + interactions: Map>; + /** Items que algo da o coloca. */ + provided: Set; + /** Flag -> primer sitio donde se lee / se escribe. */ + flagsRead: Map; + flagsWritten: Map; + /** Escena -> escenas a las que se puede ir desde ella. */ + sceneEdges: Map>; +} + +export function report( + ctx: ValidationCtx, + severity: ContentIssue["severity"], + code: string, + where: string, + message: string, +): void { + ctx.issues.push({ severity, code, where, message }); +} + +/** Marca duplicados de `ids` (en orden) bajo `where`. */ +export function checkDuplicates( + ctx: ValidationCtx, + kind: string, + where: string, + ids: ReadonlyArray, +): void { + const seen = new Set(); + const dup = new Set(); + for (const id of ids) { + if (typeof id !== "string") continue; + if (seen.has(id)) dup.add(id); + seen.add(id); + } + for (const id of dup) { + report(ctx, "error", "duplicate-id", where, `${kind} duplicado: "${id}"`); + } +} diff --git a/packages/engine-core/src/game/narrative/validateWalkers.ts b/packages/engine-core/src/game/narrative/validateWalkers.ts new file mode 100644 index 0000000..9edf05f --- /dev/null +++ b/packages/engine-core/src/game/narrative/validateWalkers.ts @@ -0,0 +1,88 @@ +/** + * Recorrido generico de guiones y condiciones para el validador. Es el UNICO sitio + * que conoce la forma de las acciones y condiciones: una accion o condicion nueva + * solo hay que ensenarsela aqui. Puro: no lee stores ni registros. + */ + +export const ACTION_KINDS = [ + "say", + "setFlag", + "giveItem", + "removeItem", + "placeItem", + "removePlacedItem", + "changeScene", + "walkTo", + "wait", + "playSfx", + "startDialogue", + "lockInput", + "emit", + "call", +] as const; + +/** En el orden en que `evaluateCondition` las reconoce. */ +export const CONDITION_KINDS = [ + "flag", + "hasItem", + "itemPlaced", + "inScene", + "visited", + "all", + "any", + "not", +] as const; + +type Node = Record; + +export interface WalkVisitor { + /** Una accion reconocida (`kind` es su clave distintiva). */ + action?(kind: string, action: Node, where: string): void; + /** Una condicion reconocida; `all`/`any`/`not` tambien se avisan, y luego se recorren. */ + condition?(kind: string, condition: Node, where: string): void; + /** Un elemento que no es una accion/condicion conocida. */ + unknown?(what: "action" | "condition" | "branch", node: unknown, where: string): void; +} + +const isObj = (x: unknown): x is Node => x !== null && typeof x === "object" && !Array.isArray(x); + +export function detectKind(node: Node, kinds: readonly string[]): string | undefined { + return kinds.find((k) => k in node); +} + +export function walkCondition(cond: unknown, where: string, v: WalkVisitor): void { + if (cond === undefined) return; + const c = isObj(cond) ? cond : null; + const kind = c ? detectKind(c, CONDITION_KINDS) : undefined; + if (!c || !kind) return void v.unknown?.("condition", cond, where); + v.condition?.(kind, c, where); + if ((kind === "all" || kind === "any") && Array.isArray(c[kind])) { + (c[kind] as unknown[]).forEach((x, i) => walkCondition(x, `${where}.${kind}[${i}]`, v)); + } else if (kind === "not") { + walkCondition(c.not, `${where}.not`, v); + } +} + +export function walkScript(script: unknown, where: string, v: WalkVisitor): void { + if (script === undefined) return; + if (!Array.isArray(script)) return void v.unknown?.("action", script, where); + script.forEach((action, i) => { + const at = `${where}[${i}]`; + const a = isObj(action) ? action : null; + const kind = a ? detectKind(a, ACTION_KINDS) : undefined; + if (!a || !kind) return void v.unknown?.("action", action, at); + v.action?.(kind, a, at); + }); +} + +/** `where` apunta a la lista de ramas (p. ej. `verbs.use`); cada rama anade `[i].when` / `[i].do`. */ +export function walkBranches(branches: unknown, where: string, v: WalkVisitor): void { + if (branches === undefined) return; + if (!Array.isArray(branches)) return void v.unknown?.("branch", branches, where); + branches.forEach((b, i) => { + const at = `${where}[${i}]`; + if (!isObj(b)) return void v.unknown?.("branch", b, at); + walkCondition(b.when, `${at}.when`, v); + walkScript(b.do, `${at}.do`, v); + }); +} diff --git a/packages/engine-core/src/game/runtime/createGameRuntime.ts b/packages/engine-core/src/game/runtime/createGameRuntime.ts new file mode 100644 index 0000000..e4d6435 --- /dev/null +++ b/packages/engine-core/src/game/runtime/createGameRuntime.ts @@ -0,0 +1,205 @@ +import { EventBus } from "../../events"; +import { CommandHandler } from "../commands/CommandHandler"; +import { setSceneStoreEmitter, useSceneStore, useWorldStateStore } from "../state"; +import type { GameEvent, GameEventType, GameEventHandler } from "../events/types"; +import type { + GameRuntime, + GameRuntimeConfig, + GameState, + GameActions, + SceneStoreSnapshot, +} from "./types"; +import { + registerScene, + registerItem, + registerRule, + registerDialogue, + sceneRegistry, + itemRegistry, + ruleRegistry, + dialogueRegistry, + toRuntimeScene, +} from "./registry"; +import { registerRuntimeExecutors } from "./executors"; +import { createSequencer } from "../narrative/sequencer"; +import { registerCombineCommands } from "../narrative/combine"; +import { registerHotspotCommands } from "../narrative/hotspots"; +import { registerDialogueCommands } from "../narrative/dialogue"; +import { registerInventoryCommands } from "./inventoryExecutors"; +import { systemClock } from "../../ports/clock"; +import { validateContent, type ContentIssue } from "../narrative/validateContent"; + +const isDevelopment = (): boolean => + typeof process !== "undefined" && process.env?.NODE_ENV === "development"; + +const formatIssue = (i: ContentIssue): string => + ` [${i.severity}] ${i.code} @ ${i.where}: ${i.message}`; + +/** Valida el contenido de `config` segun `config.validate` (ver `GameRuntimeConfig.validate`). */ +function runContentValidation(config: GameRuntimeConfig): void { + const mode = config.validate ?? (isDevelopment() ? true : false); + if (mode === false) return; + if (!config.scenes?.length && !config.items?.length && !config.dialogues?.length) return; + const issues = validateContent({ + scenes: config.scenes ?? [], + items: config.items ?? [], + ...(config.dialogues ? { dialogues: config.dialogues } : {}), + ...(config.dialogKeys ? { dialogKeys: config.dialogKeys } : {}), + ...(config.handlerNames ? { handlers: config.handlerNames } : {}), + }); + if (issues.length === 0) return; + const errors = issues.filter((i) => i.severity === "error"); + const text = `[validateContent] ${errors.length} error(es), ${issues.length - errors.length} aviso(s):\n${issues.map(formatIssue).join("\n")}`; + if (mode === "throw" && errors.length > 0) throw new Error(text); + console.warn(text); +} + +/** + * Cablea el estado de mundo con el bus (los stores no se conocen entre sí ni al bus): + * - suscripción al store de mundo -> emite `state:flagChanged` por diff de flags + * (cubre comandos y llamadas directas a `getWorldState().setFlag`). + * - `scene:changed` del bus -> `markSceneVisited` (incluida la escena ya activa). + * Devuelve la función que suelta ambas suscripciones. + */ +function wireWorldState(bus: EventBus): () => void { + const unsubStore = useWorldStateStore.subscribe((state, prev) => { + if (state.flags === prev.flags) return; + const names = new Set([...Object.keys(prev.flags), ...Object.keys(state.flags)]); + for (const name of names) { + const before = prev.flags[name]; + const after = state.flags[name]; + if (before === after) continue; + bus.emit("state:flagChanged", { + type: "state:flagChanged", + name, + ...(after !== undefined ? { value: after } : {}), + ...(before !== undefined ? { previous: before } : {}), + }); + } + }); + const unsubScene = bus.on<{ sceneId: string }>("scene:changed", (e) => { + useWorldStateStore.getState().markSceneVisited(e.sceneId); + }); + const activeSceneId = useSceneStore.getState().sceneId; + if (activeSceneId) useWorldStateStore.getState().markSceneVisited(activeSceneId); + return () => { + unsubStore(); + unsubScene(); + }; +} + +/** Singleton del runtime activo. Accesible vía getGameRuntime(). */ +let runtimeHandle: GameRuntime | null = null; + +/** + * Inicializa el runtime con las escenas, ítems y reglas proporcionadas. + * Crea EventBus y CommandHandler, cablea store → bus y devuelve el handle + * (`executeCommand`, `on`, `emit`, `dispose`), guardado como singleton. + */ +export function createGameRuntime(config: GameRuntimeConfig = {}): GameRuntime { + runContentValidation(config); + for (const scene of config.scenes ?? []) registerScene(scene); + for (const item of config.items ?? []) registerItem(item); + for (const rule of config.rules ?? []) registerRule(rule); + for (const dlg of config.dialogues ?? []) registerDialogue(dlg); + + const bus = new EventBus(); + const commands = new CommandHandler(); + + setSceneStoreEmitter((event) => bus.emit(event.type, event)); + registerRuntimeExecutors(commands, bus, config); + const unwireWorldState = wireWorldState(bus); + + // Secuenciador narrativo: despacha comandos por el handle y espera eventos del bus. + const sequencer = createSequencer({ + execute: (cmd) => runtime.executeCommand(cmd), + emit: (event) => bus.emit(event.type, event), + on: (type, handler) => bus.on(type, handler as (data: unknown) => void), + clock: config.clock ?? systemClock, + instantWalk: config.instantWalk ?? false, + getItem: (id) => itemRegistry.get(id), + }); + commands.register("script:run", (cmd) => { + sequencer.run(cmd.script, { interrupt: cmd.interrupt }); + }); + commands.register("script:cancelAll", () => sequencer.cancelAll()); + const emitEvent = (event: GameEvent) => bus.emit(event.type, event); + registerHotspotCommands(commands, { emit: emitEvent, runScript: (s) => sequencer.run(s) }); + const dialogueEngine = registerDialogueCommands(commands, { + emit: emitEvent, + runScript: (s) => sequencer.run(s), + registerExecutor: (key, executor) => sequencer.registerExecutor(key, executor), + }); + registerCombineCommands(commands, { + emit: emitEvent, + runScript: (s) => sequencer.run(s), + getItem: (id) => itemRegistry.get(id), + }); + registerInventoryCommands(commands, emitEvent); + + const runtime: GameRuntime = { + getScenes: () => Object.fromEntries(sceneRegistry), + getItems: () => Object.fromEntries(itemRegistry), + getRules: () => Object.fromEntries(ruleRegistry), + getDialogues: () => Object.fromEntries(dialogueRegistry), + executeCommand: (cmd) => commands.execute(cmd), + on: (type: T, handler: GameEventHandler) => + bus.on(type, handler as (data: unknown) => void), + emit: (event: GameEvent) => bus.emit(event.type, event), + runScript: (script, opts) => sequencer.run(script, opts), + registerHandler: (name, fn) => sequencer.registerHandler(name, fn), + dispose: () => { + dialogueEngine.dispose(); + sequencer.dispose(); + unwireWorldState(); + bus.clear(); + commands.clear(); + setSceneStoreEmitter(null); + if (runtimeHandle === runtime) runtimeHandle = null; + }, + }; + + runtimeHandle = runtime; + return runtime; +} + +/** Handle del runtime activo, o `null` si no hay o tras `dispose()`. */ +export function getGameRuntime(): GameRuntime | null { + return runtimeHandle; +} + +/** Proyección pública del estado del store (reutilizable por hooks). */ +export function toGameState(state: SceneStoreSnapshot): GameState { + return { + sceneId: state.sceneId, + scene: state.scene, + playerPosition: state.playerPosition, + respawnSignal: state.respawnSignal, + }; +} + +/** Construye las acciones públicas a partir de un snapshot del store. */ +export function toGameActions(state: SceneStoreSnapshot): GameActions { + return { + setScene: (id: string) => { + const sceneConfig = sceneRegistry.get(id); + if (!sceneConfig) { + console.warn(`Scene not registered: ${id}`); + return; + } + state.setScene(id, toRuntimeScene(sceneConfig)); + }, + setPlayerPosition: state.setPlayerPosition, + requestRespawn: state.requestRespawn, + }; +} + +/** Lee snapshot del estado público sin hooks. */ +export function getGameState(): GameState { + return toGameState(useSceneStore.getState()); +} + +/** Lee acciones públicas sin hooks. */ +export function getGameActions(): GameActions { + return toGameActions(useSceneStore.getState()); +} diff --git a/packages/engine-core/src/game/runtime/executors.ts b/packages/engine-core/src/game/runtime/executors.ts new file mode 100644 index 0000000..25dc04c --- /dev/null +++ b/packages/engine-core/src/game/runtime/executors.ts @@ -0,0 +1,212 @@ +import type { EventBus } from "../../events"; +import type { CommandHandler } from "../commands/CommandHandler"; +import { findPath } from "../logic"; +import { + useSceneStore, + useDialogStore, + useInventoryUiStore, + useWorldStateStore, + applySnapshot, + clearSave, + loadGame, + resetGameState, + saveGame, +} from "../state"; +import type { GameVec3 } from "../types"; +import type { GameRuntimeConfig } from "./types"; +import { ruleRegistry, sceneRegistry, toRuntimeScene } from "./registry"; + +/** Registra en `commands` todos los executors del runtime. */ +export function registerRuntimeExecutors( + commands: CommandHandler, + bus: EventBus, + config: GameRuntimeConfig, +): void { + commands.register("scene:set", (cmd) => { + const sceneConfig = sceneRegistry.get(cmd.sceneId); + if (!sceneConfig) { + console.warn(`[runtime] scene:set — scene not registered: ${cmd.sceneId}`); + return; + } + useSceneStore + .getState() + .setScene(sceneConfig.id, toRuntimeScene(sceneConfig), cmd.spawnPosition); + }); + + commands.register("scene:respawn", () => { + useSceneStore.getState().requestRespawn(); + }); + + commands.register("player:move", (cmd) => { + useSceneStore.getState().setPlayerPosition(cmd.position); + }); + + commands.register("player:walkTo", (cmd) => { + const state = useSceneStore.getState(); + const from: GameVec3 = [ + state.playerPosition[0], + state.playerPosition[1], + state.playerPosition[2], + ]; + const pathResult = findPath({ + start: { x: from[0], z: from[2] }, + goal: { x: cmd.position[0], z: cmd.position[2] }, + bounds: { + minX: state.scene.ground.minX, + maxX: state.scene.ground.maxX, + minZ: state.scene.ground.minZ, + maxZ: state.scene.ground.maxZ, + }, + walls: state.scene.walls, + interactions: state.scene.interactions, + }); + + if (pathResult && pathResult.length > 0) { + // Siempre incluye el punto de partida para garantizar ≥2 puntos. + const pathPoints: GameVec3[] = [ + from, + ...pathResult.map((p) => [p.x, state.scene.ground.y, p.z] as GameVec3), + ]; + state.setPlayerWalkingState({ + targetPosition: cmd.position, + pathPoints, + progress: 0, + isActive: true, + }); + bus.emit("player:walkStarted", { + type: "player:walkStarted", + targetPosition: cmd.position, + }); + } else { + bus.emit("player:walkAborted", { + type: "player:walkAborted", + reason: "unreachable", + }); + } + }); + + commands.register("inventory:toggle", () => { + if (config.inventoryAdapter) config.inventoryAdapter.toggle(); + else useInventoryUiStore.getState().toggle(); + }); + + // Clave del diálogo activo para que dialog:dismiss la incluya en el evento. + let activeDialogKey: string | undefined; + + commands.register("dialog:trigger", (cmd) => { + const phrases = ruleRegistry.get(cmd.dialogKey)?.phrases ?? []; + const text = + phrases.length > 0 + ? phrases[Math.floor(Math.random() * phrases.length)]! + : cmd.dialogKey; + activeDialogKey = cmd.dialogKey; + const speaker = cmd.speaker; + if (config.dialogAdapter) { + if (speaker !== undefined) config.dialogAdapter.show(text, cmd.dialogKey, speaker); + else config.dialogAdapter.show(text, cmd.dialogKey); + } else if (speaker !== undefined) useDialogStore.getState().show(text, cmd.dialogKey, speaker); + else useDialogStore.getState().show(text, cmd.dialogKey); + bus.emit("dialog:triggered", { + type: "dialog:triggered", + text, + dialogKey: cmd.dialogKey, + source: "command", + ...(speaker !== undefined ? { speaker } : {}), + }); + }); + + commands.register("dialog:dismiss", () => { + const key = activeDialogKey; + activeDialogKey = undefined; + if (config.dialogAdapter) config.dialogAdapter.hide(); + else useDialogStore.getState().dismiss(); + bus.emit("dialog:dismissed", { type: "dialog:dismissed", dialogKey: key }); + }); + + commands.register("transition:activate", (cmd) => { + const state = useSceneStore.getState(); + const transition = state.scene.transitions?.find((t) => t.id === cmd.transitionId); + if (!transition) { + console.warn(`[runtime] transition:activate — unknown transition: ${cmd.transitionId}`); + return; + } + const fromSceneId = state.sceneId; + bus.emit("transition:started", { + type: "transition:started", + transitionId: cmd.transitionId, + }); + const sceneConfig = sceneRegistry.get(transition.targetSceneId); + if (!sceneConfig) { + console.warn( + `[runtime] transition:activate — target scene not registered: ${transition.targetSceneId}`, + ); + return; + } + useSceneStore + .getState() + .setScene(sceneConfig.id, toRuntimeScene(sceneConfig), transition.spawnPosition); + bus.emit("transition:completed", { + type: "transition:completed", + fromSceneId, + toSceneId: transition.targetSceneId, + }); + }); + + commands.register("transition:cancel", (cmd) => { + useSceneStore.getState().setTransitionItemOccupying(cmd.transitionId, undefined); + }); + + commands.register("player:stop", () => { + const state = useSceneStore.getState(); + if (state.playerWalkingState?.isActive) { + state.setPlayerWalkingState(null); + bus.emit("player:walkAborted", { + type: "player:walkAborted", + reason: "user-input", + }); + } + }); + + commands.register("state:setFlag", (cmd) => { + useWorldStateStore.getState().setFlag(cmd.name, cmd.value); + }); + + commands.register("state:clearFlag", (cmd) => { + useWorldStateStore.getState().clearFlag(cmd.name); + }); + + commands.register("game:save", (cmd) => { + if (!config.storage) { + console.warn("[runtime] game:save — no storage configured"); + return; + } + saveGame(config.storage, { key: config.saveKey, extra: cmd.extra }); + bus.emit("game:saved", { type: "game:saved" }); + }); + + commands.register("game:load", () => { + if (!config.storage) { + console.warn("[runtime] game:load — no storage configured"); + return; + } + const snapshot = loadGame(config.storage, { key: config.saveKey }); + if (!snapshot) { + bus.emit("game:loaded", { type: "game:loaded", found: false }); + return; + } + const applied = applySnapshot(snapshot); + bus.emit("game:loaded", { + type: "game:loaded", + found: true, + applied, + ...(snapshot.extra ? { extra: snapshot.extra } : {}), + }); + }); + + commands.register("game:reset", () => { + resetGameState(); + if (config.storage) clearSave(config.storage, { key: config.saveKey }); + bus.emit("game:reset", { type: "game:reset" }); + }); + +} diff --git a/packages/engine-core/src/game/runtime/index.ts b/packages/engine-core/src/game/runtime/index.ts new file mode 100644 index 0000000..d827a06 --- /dev/null +++ b/packages/engine-core/src/game/runtime/index.ts @@ -0,0 +1,26 @@ +export type { + GameSceneConfig, + GameItemConfig, + GameItemRule, + GameItemDropOutcome, + GameRuleConfig, + GameRuntime, + GameRuntimeConfig, + GameRuntimeEvent, + GameRuntimeEventHandler, + GameState, + GameActions, + InventoryUIAdapter, + DialogUIAdapter, + ScriptHandler, +} from "./types"; +export { registerScene, registerItem, registerRule, registerDialogue, toRuntimeScene } from "./registry"; +export { + createGameRuntime, + getGameRuntime, + getGameState, + getGameActions, + toGameState, + toGameActions, +} from "./createGameRuntime"; +export { createInventoryRuleContext } from "./inventoryRuleContext"; diff --git a/packages/engine-core/src/game/runtime/inventoryExecutors.ts b/packages/engine-core/src/game/runtime/inventoryExecutors.ts new file mode 100644 index 0000000..5a2f92c --- /dev/null +++ b/packages/engine-core/src/game/runtime/inventoryExecutors.ts @@ -0,0 +1,92 @@ +import type { CommandHandler } from "../commands/CommandHandler"; +import type { GameEvent } from "../events/types"; +import { + addOneToInventory, + removeOneFromSlot, + resolveInventoryDropHitDecision, + resolvePickupPlacedItemDecision, +} from "../logic/rules/inventoryRules"; +import { getInventoryState } from "../state/inventoryStore"; +import { getPlacedItemsState } from "../state/placedItemsReactiveStore"; +import { getSceneState } from "../state/sceneStore"; +import { createInventoryRuleContext } from "./inventoryRuleContext"; +import { itemRegistry } from "./registry"; + +/** + * Comandos `inventory:pickup` e `inventory:drop` sobre los stores del core. + * + * Diferencia con el renderer: aqui solo cambian estado y se emiten eventos; NO se + * muestran dialogos (el renderer enseña las claves `hitDialogKey`, `pickup*DialogKey`...). + * Un guion que quiera texto lo declara con `say` (p. ej. via `hotspot:interact`). + */ +export function registerInventoryCommands( + commands: CommandHandler, + emit: (event: GameEvent) => void, +): void { + const ruleContext = createInventoryRuleContext(() => Object.fromEntries(itemRegistry)); + + commands.register("inventory:pickup", (cmd) => { + const sceneId = getSceneState().sceneId; + const placed = getPlacedItemsState().items.find((p) => + cmd.placedItemId !== undefined + ? p.id === cmd.placedItemId + : p.itemId === cmd.itemId && p.sceneId === sceneId, + ); + const fail = (reason: "not-found" | "blocked" | "full" | "unknown-item") => + emit({ type: "inventory:pickupFailed", itemId: cmd.itemId, reason }); + if (!placed) return fail("not-found"); + + const decision = resolvePickupPlacedItemDecision(ruleContext, { placedItem: placed }); + if (decision.kind === "ignore") return fail("unknown-item"); + if (decision.kind === "blocked") return fail("blocked"); + + const result = addOneToInventory(getInventoryState().slots, decision.stack); + if (!result.added) return fail("full"); + getInventoryState().setSlots(result.slots); + getPlacedItemsState().removeItem(decision.placedItemId); + emit({ type: "item:pickedUp", itemId: placed.itemId, quantity: 1 }); + }); + + commands.register("inventory:drop", (cmd) => { + if (cmd.hotspotId !== undefined) { + commands.execute({ + type: "hotspot:interact", + hotspotId: cmd.hotspotId, + verb: "useItem", + itemId: cmd.itemId, + }); + return; + } + const dropped = (outcome: "consume" | "place" | "return", interactionId?: string) => + emit({ + type: "item:dropped", + itemId: cmd.itemId, + outcome, + ...(interactionId !== undefined ? { interactionId } : {}), + }); + + const scene = getSceneState(); + const interaction = + cmd.interactionId !== undefined + ? scene.scene.interactions.find((i) => (i as { id?: string }).id === cmd.interactionId) + : undefined; + const stack = getInventoryState().slots[cmd.slotIndex]; + if (!interaction || !stack || stack.id !== cmd.itemId) return dropped("return", cmd.interactionId); + + const decision = resolveInventoryDropHitDecision(ruleContext, { + interaction, + payload: { stack, fromSlotIndex: cmd.slotIndex }, + now: Date.now(), + }); + if (decision.kind === "place") { + getInventoryState().setSlots(removeOneFromSlot(getInventoryState().slots, decision.fromSlotIndex)); + getPlacedItemsState().addItem({ ...decision.placedItem, sceneId: scene.sceneId }); + return dropped("place", cmd.interactionId); + } + if (decision.kind === "consume") { + getInventoryState().setSlots(removeOneFromSlot(getInventoryState().slots, decision.fromSlotIndex)); + return dropped("consume", cmd.interactionId); + } + return dropped("return", cmd.interactionId); + }); +} diff --git a/packages/engine-core/src/game/runtime/inventoryRuleContext.ts b/packages/engine-core/src/game/runtime/inventoryRuleContext.ts new file mode 100644 index 0000000..408aa7b --- /dev/null +++ b/packages/engine-core/src/game/runtime/inventoryRuleContext.ts @@ -0,0 +1,116 @@ +import type { InventoryRuleContext } from "../logic/rules/inventoryRules"; +import type { ItemDefinition, ItemInteractionRule } from "../types"; +import type { GameItemConfig, GameItemRule } from "./types"; + +type ItemsSource = + | Record + | (() => Record); + +const INTERACTION_OUTCOMES: ReadonlySet = new Set(["place", "consume", "return"]); + +function hasOwn(obj: object, key: string): boolean { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +/** + * Una regla de interaccion solo admite place/consume/return. `GameItemRule` + * es mas ancha (incluye outcomes de resultado como "rule-miss"), asi que se + * comprueba en tiempo de ejecucion y se estrecha el tipo sin `as any`. + */ +function toInteractionRule(rule: GameItemRule): ItemInteractionRule | null { + if (!INTERACTION_OUTCOMES.has(rule.outcome)) return null; + const outcome = rule.outcome as ItemInteractionRule["outcome"]; + return { ...rule, outcome }; +} + +/** + * Construye el `InventoryRuleContext` que consumen las reglas de inventario + * (`resolveInventoryDropHitDecision`, `resolvePickupPlacedItemDecision`, ...) + * a partir de un registro de items del runtime. + * + * `items` puede ser el registro o una funcion que lo devuelva; con funcion, el + * registro se lee en CADA uso (no al crear el contexto), de modo que items + * registrados despues o un runtime recreado se reflejan sin rehacer el contexto. + * + * Comportamiento ante reglas invalidas: una regla cuyo `outcome` no sea + * place/consume/return (p. ej. "rule-miss" o un valor desconocido) no es una + * regla de interaccion valida. Comportamiento seguro y sin efectos: + * - `resolveItemRule` devuelve `null` para esa interaccion (la regla elegida, + * sea la especifica o la `defaultRule`, no cae a otra). Las reglas de + * inventario lo traducen en "rule-miss": el item NO se consume ni se coloca + * y se muestra el dialogo de fallo por defecto. + * - `getItemDefinition` omite esas reglas de `interactionRules` y sustituye una + * `defaultRule` invalida por `{ outcome: "return" }` (conservando + * `missDialogKey`), para que la definicion devuelta cumpla `ItemDefinition`. + * - Se avisa una sola vez por regla con `console.warn`. + * + * Un item desconocido devuelve `null` en ambas funciones. + */ +export function createInventoryRuleContext(items: ItemsSource): InventoryRuleContext { + const read = (): Record => + typeof items === "function" ? items() : items; + const warned = new Set(); + + const warnInvalid = (itemId: string, where: string, rule: GameItemRule) => { + const key = `${itemId}|${where}`; + if (warned.has(key)) return; + warned.add(key); + console.warn( + `[inventory] item "${itemId}" ${where}: outcome "${String(rule.outcome)}" is not a valid interaction outcome (place|consume|return); rule ignored`, + ); + }; + + const getConfig = (itemId: string): GameItemConfig | null => { + const registry = read(); + return hasOwn(registry, itemId) ? (registry[itemId] ?? null) : null; + }; + + return { + getItemDefinition: (itemId: string): ItemDefinition | null => { + const config = getConfig(itemId); + if (!config) return null; + + const interactionRules: Record = {}; + for (const [interactionId, rule] of Object.entries(config.interactionRules)) { + const valid = toInteractionRule(rule); + if (valid) interactionRules[interactionId] = valid; + else warnInvalid(itemId, `interactionRules["${interactionId}"]`, rule); + } + + let defaultRule = toInteractionRule(config.defaultRule); + if (!defaultRule) { + warnInvalid(itemId, "defaultRule", config.defaultRule); + defaultRule = { outcome: "return", missDialogKey: config.defaultRule.missDialogKey }; + } + + return { + id: config.id, + name: config.name, + spriteUrl: config.spriteUrl, + descriptionDialogKey: config.descriptionDialogKey, + pickupSoundUrl: config.pickupSoundUrl, + dropSoundUrl: config.dropSoundUrl, + interactionRules, + defaultRule, + }; + }, + + resolveItemRule: (itemId: string, interactionId: string): ItemInteractionRule | null => { + const config = getConfig(itemId); + if (!config) return null; + + const isSpecific = hasOwn(config.interactionRules, interactionId); + const raw = isSpecific ? config.interactionRules[interactionId]! : config.defaultRule; + const valid = toInteractionRule(raw); + if (!valid) { + warnInvalid( + itemId, + isSpecific ? `interactionRules["${interactionId}"]` : "defaultRule", + raw, + ); + return null; + } + return valid; + }, + }; +} diff --git a/packages/engine-core/src/game/runtime/registry.ts b/packages/engine-core/src/game/runtime/registry.ts new file mode 100644 index 0000000..8303d20 --- /dev/null +++ b/packages/engine-core/src/game/runtime/registry.ts @@ -0,0 +1,61 @@ +import type { GameScene } from "../types"; +import { npcToHotspot } from "../narrative/npcs"; +import type { DialogueDefinition } from "../narrative/dialogueTypes"; +import type { + GameSceneConfig, + GameItemConfig, + GameRuleConfig, +} from "./types"; + +// Registros por defecto (singleton de módulo, como el contrato v1). +export const sceneRegistry = new Map(); +export const itemRegistry = new Map(); +export const ruleRegistry = new Map(); +export const dialogueRegistry = new Map(); + +/** Registra una escena. Idempotente: la misma id sobreescribe la anterior. */ +export function registerScene(config: GameSceneConfig): void { + sceneRegistry.set(config.id, config); +} + +/** Registra un ítem. Idempotente: el mismo id sobreescribe el anterior. */ +export function registerItem(config: GameItemConfig): void { + itemRegistry.set(config.id, config); +} + +/** Registra una regla de diálogo. Idempotente por key. */ +export function registerRule(config: GameRuleConfig): void { + ruleRegistry.set(config.key, config); +} + +/** Registra un arbol de dialogo. Idempotente: el mismo id sobreescribe el anterior. */ +export function registerDialogue(def: DialogueDefinition): void { + dialogueRegistry.set(def.id, def); +} + +/** + * Convierte la config pública en `GameScene` completa. + * Único punto de conversión: conserva `transitions` y `music`. + */ +export function toRuntimeScene(config: GameSceneConfig): GameScene { + // Un NPC es un hotspot con sprite: se anade a `hotspots` para que `hotspot:interact` lo vea. + // Sin NPCs, `hotspots` es la misma referencia de la config. + const hotspots = config.npcs?.length + ? [...(config.hotspots ?? []), ...config.npcs.map(npcToHotspot)] + : config.hotspots; + return { + id: config.id, + label: config.label, + background: config.background, + playerSpawn: config.playerSpawn, + ground: config.ground, + walls: config.walls, + interactions: config.interactions, + transitions: config.transitions, + music: config.music, + hotspots, + npcs: config.npcs, + initialItems: config.initialItems, + onEnter: config.onEnter, + }; +} diff --git a/packages/engine-core/src/game/runtime/types.ts b/packages/engine-core/src/game/runtime/types.ts new file mode 100644 index 0000000..f3103b0 --- /dev/null +++ b/packages/engine-core/src/game/runtime/types.ts @@ -0,0 +1,179 @@ +import type { + GameVec3, + GameSceneGround, + GameSceneWall, + GameSceneInteractionFull, + GameSceneTransition, + GameSceneHotspot, + GameSceneNpc, + SceneInitialItem, + SceneMusicConfig, +} from "../types"; +import type { + GameEvent, + GameEventType, + GameEventHandler, +} from "../events/types"; +import type { GameCommand } from "../commands/types"; +import type { Script, ScriptRun, Branch } from "../narrative/actions"; +import type { DialogueDefinition } from "../narrative/dialogueTypes"; +import type { ClockPort } from "../../ports/clock"; +import type { useSceneStore, KeyValueStoragePort } from "../state"; + +/** Configuración de escena registrable via API pública. */ +export type GameSceneConfig = { + id: string; + label: string; + background: string; + playerSpawn: GameVec3; + ground: GameSceneGround; + walls: GameSceneWall[]; + interactions: GameSceneInteractionFull[]; + /** Zonas de transición declarativas (se conservan al registrar la escena). */ + transitions?: GameSceneTransition[]; + music?: SceneMusicConfig; + /** Hotspots con verbos narrativos (se conservan al registrar la escena). */ + hotspots?: GameSceneHotspot[]; + /** NPCs (se conservan y se proyectan a hotspots al registrar la escena). */ + npcs?: GameSceneNpc[]; + /** Items iniciales declarativos (se conservan al registrar la escena). */ + initialItems?: SceneInitialItem[]; + /** Ramas de entrada declarativas (se conservan al registrar la escena). */ + onEnter?: Branch[]; +}; + +export type GameItemDropOutcome = + | "consume" + | "place" + | "return" + | "rule-miss" + | "unknown-item" + | "on-player" + | "pickup-blocked" + | "pickup-success"; + +export type GameItemRule = { + outcome: GameItemDropOutcome; + hitDialogKey?: string; + missDialogKey?: string; + placeCanPickup?: boolean; + placeHasCollision?: boolean; + placeCollisionHalfSize?: GameVec3; + pickupSuccessDialogKey?: string; + pickupBlockedDialogKey?: string; + dropSoundUrl?: string; +}; + +/** Configuración de ítem registrable via API pública. */ +export type GameItemConfig = { + id: string; + name: string; + spriteUrl: string; + descriptionDialogKey?: string; + pickupSoundUrl?: string; + dropSoundUrl?: string; + interactionRules: Record; + defaultRule: GameItemRule; + /** Ramas condicionales para combinar este ítem con otro por id. */ + combine?: Record; +}; + +/** Regla de texto/diálogo registrable via API pública. */ +export type GameRuleConfig = { + key: string; + phrases: string[]; +}; + +/** Eventos de runtime (legacy — mantenidos por backwards compat). */ +export type GameRuntimeEvent = + | { + type: "onMove"; + position: GameVec3; + action: "idle" | "north" | "south" | "west" | "east"; + } + | { type: "onCollide"; reason: "boundary" | "stuck"; position: GameVec3 } + | { type: "onDrop"; outcome: string; itemId: string; interactionId?: string } + | { type: "onDialog"; text: string; dialogKey?: string; source: string }; + +export type GameRuntimeEventHandler = (event: GameRuntimeEvent) => void; + +export type ScriptHandler = (args: unknown) => void | Promise; + +/** Handle de runtime devuelto por createGameRuntime. */ +export type GameRuntime = { + getScenes: () => Record; + getItems: () => Record; + getRules: () => Record; + getDialogues: () => Record; + /** + * Envía un comando al motor. Sync, fire-and-forget. + * Comandos sin executor registrado loguean warn y no hacen nada. + */ + executeCommand: (cmd: GameCommand) => void; + /** Suscribe a un tipo de evento. Devuelve unsubscribe. */ + on: (type: T, handler: GameEventHandler) => () => void; + /** Emite un evento al bus del runtime. */ + emit: (event: GameEvent) => void; + /** Ejecuta un guion narrativo (cola FIFO; `interrupt` cancela el actual y vacía la cola). */ + runScript: (script: Script, opts?: { interrupt?: boolean }) => ScriptRun; + /** Registra un manejador para la acción `call`. Devuelve la función que lo quita. */ + registerHandler: (name: string, fn: ScriptHandler) => () => void; + /** Libera el bus, los comandos y desactiva las emisiones del store. */ + dispose: () => void; +}; + +export type SceneStoreSnapshot = ReturnType; + +export type GameState = Pick< + SceneStoreSnapshot, + "sceneId" | "scene" | "playerPosition" | "respawnSignal" +>; + +export type GameActions = { + setScene: (sceneId: string) => void; + setPlayerPosition: SceneStoreSnapshot["setPlayerPosition"]; + requestRespawn: SceneStoreSnapshot["requestRespawn"]; +}; + +/** Adapter para conectar el engine con la UI de inventario del host. */ +export interface InventoryUIAdapter { + toggle(): void; + isOpen(): boolean; +} + +/** Adapter para conectar el engine con el sistema de diálogos del host. */ +export interface DialogUIAdapter { + show(text: string, dialogKey?: string, speaker?: string): void; + hide(): void; +} + +export type GameRuntimeConfig = { + scenes?: GameSceneConfig[]; + items?: GameItemConfig[]; + rules?: GameRuleConfig[]; + /** Arboles de dialogo (conversaciones); se registran igual que escenas e items. */ + dialogues?: DialogueDefinition[]; + /** Adapter de UI para inventory. Si no se pasa, inventory:toggle usa el store del core (useInventoryUiStore). */ + inventoryAdapter?: InventoryUIAdapter; + /** Adapter de UI para diálogos. Si no se pasa, dialog:trigger/dismiss usan el store del core (useDialogStore) y emiten el evento. */ + dialogAdapter?: DialogUIAdapter; + /** Almacenamiento para game:save / game:load / game:reset. Sin él esos comandos solo avisan. */ + storage?: KeyValueStoragePort; + /** Clave de guardado dentro de `storage` (por defecto `pointclick-save`). */ + saveKey?: string; + /** Reloj para esperas del secuenciador (por defecto `systemClock`). */ + clock?: ClockPort; + /** Si true, `walkTo` de un guion teletransporta y emite `player:walkCompleted` (headless). */ + instantWalk?: boolean; + /** + * Validacion del contenido al crear el runtime (`validateContent`). + * `true`: avisa por consola con un unico `console.warn` agrupado. `"throw"`: lanza si hay + * errores (los avisos van a consola). `false`: no valida. Sin valor: como `true` solo cuando + * `NODE_ENV === "development"`, y nada en test o produccion. + */ + validate?: boolean | "throw"; + /** Claves de dialogo conocidas, para que la validacion compruebe `say`, `line`, `text` y `label`. */ + dialogKeys?: ReadonlySet; + /** Nombres de manejadores `call` que el host registra, para que la validacion los compruebe. */ + handlerNames?: ReadonlySet; +}; diff --git a/packages/engine-core/src/game/state/dialogStore.ts b/packages/engine-core/src/game/state/dialogStore.ts new file mode 100644 index 0000000..c3f2cc3 --- /dev/null +++ b/packages/engine-core/src/game/state/dialogStore.ts @@ -0,0 +1,40 @@ +import { create } from "zustand"; + +/** + * dialogStore — estado del diálogo/speech bubble activo. + * + * Destino por defecto de `dialog:trigger`/`dialog:dismiss` cuando el runtime + * no recibe `dialogAdapter`. Misma forma que el store de la demo. + */ +export type DialogStoreState = { + text: string; + key: string | undefined; + /** Quien habla (opcional; solo lo fija el secuenciador de guiones). */ + speaker?: string; + visible: boolean; + /** Incrementado en cada `show()` para forzar re-animación del speech bubble. */ + triggerCount: number; + show: (text: string, key?: string, speaker?: string) => void; + dismiss: () => void; +}; + +export const useDialogStore = create((set) => ({ + text: "", + key: undefined, + visible: false, + triggerCount: 0, + show: (text, key, speaker) => + set((s) => ({ + text, + key, + speaker, + visible: true, + triggerCount: s.triggerCount + 1, + })), + dismiss: () => set({ visible: false }), +})); + +/** Lee el estado del diálogo sin React. */ +export function getDialogState() { + return useDialogStore.getState(); +} diff --git a/packages/engine-core/src/game/state/dialogueStore.ts b/packages/engine-core/src/game/state/dialogueStore.ts new file mode 100644 index 0000000..f8dd577 --- /dev/null +++ b/packages/engine-core/src/game/state/dialogueStore.ts @@ -0,0 +1,48 @@ +import { create } from "zustand"; + +/** + * dialogueStore — estado de la conversacion (arbol de dialogo) activa. + * + * No confundir con dialogStore (bocadillo de una frase). Las escrituras las hace + * el motor de dialogo (narrative/dialogue.ts); el store no contiene logica. + */ +export type DialogueChoiceView = { + /** Posicion ORIGINAL en `node.choices` (estable aunque se oculten otras). */ + index: number; + /** Clave de i18n del texto. */ + textKey: string; +}; + +export type DialogueStoreState = { + activeDialogueId: string | null; + nodeId: string | null; + speaker?: string; + lineKey?: string; + /** Opciones visibles (ya filtradas por `when` y `once`). */ + choices: DialogueChoiceView[]; + enterNode: (dialogueId: string, nodeId: string, speaker?: string, lineKey?: string) => void; + setChoices: (choices: DialogueChoiceView[]) => void; + clear: () => void; +}; + +export const useDialogueStore = create((set) => ({ + activeDialogueId: null, + nodeId: null, + choices: [], + enterNode: (dialogueId, nodeId, speaker, lineKey) => + set({ activeDialogueId: dialogueId, nodeId, speaker, lineKey, choices: [] }), + setChoices: (choices) => set({ choices }), + clear: () => + set({ + activeDialogueId: null, + nodeId: null, + speaker: undefined, + lineKey: undefined, + choices: [], + }), +})); + +/** Lee el estado de la conversacion sin React. */ +export function getDialogueState() { + return useDialogueStore.getState(); +} diff --git a/packages/engine-core/src/game/state/gameStatePersistence.ts b/packages/engine-core/src/game/state/gameStatePersistence.ts new file mode 100644 index 0000000..371bb02 --- /dev/null +++ b/packages/engine-core/src/game/state/gameStatePersistence.ts @@ -0,0 +1,109 @@ +import type { InventorySlotsState, PlacedSceneItem } from "../types"; + +/** Puerto mínimo de almacenamiento clave/valor (localStorage-like, sin depender de él). */ +export interface KeyValueStoragePort { + getItem(key: string): string | null; + setItem(key: string, value: string): void; + removeItem?(key: string): void; +} + +/** Clave que usa hoy la demo para los slots. */ +export const INVENTORY_SLOTS_STORAGE_KEY = "inventory-slots"; +/** Clave que usa hoy la demo (zustand persist) para los ítems colocados. */ +export const PLACED_ITEMS_STORAGE_KEY = "placed-items-state"; + +function parseJson(raw: string | null): unknown { + if (!raw) return undefined; + try { + return JSON.parse(raw); + } catch { + return undefined; + } +} + +/** + * Lee slots. Formato: array JSON plano, p. ej. + * `[{"id":"gameboy","name":"Gameboy","spriteUrl":"/a.png","quantity":1},null,null]`. + * Devuelve null si falta, es JSON inválido o no es un array. Nunca lanza. + */ +export function loadInventorySlotsState( + storage: KeyValueStoragePort, + key: string = INVENTORY_SLOTS_STORAGE_KEY, +): InventorySlotsState | null { + try { + const parsed = parseJson(storage.getItem(key)); + return Array.isArray(parsed) ? (parsed as InventorySlotsState) : null; + } catch { + return null; + } +} + +/** Guarda slots como array JSON plano (mismo formato que lee `loadInventorySlotsState`). */ +export function saveInventorySlotsState( + storage: KeyValueStoragePort, + slots: InventorySlotsState, + key: string = INVENTORY_SLOTS_STORAGE_KEY, +): void { + storage.setItem(key, JSON.stringify(slots)); +} + +export type PersistedPlacedItems = { + items: PlacedSceneItem[]; + seededSceneIds: string[]; +}; + +/** + * Lee ítems colocados. Formato: envoltorio de zustand `persist`: + * `{"state":{"items":[...],"initialItemsCreated":true},"version":0}` + * (también acepta `"seededSceneIds":["scene"]` dentro de `state`, que es lo que escribe `save`). + * + * Traducción del flag antiguo `initialItemsCreated: true`: no sabía a qué escena + * correspondía, así que quien llama la indica en `legacySeededSceneId` (la demo: la + * escena que sembraba, "personalRoom"). Con flag true y sin `legacySeededSceneId` no se + * marca ninguna escena (conservador: podría resembrarse). Si existe `seededSceneIds` + * como array, tiene prioridad y el flag se ignora. + * + * Devuelve null si falta, JSON inválido, o sin `state.items` como array. Nunca lanza. + */ +export function loadPlacedItemsState( + storage: KeyValueStoragePort, + options: { key?: string; legacySeededSceneId?: string } = {}, +): PersistedPlacedItems | null { + try { + const parsed = parseJson(storage.getItem(options.key ?? PLACED_ITEMS_STORAGE_KEY)); + if (!parsed || typeof parsed !== "object") return null; + const state = (parsed as { state?: unknown }).state; + if (!state || typeof state !== "object") return null; + const { items, seededSceneIds, initialItemsCreated } = state as Record; + if (!Array.isArray(items)) return null; + + let seeded: string[] = []; + if (Array.isArray(seededSceneIds)) { + seeded = seededSceneIds.filter((s): s is string => typeof s === "string"); + } else if (initialItemsCreated === true && options.legacySeededSceneId) { + seeded = [options.legacySeededSceneId]; + } + return { items: items as PlacedSceneItem[], seededSceneIds: seeded }; + } catch { + return null; + } +} + +/** + * Guarda ítems colocados como envoltorio de zustand persist con version 0: + * `{"state":{"items":[...],"seededSceneIds":["scene"]},"version":0}`. + * No escribe `initialItemsCreated`. + */ +export function savePlacedItemsState( + storage: KeyValueStoragePort, + data: PersistedPlacedItems, + key: string = PLACED_ITEMS_STORAGE_KEY, +): void { + storage.setItem( + key, + JSON.stringify({ + state: { items: data.items, seededSceneIds: data.seededSceneIds }, + version: 0, + }), + ); +} diff --git a/packages/engine-core/src/game/state/index.ts b/packages/engine-core/src/game/state/index.ts index c030168..985927e 100644 --- a/packages/engine-core/src/game/state/index.ts +++ b/packages/engine-core/src/game/state/index.ts @@ -24,3 +24,61 @@ export { setI18nStoreEmitter, type I18nStore, } from "./i18nStore"; +export { useDialogStore, getDialogState, type DialogStoreState } from "./dialogStore"; +export { + useDialogueStore, + getDialogueState, + type DialogueStoreState, + type DialogueChoiceView, +} from "./dialogueStore"; +export { useInputLockStore, getInputLockState, type InputLockStoreState } from "./inputLockStore"; +export { + useInventoryUiStore, + getInventoryUiState, + type InventoryUiStoreState, +} from "./inventoryUiStore"; +export { + DEFAULT_INVENTORY_SLOT_COUNT, + createEmptySlots, + useInventoryStateStore, + getInventoryState, + type InventoryStateStoreState, +} from "./inventoryStore"; +export { + useWorldStateStore, + getWorldState, + type FlagValue, + type WorldSnapshot, + type WorldStateStoreState, +} from "./worldStateStore"; +export { + selectPlacedItemsForScene, + usePlacedItemsStateStore, + getPlacedItemsState, + type PlacedItemsStateStoreState, +} from "./placedItemsReactiveStore"; +export { + INVENTORY_SLOTS_STORAGE_KEY, + PLACED_ITEMS_STORAGE_KEY, + loadInventorySlotsState, + saveInventorySlotsState, + loadPlacedItemsState, + savePlacedItemsState, + type KeyValueStoragePort, + type PersistedPlacedItems, +} from "./gameStatePersistence"; +export { + SAVE_FORMAT_VERSION, + SAVE_STORAGE_KEY, + SAVE_MIGRATIONS, + captureSnapshot, + applySnapshot, + saveGame, + loadGame, + clearSave, + resetGameState, + applySaveMigrations, + type GameSnapshot, + type SnapshotMigration, +} from "./saveGame"; +export { migrateLegacySave, LEGACY_SCENE_ID_STORAGE_KEY } from "./saveGameLegacy"; diff --git a/packages/engine-core/src/game/state/inputLockStore.ts b/packages/engine-core/src/game/state/inputLockStore.ts new file mode 100644 index 0000000..e7da8b1 --- /dev/null +++ b/packages/engine-core/src/game/state/inputLockStore.ts @@ -0,0 +1,23 @@ +import { create } from "zustand"; + +/** + * inputLockStore — bloqueo de entrada del jugador mientras corre un guion. + * + * Lo escribe el secuenciador (acción `lockInput`) y lo lee el renderer para + * ignorar clics/joystick. El secuenciador lo libera siempre que termina o se + * cancela el guion que lo activó. + */ +export type InputLockStoreState = { + inputLocked: boolean; + setInputLocked: (locked: boolean) => void; +}; + +export const useInputLockStore = create((set) => ({ + inputLocked: false, + setInputLocked: (locked) => set({ inputLocked: locked }), +})); + +/** Lee el bloqueo de entrada sin React. */ +export function getInputLockState() { + return useInputLockStore.getState(); +} diff --git a/packages/engine-core/src/game/state/inventoryStore.ts b/packages/engine-core/src/game/state/inventoryStore.ts new file mode 100644 index 0000000..6a481c8 --- /dev/null +++ b/packages/engine-core/src/game/state/inventoryStore.ts @@ -0,0 +1,72 @@ +import { create } from "zustand"; + +import { addOneToInventory, removeOneFromSlot } from "../logic/rules/inventoryRules"; +import type { InventorySlotsState } from "../types"; + +/** Número de slots por defecto del inventario reactivo. */ +export const DEFAULT_INVENTORY_SLOT_COUNT = 9; + +/** + * inventoryStore — slots del inventario como store reactivo (suscribible desde React + * con `useInventoryStateStore(selector)` y desde fuera con `subscribe`). + * + * No confundir con `createInventorySlotsStore` (lista mutable sin suscripción) ni con + * `useInventoryUiStore` (visibilidad del panel). + */ +export type InventoryStateStoreState = { + slots: InventorySlotsState; + slotCount: number; + /** Sustituye todos los slots (p. ej. al hidratar desde persistencia). */ + setSlots: (slots: InventorySlotsState) => void; + /** + * Añade una unidad: apila si ya existe el id, si no usa el primer hueco. + * Devuelve `false` (sin cambiar el estado) si el inventario está lleno. + */ + addItem: (stack: { id: string; name: string; spriteUrl: string }) => boolean; + /** Quita una unidad del slot (lo vacía al llegar a 0). Slot vacío/inexistente: no-op. */ + removeOne: (slotIndex: number) => void; + /** Cambia el número de slots, rellenando con null o recortando por el final. */ + setSlotCount: (slotCount: number) => void; + /** Vacía el inventario; opcionalmente fija un nuevo número de slots. */ + reset: (slotCount?: number) => void; +}; + +export function createEmptySlots(slotCount: number): InventorySlotsState { + const n = Math.max(0, Math.floor(slotCount)); + return Array.from({ length: n }, () => null); +} + +export const useInventoryStateStore = create((set, get) => ({ + slots: createEmptySlots(DEFAULT_INVENTORY_SLOT_COUNT), + slotCount: DEFAULT_INVENTORY_SLOT_COUNT, + setSlots: (slots) => set({ slots }), + addItem: (stack) => { + const result = addOneToInventory(get().slots, stack); + if (!result.added) return false; + set({ slots: result.slots }); + return true; + }, + removeOne: (slotIndex) => { + const current = get().slots; + const next = removeOneFromSlot(current, slotIndex); + if (next !== current) set({ slots: next }); + }, + setSlotCount: (slotCount) => { + const n = Math.max(0, Math.floor(slotCount)); + const current = get().slots; + const slots = + n >= current.length + ? [...current, ...createEmptySlots(n - current.length)] + : current.slice(0, n); + set({ slots, slotCount: n }); + }, + reset: (slotCount) => { + const n = Math.max(0, Math.floor(slotCount ?? get().slotCount)); + set({ slots: createEmptySlots(n), slotCount: n }); + }, +})); + +/** Lee el estado del inventario sin React. */ +export function getInventoryState() { + return useInventoryStateStore.getState(); +} diff --git a/packages/engine-core/src/game/state/inventoryUiStore.ts b/packages/engine-core/src/game/state/inventoryUiStore.ts new file mode 100644 index 0000000..8b5348d --- /dev/null +++ b/packages/engine-core/src/game/state/inventoryUiStore.ts @@ -0,0 +1,26 @@ +import { create } from "zustand"; + +/** + * inventoryUiStore — visibilidad del inventario. + * + * Destino por defecto de `inventory:toggle` cuando el runtime no recibe + * `inventoryAdapter`. Misma forma que `inventoryStore` de la demo. + */ +export type InventoryUiStoreState = { + isOpen: boolean; + toggle: () => void; + open: () => void; + close: () => void; +}; + +export const useInventoryUiStore = create((set) => ({ + isOpen: false, + toggle: () => set((s) => ({ isOpen: !s.isOpen })), + open: () => set({ isOpen: true }), + close: () => set({ isOpen: false }), +})); + +/** Lee el estado de visibilidad del inventario sin React. */ +export function getInventoryUiState() { + return useInventoryUiStore.getState(); +} diff --git a/packages/engine-core/src/game/state/placedItemsReactiveStore.ts b/packages/engine-core/src/game/state/placedItemsReactiveStore.ts new file mode 100644 index 0000000..84dfb5b --- /dev/null +++ b/packages/engine-core/src/game/state/placedItemsReactiveStore.ts @@ -0,0 +1,69 @@ +import { create } from "zustand"; + +import type { PlacedSceneItem } from "../types"; + +/** + * placedItemsReactiveStore — ítems colocados de TODAS las escenas como store reactivo, + * más el conjunto genérico de escenas ya "sembradas" (equivale al antiguo + * `initialItemsCreated`, pero por escena). Qué se siembra y cuándo lo decide quien llama. + * + * No confundir con `createPlacedItemsStore` (lista mutable sin suscripción). + */ +export type PlacedItemsStateStoreState = { + items: PlacedSceneItem[]; + seededSceneIds: string[]; + setItems: (items: PlacedSceneItem[]) => void; + addItem: (item: PlacedSceneItem) => void; + removeItem: (id: string) => void; + /** Sustituye un eje (0=x,1=y,2=z) de la posición del ítem. */ + updateItemPosition: (id: string, axis: 0 | 1 | 2, value: number) => void; + /** Sustituye la posición completa del ítem. */ + setItemPosition: (id: string, position: [number, number, number]) => void; + setSeededSceneIds: (sceneIds: string[]) => void; + markSceneSeeded: (sceneId: string) => void; + isSceneSeeded: (sceneId: string) => boolean; + reset: () => void; +}; + +/** Selector/función pura: ítems de una escena (los que no tienen sceneId no se incluyen). */ +export function selectPlacedItemsForScene( + items: readonly PlacedSceneItem[], + sceneId: string, +): PlacedSceneItem[] { + return items.filter((item) => item.sceneId === sceneId); +} + +export const usePlacedItemsStateStore = create((set, get) => ({ + items: [], + seededSceneIds: [], + setItems: (items) => set({ items }), + addItem: (item) => set((s) => ({ items: [...s.items, item] })), + removeItem: (id) => set((s) => ({ items: s.items.filter((i) => i.id !== id) })), + updateItemPosition: (id, axis, value) => + set((s) => ({ + items: s.items.map((item) => { + if (item.id !== id) return item; + const worldPosition = [...item.worldPosition] as [number, number, number]; + worldPosition[axis] = value; + return { ...item, worldPosition }; + }), + })), + setItemPosition: (id, position) => + set((s) => ({ + items: s.items.map((item) => + item.id === id ? { ...item, worldPosition: [...position] as [number, number, number] } : item, + ), + })), + setSeededSceneIds: (sceneIds) => set({ seededSceneIds: [...new Set(sceneIds)] }), + markSceneSeeded: (sceneId) => + set((s) => + s.seededSceneIds.includes(sceneId) ? s : { seededSceneIds: [...s.seededSceneIds, sceneId] }, + ), + isSceneSeeded: (sceneId) => get().seededSceneIds.includes(sceneId), + reset: () => set({ items: [], seededSceneIds: [] }), +})); + +/** Lee el estado de ítems colocados sin React. */ +export function getPlacedItemsState() { + return usePlacedItemsStateStore.getState(); +} diff --git a/packages/engine-core/src/game/state/saveGame.ts b/packages/engine-core/src/game/state/saveGame.ts new file mode 100644 index 0000000..5568450 --- /dev/null +++ b/packages/engine-core/src/game/state/saveGame.ts @@ -0,0 +1,193 @@ +import type { GameVec3, InventorySlotsState, PlacedSceneItem } from "../types"; +import { sceneRegistry, toRuntimeScene } from "../runtime/registry"; +import type { KeyValueStoragePort } from "./gameStatePersistence"; +import { useInventoryStateStore } from "./inventoryStore"; +import { usePlacedItemsStateStore } from "./placedItemsReactiveStore"; +import { useSceneStore } from "./sceneStore"; +import { useWorldStateStore, type FlagValue } from "./worldStateStore"; + +/** Versión actual del formato de guardado. Súbela al cambiar `GameSnapshot` y añade su migración. */ +export const SAVE_FORMAT_VERSION = 1; + +/** Clave por defecto de la partida única. */ +export const SAVE_STORAGE_KEY = "pointclick-save"; + +/** + * Instantánea completa de la partida (lo que se serializa con `JSON.stringify`, + * `version` primero). + * + * `playerPosition` es OPCIONAL: ausente significa "sin posición guardada" y + * `applySnapshot` usa el spawn por defecto de la escena (el formato de 0.5.0 no + * guardaba la posición del jugador). + */ +export interface GameSnapshot { + version: number; + sceneId: string; + playerPosition?: GameVec3; + inventory: InventorySlotsState; + placedItems: PlacedSceneItem[]; + seededSceneIds: string[]; + flags: Record; + visitedSceneIds: string[]; + /** Estado propio del host (p. ej. puertas de la demo). Opaco para el core. */ + extra?: Record; +} + +export type SaveOptions = { key?: string }; + +function cloneJson(value: T): T { + return JSON.parse(JSON.stringify(value)) as T; +} + +/** Lee los stores y construye la instantánea (copias; no comparte referencias con los stores). */ +export function captureSnapshot(extra?: Record): GameSnapshot { + const scene = useSceneStore.getState(); + const world = useWorldStateStore.getState(); + const placed = usePlacedItemsStateStore.getState(); + const snapshot: GameSnapshot = { + version: SAVE_FORMAT_VERSION, + sceneId: scene.sceneId, + playerPosition: [...scene.playerPosition] as GameVec3, + inventory: cloneJson(useInventoryStateStore.getState().slots), + placedItems: cloneJson(placed.items), + seededSceneIds: [...placed.seededSceneIds], + flags: { ...world.flags }, + visitedSceneIds: [...world.visitedSceneIds], + }; + if (extra) snapshot.extra = extra; + return snapshot; +} + +/** + * Restaura la instantánea. Orden: inventario, ítems colocados + escenas sembradas, + * flags + escenas visitadas y, AL FINAL, la escena (`setScene` con la posición guardada + * o el spawn por defecto), para que lo que se evalúe al entrar vea el estado ya restaurado. + * Si la escena no está registrada no cambia de escena, avisa y devuelve `false` + * (el resto del estado ya queda restaurado). + */ +export function applySnapshot(snapshot: GameSnapshot): boolean { + // Se comprueba la escena antes de tocar nada: una instantánea que no se puede + // aplicar entera no se aplica a medias. + const sceneConfig = sceneRegistry.get(snapshot.sceneId); + if (!sceneConfig) { + console.warn(`[save] applySnapshot — scene not registered: ${snapshot.sceneId}`); + return false; + } + + // El estado se restaura antes de fijar la escena, para que las reglas que se + // evalúan al entrar en ella lo vean ya restaurado. + const slots = cloneJson(snapshot.inventory); + useInventoryStateStore.setState({ slots, slotCount: slots.length }); + + const placed = usePlacedItemsStateStore.getState(); + placed.setItems(cloneJson(snapshot.placedItems)); + placed.setSeededSceneIds(snapshot.seededSceneIds); + + useWorldStateStore.getState().setAll({ + flags: snapshot.flags, + visitedSceneIds: snapshot.visitedSceneIds, + }); + + useSceneStore + .getState() + .setScene(sceneConfig.id, toRuntimeScene(sceneConfig), snapshot.playerPosition); + return true; +} + +/** Guarda la instantánea actual como JSON bajo una única clave. */ +export function saveGame( + storage: KeyValueStoragePort, + opts: SaveOptions & { extra?: Record } = {}, +): void { + storage.setItem(opts.key ?? SAVE_STORAGE_KEY, JSON.stringify(captureSnapshot(opts.extra))); +} + +// --------------------------------------------------------------------------- +// Migraciones por versión +// --------------------------------------------------------------------------- + +export type SnapshotMigration = (snapshot: Record) => Record; + +/** + * Tabla `{ [fromVersion]: migración a fromVersion + 1 }`. Hoy vacía: solo existe la v1. + * Al subir `SAVE_FORMAT_VERSION` a N, añade la entrada N-1. + */ +export const SAVE_MIGRATIONS: Record = {}; + +/** + * Aplica en cadena las migraciones desde `raw.version` hasta `target`. + * Devuelve null si falta algún eslabón o la versión es inválida / superior a `target`. + * `target` y `migrations` son inyectables para poder probar el mecanismo. + */ +export function applySaveMigrations( + raw: Record, + target: number = SAVE_FORMAT_VERSION, + migrations: Record = SAVE_MIGRATIONS, +): Record | null { + let current = raw; + let version = current.version; + if (typeof version !== "number" || !Number.isInteger(version) || version < 1) return null; + if (version > target) return null; + while (version < target) { + const step: SnapshotMigration | undefined = migrations[version]; + if (!step) return null; + version += 1; + current = { ...step(current), version }; + } + return current; +} + +const isObj = (v: unknown): v is Record => + typeof v === "object" && v !== null && !Array.isArray(v); +const isStrArr = (v: unknown): v is string[] => + Array.isArray(v) && v.every((s) => typeof s === "string"); + +function isValidSnapshot(v: Record): boolean { + const pos = v.playerPosition; + return ( + typeof v.sceneId === "string" && + Array.isArray(v.inventory) && + Array.isArray(v.placedItems) && + isStrArr(v.seededSceneIds) && + isObj(v.flags) && + isStrArr(v.visitedSceneIds) && + (pos === undefined || + (Array.isArray(pos) && pos.length === 3 && pos.every((n) => typeof n === "number"))) && + (v.extra === undefined || isObj(v.extra)) + ); +} + +/** + * Lee y valida la partida. Devuelve null si no existe, JSON inválido, forma inesperada, + * versión superior a la soportada o sin migración disponible. Nunca lanza. + */ +export function loadGame(storage: KeyValueStoragePort, opts: SaveOptions = {}): GameSnapshot | null { + try { + const text = storage.getItem(opts.key ?? SAVE_STORAGE_KEY); + if (!text) return null; + const parsed: unknown = JSON.parse(text); + if (!isObj(parsed)) return null; + const migrated = applySaveMigrations(parsed); + if (!migrated || !isValidSnapshot(migrated)) return null; + return migrated as unknown as GameSnapshot; + } catch { + return null; + } +} + +/** + * Borra SOLO la clave de guardado (nunca `clear()`). Si el puerto no tiene `removeItem`, + * la deja vacía (`loadGame` trata la cadena vacía como "sin partida"). + */ +export function clearSave(storage: KeyValueStoragePort, opts: SaveOptions = {}): void { + const key = opts.key ?? SAVE_STORAGE_KEY; + if (storage.removeItem) storage.removeItem(key); + else storage.setItem(key, ""); +} + +/** Vacía los stores de partida (inventario al tamaño actual, ítems, sembrados, mundo). No cambia de escena. */ +export function resetGameState(): void { + useInventoryStateStore.getState().reset(); + usePlacedItemsStateStore.getState().reset(); + useWorldStateStore.getState().reset(); +} diff --git a/packages/engine-core/src/game/state/saveGameLegacy.ts b/packages/engine-core/src/game/state/saveGameLegacy.ts new file mode 100644 index 0000000..689eeb2 --- /dev/null +++ b/packages/engine-core/src/game/state/saveGameLegacy.ts @@ -0,0 +1,69 @@ +import { sceneRegistry } from "../runtime/registry"; +import type { GameVec3 } from "../types"; +import { + INVENTORY_SLOTS_STORAGE_KEY, + PLACED_ITEMS_STORAGE_KEY, + loadInventorySlotsState, + loadPlacedItemsState, + type KeyValueStoragePort, +} from "./gameStatePersistence"; +import { DEFAULT_INVENTORY_SLOT_COUNT, createEmptySlots } from "./inventoryStore"; +import { SAVE_FORMAT_VERSION, type GameSnapshot } from "./saveGame"; + +/** Clave antigua de la escena actual: TEXTO PLANO (sin JSON). */ +export const LEGACY_SCENE_ID_STORAGE_KEY = "current-scene-id"; + +function readExtra(raw: string): unknown { + try { + return JSON.parse(raw); + } catch { + return raw; + } +} + +/** + * Construye una instantánea a partir de las claves de 0.5.0 (`inventory-slots`, + * `current-scene-id`, `placed-items-state`). NO borra las claves antiguas ni escribe la + * nueva: quien llama decide. Devuelve null si no existe NINGUNA de esas tres claves. + * Lo que falte o sea ilegible se rellena con valores neutros (escena `defaultSceneId`, + * inventario vacío de tamaño por defecto, sin ítems colocados). `flags` y + * `visitedSceneIds` quedan vacíos. `playerPosition` se toma del `playerSpawn` de la escena + * si está registrada; si no, se omite (y `applySnapshot` usa el spawn por defecto). + * `extraKeys`: claves antiguas del host cuyo contenido (JSON parseado, o texto si no es + * JSON) se copia a `snapshot.extra[clave]` (las ausentes se ignoran; no cuentan para + * decidir si existe partida antigua). + */ +export function migrateLegacySave( + storage: KeyValueStoragePort, + opts: { legacySeededSceneId?: string; defaultSceneId: string; extraKeys?: string[] }, +): GameSnapshot | null { + const rawScene = storage.getItem(LEGACY_SCENE_ID_STORAGE_KEY); + const rawInventory = storage.getItem(INVENTORY_SLOTS_STORAGE_KEY); + const rawPlaced = storage.getItem(PLACED_ITEMS_STORAGE_KEY); + if (rawScene === null && rawInventory === null && rawPlaced === null) return null; + + const sceneId = rawScene?.trim() ? rawScene.trim() : opts.defaultSceneId; + const inventory = + loadInventorySlotsState(storage) ?? createEmptySlots(DEFAULT_INVENTORY_SLOT_COUNT); + const placed = loadPlacedItemsState(storage, { legacySeededSceneId: opts.legacySeededSceneId }); + + const snapshot: GameSnapshot = { + version: SAVE_FORMAT_VERSION, + sceneId, + inventory, + placedItems: placed?.items ?? [], + seededSceneIds: placed?.seededSceneIds ?? [], + flags: {}, + visitedSceneIds: [], + }; + const spawn = sceneRegistry.get(sceneId)?.playerSpawn; + if (spawn) snapshot.playerPosition = [...spawn] as GameVec3; + + const extra: Record = {}; + for (const key of opts.extraKeys ?? []) { + const raw = storage.getItem(key); + if (raw !== null) extra[key] = readExtra(raw); + } + if (Object.keys(extra).length > 0) snapshot.extra = extra; + return snapshot; +} diff --git a/packages/engine-core/src/game/state/sceneStore.ts b/packages/engine-core/src/game/state/sceneStore.ts index d0b1655..7ac24f5 100644 --- a/packages/engine-core/src/game/state/sceneStore.ts +++ b/packages/engine-core/src/game/state/sceneStore.ts @@ -29,7 +29,8 @@ function emit(event: GameEvent): void { if (_emitter) _emitter(event); } -const SHOULD_LOG_STATE_TRANSITIONS = process.env.NODE_ENV !== "production"; +const SHOULD_LOG_STATE_TRANSITIONS = + typeof process !== "undefined" && process.env?.NODE_ENV !== "production"; type SceneStoreLogger = (event: string, payload: Record) => void; let _logger: SceneStoreLogger | null = null; diff --git a/packages/engine-core/src/game/state/worldStateStore.ts b/packages/engine-core/src/game/state/worldStateStore.ts new file mode 100644 index 0000000..6a839a2 --- /dev/null +++ b/packages/engine-core/src/game/state/worldStateStore.ts @@ -0,0 +1,57 @@ +import { create } from "zustand"; + +/** + * worldStateStore — memoria del motor: flags con nombre y escenas visitadas. + * + * Mismo estilo que dialogStore. El store NO conoce el bus: `createGameRuntime` + * se suscribe a él y emite `state:flagChanged` (ver runtime/worldStateWiring.ts). + */ +export type FlagValue = boolean | number | string; + +export type WorldSnapshot = { + flags: Record; + visitedSceneIds: string[]; +}; + +export type WorldStateStoreState = { + flags: Record; + visitedSceneIds: string[]; + setFlag: (name: string, value: FlagValue) => void; + clearFlag: (name: string) => void; + markSceneVisited: (sceneId: string) => void; + setAll: (snapshot: WorldSnapshot) => void; + reset: () => void; +}; + +export const useWorldStateStore = create((set, get) => ({ + flags: {}, + visitedSceneIds: [], + setFlag: (name, value) => { + const flags = get().flags; + if (Object.prototype.hasOwnProperty.call(flags, name) && flags[name] === value) return; + set({ flags: { ...flags, [name]: value } }); + }, + clearFlag: (name) => { + const flags = get().flags; + if (!Object.prototype.hasOwnProperty.call(flags, name)) return; + const next = { ...flags }; + delete next[name]; + set({ flags: next }); + }, + markSceneVisited: (sceneId) => { + const visited = get().visitedSceneIds; + if (visited.includes(sceneId)) return; + set({ visitedSceneIds: [...visited, sceneId] }); + }, + setAll: (snapshot) => + set({ + flags: { ...snapshot.flags }, + visitedSceneIds: Array.from(new Set(snapshot.visitedSceneIds)), + }), + reset: () => set({ flags: {}, visitedSceneIds: [] }), +})); + +/** Lee el estado de mundo sin React. */ +export function getWorldState(): WorldStateStoreState { + return useWorldStateStore.getState(); +} diff --git a/packages/engine-core/src/game/types/index.ts b/packages/engine-core/src/game/types/index.ts index 50c5861..cf742df 100644 --- a/packages/engine-core/src/game/types/index.ts +++ b/packages/engine-core/src/game/types/index.ts @@ -5,6 +5,9 @@ export type GameVec3 = [x: number, y: number, z: number]; export type GameVec2 = [x: number, y: number]; +import type { Branch, Script } from "../narrative/actions"; +import type { Condition } from "../narrative/conditions"; + // Scene geometry export interface GameSceneGround { minX: number; @@ -101,6 +104,8 @@ export type ItemDefinition = { pickupSoundUrl?: string; /** Override del SFX por defecto al soltar este ítem. */ dropSoundUrl?: string; + /** Ramas condicionales para combinar este ítem con otro por id. */ + combine?: Record; }; // Inventory state @@ -154,6 +159,13 @@ export interface BaseSceneTransition { postTransitionDialogKey?: DialogKey; /** Override del SFX por defecto al disparar esta transición. */ triggerSoundUrl?: string; + /** + * Condicion para que la transicion ocurra (todos los tipos). Sin ella, siempre ocurre. + * Si no se cumple no hay cambio de escena y, si existe, corre `blocked`. + */ + when?: Condition; + /** Guion que corre al intentar la transicion sin cumplir `when`. */ + blocked?: Script; } export interface GameSceneTransitionOnCollision extends BaseSceneTransition { @@ -206,6 +218,54 @@ export interface PlayerWalkingState { isActive: boolean; } +// Hotspots (verbos narrativos; ver narrative/hotspots.ts) +export type Verb = "look" | "use" | "talk"; + +export interface GameSceneHotspot { + id: string; + /** Clave de i18n. */ + label: string; + position: GameVec3; + halfSize: GameVec3; + rotationY?: number; + visibleWhen?: Condition; + hasCollision?: boolean; + /** Punto al que camina el jugador antes de actuar. Sin el, actua desde donde esta. */ + approach?: GameVec3; + verbs?: Partial>; + /** Ramas por itemId al usar un item del inventario sobre el hotspot. */ + useItem?: Record; + /** Ramas para un item sin regla propia en `useItem`. */ + useItemDefault?: Branch[]; +} + +/** Hacia donde mira un NPC en reposo. */ +export type NpcFacing = "north" | "south" | "west" | "east"; + +/** Personaje de la escena con el que se puede hablar. Se proyecta a hotspot (`npcToHotspot`). */ +export interface GameSceneNpc { + id: string; + /** Clave de i18n. */ + name: string; + /** Id de un personaje registrado en el viewport (prop `characters`). */ + characterId: string; + position: GameVec3; + facing?: NpcFacing; + visibleWhen?: Condition; + hasCollision?: boolean; + approach?: GameVec3; + /** + * Caja clicable del NPC: semi-extensiones y desplazamiento de su centro respecto a `position`. + * Por defecto cubre un sprite del tamano por defecto, de los pies a la cabeza. + */ + clickBox?: { halfSize: GameVec3; offset?: GameVec3 }; + /** Atajo: hablar inicia este diálogo. Equivale a `verbs.talk = [{ do: [{ startDialogue }] }]`. */ + dialogueId?: string; + /** Verbos e ítems, igual que un hotspot. `verbs.talk` explícito gana sobre `dialogueId`. */ + verbs?: Partial>; + useItem?: Record; +} + // Scene (full scene with all interactions) export interface GameScene { id: string; @@ -219,6 +279,26 @@ export interface GameScene { transitions?: GameSceneTransition[]; /** Music optional associated to this scene. */ music?: SceneMusicConfig; + /** Hotspots con verbos narrativos. */ + hotspots?: GameSceneHotspot[]; + /** NPCs de la escena. `toRuntimeScene` los proyecta además a `hotspots`. */ + npcs?: GameSceneNpc[]; + /** + * Items colocados iniciales, sembrados una vez por escena al entrar. Cada item + * se incluye solo si su `when` se cumple en ese momento (sin `when`, siempre). + */ + initialItems?: SceneInitialItem[]; + /** + * Ramas de entrada: en cada entrada a la escena corre el guion de la primera que se cumple. + * Al evaluarse, la escena ya cuenta como visitada: para "solo la primera vez" usa un flag + * (`not(flag(...))` y `setFlag` en el guion), no `not(visited(...))`. + */ + onEnter?: Branch[]; +} + +export interface SceneInitialItem { + item: PlacedSceneItem; + when?: Condition; } // Editor/Debug modes diff --git a/packages/engine-core/src/index.ts b/packages/engine-core/src/index.ts index 38bc77f..42bcb9b 100644 --- a/packages/engine-core/src/index.ts +++ b/packages/engine-core/src/index.ts @@ -4,7 +4,9 @@ export * from "./game/state"; export * from "./game/commands"; export * from "./game/events"; export * from "./game/i18n"; +export * from "./game/runtime"; +export * from "./game/narrative"; export * from "./events"; export * from "./ports"; -export const VERSION = "0.4.0"; +export const VERSION = "0.6.0"; diff --git a/packages/engine-core/src/ports/clock.ts b/packages/engine-core/src/ports/clock.ts new file mode 100644 index 0000000..41692be --- /dev/null +++ b/packages/engine-core/src/ports/clock.ts @@ -0,0 +1,37 @@ +/** + * Clock port abstraction. Renderer-agnostic contract. + * + * Allows the game engine to measure time and schedule async operations + * without relying on setTimeout directly. + * + * Implementations: + * - System: wraps globalThis.setTimeout and Date.now + * - Headless: manual time advance via HeadlessClock.advance(ms) for tests + */ +export interface ClockPort { + /** Current time in milliseconds. */ + now(): number; + + /** + * Schedule a callback to run after ms milliseconds. + * Returns a cancel function that stops the callback if called before execution. + */ + setTimeout(fn: () => void, ms: number): () => void; +} + +/** + * System clock implementation using globalThis.setTimeout and Date.now. + * Safe for core (no window, no document, no React). + */ +export const systemClock: ClockPort = { + now(): number { + return Date.now(); + }, + + setTimeout(fn: () => void, ms: number): () => void { + const id = globalThis.setTimeout(fn, ms); + return () => { + globalThis.clearTimeout(id); + }; + }, +}; diff --git a/packages/engine-core/src/ports/headlessClock.ts b/packages/engine-core/src/ports/headlessClock.ts new file mode 100644 index 0000000..c431947 --- /dev/null +++ b/packages/engine-core/src/ports/headlessClock.ts @@ -0,0 +1,60 @@ +import type { ClockPort } from "./clock"; + +/** + * Headless Clock for tests: time advances only via advance(ms). + * No dependency on globalThis.setTimeout — suitable for deterministic unit tests. + */ +export class HeadlessClock implements ClockPort { + private currentTime = 0; + private nextId = 0; + private timers = new Map void }>(); + + now(): number { + return this.currentTime; + } + + setTimeout(fn: () => void, ms: number): () => void { + const id = this.nextId++; + const dueTime = this.currentTime + ms; + this.timers.set(id, { dueTime, fn }); + + return () => { + this.timers.delete(id); + }; + } + + /** + * Advance the clock by ms milliseconds and fire every timer due by then, in + * order of due time (ties in scheduling order). Timers scheduled by a callback + * also fire if they fall within the same advance, including zero-delay ones. + * `advance(0)` fires the timers that are already due. + */ + advance(ms: number): void { + const targetTime = this.currentTime + Math.max(0, ms); + + for (;;) { + let nextId: number | null = null; + let nextDue = Infinity; + // Map iteration is insertion order, so the first match wins ties. + for (const [id, { dueTime }] of this.timers) { + if (dueTime <= targetTime && dueTime < nextDue) { + nextDue = dueTime; + nextId = id; + } + } + if (nextId === null) break; + + const { fn } = this.timers.get(nextId)!; + this.timers.delete(nextId); + this.currentTime = Math.max(this.currentTime, nextDue); + fn(); + } + + this.currentTime = targetTime; + } + + /** Return the number of pending timers. */ + pending(): number { + return this.timers.size; + } +} diff --git a/packages/engine-core/src/ports/index.ts b/packages/engine-core/src/ports/index.ts index 7bce3d8..6f9ebae 100644 --- a/packages/engine-core/src/ports/index.ts +++ b/packages/engine-core/src/ports/index.ts @@ -28,3 +28,7 @@ export { HeadlessAudioAdapter, type HeadlessAudioCall } from "./headlessAudio"; export type { I18nPort } from "./i18n"; export { HeadlessI18nAdapter, type HeadlessI18nCall } from "./headlessI18n"; + +export type { ClockPort } from "./clock"; +export { systemClock } from "./clock"; +export { HeadlessClock } from "./headlessClock"; diff --git a/packages/engine-core/src/testing/index.ts b/packages/engine-core/src/testing/index.ts new file mode 100644 index 0000000..6f8c1f5 --- /dev/null +++ b/packages/engine-core/src/testing/index.ts @@ -0,0 +1,8 @@ +export { + createPlaythrough, + SETTLE_MAX_ITERATIONS, + SETTLE_STEP_MS, + type Playthrough, + type PlaythroughOptions, + type PlaythroughState, +} from "./playthrough"; diff --git a/packages/engine-core/src/testing/playthrough.ts b/packages/engine-core/src/testing/playthrough.ts new file mode 100644 index 0000000..cca36cb --- /dev/null +++ b/packages/engine-core/src/testing/playthrough.ts @@ -0,0 +1,312 @@ +import { setSceneStoreLogger } from "../game/state"; +import { useDialogStore } from "../game/state/dialogStore"; +import { getDialogueState, useDialogueStore } from "../game/state/dialogueStore"; +import { useInputLockStore } from "../game/state/inputLockStore"; +import { DEFAULT_INVENTORY_SLOT_COUNT, getInventoryState } from "../game/state/inventoryStore"; +import { getPlacedItemsState } from "../game/state/placedItemsReactiveStore"; +import { applySnapshot, captureSnapshot, type GameSnapshot } from "../game/state/saveGame"; +import { getSceneState, useSceneStore } from "../game/state/sceneStore"; +import { getWorldState, type FlagValue } from "../game/state/worldStateStore"; +import type { KeyValueStoragePort } from "../game/state/gameStatePersistence"; +import { createGameRuntime, getGameRuntime } from "../game/runtime/createGameRuntime"; +import { dialogueRegistry, itemRegistry, ruleRegistry, sceneRegistry } from "../game/runtime/registry"; +import type { GameRuntime, ScriptHandler } from "../game/runtime/types"; +import { + evaluateTransitionGate, + getDeclaredScene, + getSceneRuleContext, + resolveEnterScript, + resolveInitialItems, +} from "../game/narrative/sceneRules"; +import type { GameContent } from "../game/narrative/validateContent"; +import type { Verb } from "../game/types"; +import { HeadlessClock } from "../ports/headlessClock"; + +/** Opciones de `createPlaythrough`. */ +export interface PlaythroughOptions { + /** Escena en la que empieza la partida. Por defecto, la primera de `content.scenes`. */ + initialSceneId?: string; + /** + * Manejadores de la accion `call`. Se registran ANTES de entrar en la escena inicial, + * para que un `onEnter` que los use los encuentre. + */ + handlers?: Record; + /** + * Se llama con el runtime recien creado, ANTES de entrar en la escena inicial: el sitio para + * suscribirse a eventos que ya ocurren al arrancar (p. ej. el bocadillo de un `onEnter`). + */ + onRuntime?: (runtime: GameRuntime) => void; + /** + * Partida guardada de la que partir (p. ej. `otraPartida.save()`). Se restaura sin volver a + * correr el `onEnter` de la escena guardada; `initialSceneId` se ignora. + */ + snapshot?: GameSnapshot; +} + +export interface PlaythroughState { + sceneId: string; + /** Un id por unidad (un item apilado x2 aparece dos veces), en orden de slot. */ + inventory: string[]; + flags: Record; + /** true mientras hay una conversacion (arbol de dialogo) abierta. */ + dialogueActive: boolean; +} + +export interface Playthrough { + runtime: GameRuntime; + clock: HeadlessClock; + /** Mira el hotspot / NPC `id` de la escena activa. Verbo `look`. */ + look(id: string): Promise; + /** Usa el hotspot / NPC `id` (verbo `use`). */ + use(id: string): Promise; + /** Habla con el hotspot / NPC `id` (verbo `talk`). Se detiene en la primera eleccion pendiente. */ + talk(id: string): Promise; + /** Usa el item `itemId` del inventario sobre el hotspot / NPC `id`. */ + useItemOn(itemId: string, id: string): Promise; + /** Combina dos items del inventario. */ + combine(a: string, b: string): Promise; + /** Recoge un item colocado de la escena activa (por el `id` del item colocado). */ + pickUp(placedItemId: string): Promise; + /** + * Elige una opcion de la conversacion activa. `index` es la posicion ORIGINAL en + * `node.choices` (la misma que usa `dialogue:choose`), no la posicion entre las visibles. + * Lanza si esa opcion no esta disponible ahora. + */ + choose(index: number): Promise; + /** Cruza la transicion `transitionId` de la escena activa, respetando `when` / `blocked`. */ + goThrough(transitionId: string): Promise; + /** Avanza el reloj y descarta bocadillos hasta que no quede ningun guion en curso. */ + settle(): Promise; + state(): PlaythroughState; + save(): GameSnapshot; + dispose(): void; +} + +/** Iteraciones maximas de `settle` antes de dar el recorrido por atascado. */ +export const SETTLE_MAX_ITERATIONS = 2000; +/** Milisegundos de reloj virtual que avanza `settle` en cada iteracion. */ +export const SETTLE_STEP_MS = 250; + +const MICROTASKS_PER_TURN = 40; + +async function flushMicrotasks(times = MICROTASKS_PER_TURN): Promise { + for (let i = 0; i < times; i++) await Promise.resolve(); +} + +function memoryStorage(): KeyValueStoragePort { + const data = new Map(); + return { + getItem: (key) => (data.has(key) ? data.get(key)! : null), + setItem: (key, value) => void data.set(key, value), + removeItem: (key) => void data.delete(key), + }; +} + +/** Deja los registros globales del runtime y los stores de partida como recien arrancados. */ +function resetGlobalState(): void { + sceneRegistry.clear(); + itemRegistry.clear(); + ruleRegistry.clear(); + dialogueRegistry.clear(); + useDialogStore.setState({ text: "", key: undefined, speaker: undefined, visible: false, triggerCount: 0 }); + useDialogueStore.getState().clear(); + useInputLockStore.setState({ inputLocked: false }); + getInventoryState().reset(DEFAULT_INVENTORY_SLOT_COUNT); + getPlacedItemsState().reset(); + getWorldState().reset(); + useSceneStore.setState({ sceneId: "", playerPosition: [0, 0, 0], playerWalkingState: null }); +} + +/** + * Crea una partida headless de `content`: runtime real, `HeadlessClock`, almacenamiento en + * memoria y caminata instantanea. Valida el contenido y lanza si hay errores. + * + * Los registros de escenas, items y dialogos del runtime son globales de modulo: crear una + * partida los deja limpios (y descarta el runtime activo anterior), y `dispose()` los vuelve + * a limpiar. Hay una sola partida viva a la vez por proceso. + * + * Sin renderer, aqui se aplican las reglas declarativas de escena que en el juego aplica el + * renderer, con las mismas funciones puras del core: siembra de `initialItems` y `onEnter` al + * entrar en una escena, y `when` / `blocked` en `goThrough`. + */ +export function createPlaythrough(content: GameContent, opts: PlaythroughOptions = {}): Playthrough { + const first = content.scenes[0]; + const initialSceneId = opts.initialSceneId ?? first?.id; + if (!opts.snapshot) { + if (initialSceneId === undefined) throw new Error("[playthrough] el contenido no tiene escenas"); + if (!content.scenes.some((s) => s.id === initialSceneId)) { + throw new Error(`[playthrough] escena inicial inexistente: "${initialSceneId}"`); + } + } + + getGameRuntime()?.dispose(); + resetGlobalState(); + setSceneStoreLogger(() => {}); + + const handlerNames = + content.handlers ?? (opts.handlers ? new Set(Object.keys(opts.handlers)) : undefined); + const clock = new HeadlessClock(); + let runtime: GameRuntime; + try { + runtime = createGameRuntime({ + scenes: content.scenes, + items: content.items, + ...(content.dialogues ? { dialogues: content.dialogues } : {}), + ...(content.dialogKeys ? { dialogKeys: content.dialogKeys } : {}), + ...(handlerNames ? { handlerNames } : {}), + storage: memoryStorage(), + clock, + instantWalk: true, + validate: "throw", + }); + } catch (error) { + resetGlobalState(); + setSceneStoreLogger(null); + throw error; + } + for (const [name, fn] of Object.entries(opts.handlers ?? {})) runtime.registerHandler(name, fn); + opts.onRuntime?.(runtime); + + // --- seguimiento de guiones en curso ------------------------------------------------- + let running = 0; + let restoring = false; + let disposed = false; + const offs: Array<() => void> = [ + runtime.on("script:started", () => void running++), + runtime.on("script:finished", () => void running--), + // Lo que el renderer hace al entrar en una escena: sembrar items y correr `onEnter`. + runtime.on("scene:changed", (event) => { + if (restoring) return; + enterScene(event.sceneId); + }), + ]; + + function enterScene(sceneId: string): void { + const placed = getPlacedItemsState(); + const declared = getDeclaredScene(sceneId)?.initialItems; + if (Array.isArray(declared) && !placed.isSceneSeeded(sceneId)) { + const added = resolveInitialItems(sceneId, declared, getSceneRuleContext(sceneId, placed.items)); + if (added && added.length > 0) placed.setItems([...placed.items, ...added]); + placed.markSceneSeeded(sceneId); + } + const script = resolveEnterScript(getDeclaredScene(sceneId)?.onEnter, getSceneRuleContext(sceneId)); + if (script) runtime.runScript(script); + } + + async function settle(): Promise { + for (let i = 0; i < SETTLE_MAX_ITERATIONS; i++) { + await flushMicrotasks(); + if (useDialogStore.getState().visible) { + runtime.executeCommand({ type: "dialog:dismiss" }); + continue; + } + if (running <= 0) return; + // Una conversacion esperando una eleccion no avanza sin el jugador: es un punto de reposo. + if (getDialogueState().choices.length > 0) return; + clock.advance(SETTLE_STEP_MS); + } + const { activeDialogueId, nodeId } = getDialogueState(); + throw new Error( + `[playthrough] settle() no converge tras ${SETTLE_MAX_ITERATIONS} iteraciones ` + + `(${SETTLE_STEP_MS} ms virtuales cada una): guiones en curso=${running}, ` + + `temporizadores pendientes=${clock.pending()}, ` + + `dialogo=${activeDialogueId ?? "ninguno"}${nodeId ? `/${nodeId}` : ""}`, + ); + } + + async function interact(verb: Verb | "useItem", id: string, itemId?: string): Promise { + runtime.executeCommand({ + type: "hotspot:interact", + hotspotId: id, + verb, + ...(itemId !== undefined ? { itemId } : {}), + }); + await settle(); + } + + // --- estado inicial -------------------------------------------------------------------- + if (opts.snapshot) { + restoring = true; + let applied = false; + try { + applied = applySnapshot(opts.snapshot); + } finally { + restoring = false; + } + if (!applied) { + runtime.dispose(); + resetGlobalState(); + setSceneStoreLogger(null); + throw new Error(`[playthrough] la escena de la partida guardada no existe: "${opts.snapshot.sceneId}"`); + } + } else { + runtime.executeCommand({ type: "scene:set", sceneId: initialSceneId! }); + } + + const playthrough: Playthrough = { + runtime, + clock, + look: (id) => interact("look", id), + use: (id) => interact("use", id), + talk: (id) => interact("talk", id), + useItemOn: (itemId, id) => interact("useItem", id, itemId), + async combine(a, b) { + runtime.executeCommand({ type: "inventory:combine", itemId: a, withItemId: b }); + await settle(); + }, + async pickUp(placedItemId) { + const sceneId = getSceneState().sceneId; + const placed = getPlacedItemsState().items.find((p) => p.id === placedItemId); + // El comando busca por id en TODAS las escenas: aqui solo se alcanza lo de la escena activa. + if (placed && placed.sceneId === sceneId) { + runtime.executeCommand({ type: "inventory:pickup", itemId: placed.itemId, placedItemId }); + } else { + runtime.emit({ type: "inventory:pickupFailed", itemId: placedItemId, reason: "not-found" }); + } + await settle(); + }, + async choose(index) { + if (!getDialogueState().choices.some((c) => c.index === index)) { + const available = getDialogueState().choices.map((c) => c.index).join(", ") || "ninguna"; + throw new Error(`[playthrough] choose(${index}): opcion no disponible (disponibles: ${available})`); + } + runtime.executeCommand({ type: "dialogue:choose", index }); + await settle(); + }, + async goThrough(transitionId) { + const { sceneId, scene } = getSceneState(); + const transition = scene.transitions?.find((t) => t.id === transitionId); + if (!transition) { + throw new Error(`[playthrough] goThrough: la escena "${sceneId}" no tiene la transicion "${transitionId}"`); + } + const gate = evaluateTransitionGate(transition, getSceneRuleContext(sceneId)); + if (!gate.allowed) { + if (gate.blocked.length > 0) runtime.runScript(gate.blocked); + } else { + runtime.executeCommand({ type: "transition:activate", transitionId }); + } + await settle(); + }, + settle, + state() { + return { + sceneId: getSceneState().sceneId, + inventory: getInventoryState().slots.flatMap((s) => + s ? Array.from({ length: s.quantity }, () => s.id) : [], + ), + flags: { ...getWorldState().flags }, + dialogueActive: getDialogueState().activeDialogueId !== null, + }; + }, + save: () => captureSnapshot(), + dispose() { + if (disposed) return; + disposed = true; + for (const off of offs) off(); + runtime.dispose(); + resetGlobalState(); + setSceneStoreLogger(null); + }, + }; + return playthrough; +} diff --git a/packages/engine-renderer-r3f/CHANGELOG.md b/packages/engine-renderer-r3f/CHANGELOG.md index 17ee809..0cf6cda 100644 --- a/packages/engine-renderer-r3f/CHANGELOG.md +++ b/packages/engine-renderer-r3f/CHANGELOG.md @@ -7,6 +7,115 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.6.0] — Unreleased + +Phase 17: narrative primitives in the viewport. Requires +`@pointclick-engine/engine-core` ^0.6.0. Additive over 0.5.0. Guide: +[`docs/authoring/`](../../docs/authoring/README.md). + +### Added — Hotspots, NPCs and conversations + +- Clickable hotspots: `SceneHotspots`, `useHotspotInteractions`, + `useVisibleHotspots`, `VerbMenu` (a single applicable verb runs on click, + several open the menu), item drops onto hotspots, and the engine texts + `ensureEngineTexts`, `ENGINE_VERB_LABEL_KEYS`, `ENGINE_NO_ACTION_KEY` + (Spanish and English defaults the host can override). +- NPCs: `SceneNpcs`, `useVisibleNpcs`, `NpcSprite`, `selectNpcAnimation`, + `spriteScaleAtDepth`; the speech bubble goes over the NPC whose `id` matches + the line `speaker`. `GameSceneNpc.clickBox` adjusts the clickable box. +- Conversations: `DialogueChoices` (keyboard: arrows, Enter/Space, 1-9) and + `useDialogue`. +- New `GameViewport` / `GameViewportView` props: `characters` (character + definitions by `characterId`), `verbMenu`, `noActionDialogKey`, + `dialogueChoices`. The controller also returns `speechSpeaker`, `dialogue`, + `dialogueChoicesVisible`, `speechPersistent` and `onSpeechTypingDone`. +- The renderer applies the declarative scene rules with the pure core + functions: `initialItems` when seeding, `onEnter` on entering a scene, and + `when` / `blocked` before a transition. +- Path walks emit `player:walkCompleted` and `player:walkAborted`. + +### Changed + +- Closing the speech bubble goes through the `dialog:dismiss` command, so + `dialog:dismissed` is emitted (scripts waiting on a `say` rely on it). + +### Fixed + +- The walk clip no longer flickers between directions. + +### Deprecated + +- `canLeaveScene`, `onSceneEnter` and `getInitialPlacedItems` are not removed: + they stay as an advanced path and are evaluated after the declarative rules. + Prefer `transition.when` / `blocked`, `onEnter` and `initialItems`. + +## [0.5.0] — Unreleased + +Phase 16: the playable game composition moves into this package. The demo +becomes a consumer. Requires `@pointclick-engine/engine-core` ^0.5.0. + +### Added — Playable `GameViewport` + +- `GameViewport` works with defaults: uses the active runtime + (`getGameRuntime()`), built-in character, inventory and transitions. + Optional props: `initialSceneId`, `storage`, `resolveScene`, + `canLeaveScene`, `getPhrase`, `getInitialPlacedItems`, `onSceneEnter`, + `itemContext`, `audio`, `filterPlacedItems`, `startPersistence`, + `character`, `cameraMode`, `spriteRuntimeProps`, `canPickupItems`, + `canvasChildren`, `children`, `overlay`, `onSceneReady`, `debug`, + `onRuntimeEvent`. +- `useGameViewportController` + `GameViewportView`: the two halves of + `GameViewport`, for hosts that need the controller in their own UI. +- Hooks: `useSceneRuntime`, `useTransitionSystem`, `useInventoryRuntime`, + `useGameState`, `useGameActions`; `attachAudioSystem` (no React) behind + `useAudioSystem`. +- `CharacterSprite`, `CharacterDefinition`, `CharacterClip`, + `CharacterDirection` and helpers (`buildFrameUrls`, `selectClip`, + `resolveCharacterSprites`, `listCharacterAnimations`, `toSpriteAnimation`). +- Scene components moved from the demo: + `SceneBackgroundPlane`, `CameraController`, `CameraFitHeight`, + `SceneDropTargets`, `PlacedSceneItems`. + +### Changed + +- `useGameState` / `useGameActions` are implemented here and re-exported by + the demo's `publicApi.ts`. +- Picking up an item is emitted as `item:pickedUp` (see Breaking); the audio + bridge plays the drop sound only for `outcome: "place"`. + +- The loose physics test sphere is no longer rendered by default. Enable it + with the `collisionSphere` prop of `GameTouchSpriteRuntime` (or + `spriteRuntimeProps.collisionSphere` on the viewport) and pass your own + `textureUrl`; the package no longer requests `/globe.svg` from the host. +- Items returned by `getInitialPlacedItems` without `sceneId` are assigned to + the scene being seeded. + +### Fixed + +- Peer range for `three` was `^0.150.0`, which only matched 0.150.x and made + the package uninstallable next to current three releases. Now `>=0.150.0`. +- Test files are no longer shipped in the published package. + +### Deprecated + +- `DavidSprite` / `DavidSpriteHandle`: use `CharacterSprite` / + `CharacterSpriteHandle`. +- The exports of `sprite/clips.ts`: pass a `CharacterDefinition` via the + `character` prop (speaking clip: `CharacterDefinition.speaking`). + +### Breaking + +- Behavior (from `engine-core` 0.5.0): pick-ups arrive as `item:pickedUp`, + no longer as `item:dropped` with `outcome: "pickup-success"`. Listeners on + the runtime bus must be updated. + +### Known limitations + +- Doors are not an engine primitive (the demo implements them). +- Registries are module-global (one game per page). +- The default character has no bundled assets: without a `character` prop the + host must serve the frames under `/assets/sprites/david/`. + ## [0.4.0] — 2026-05-31 This release folds in everything between v0.1.x and v0.4.0 (phases 6, 8, 9, diff --git a/packages/engine-renderer-r3f/README.md b/packages/engine-renderer-r3f/README.md index 35a5f7e..852f7e2 100644 --- a/packages/engine-renderer-r3f/README.md +++ b/packages/engine-renderer-r3f/README.md @@ -1,6 +1,6 @@ # @pointclick-engine/engine-renderer-r3f -React Three Fiber renderer for the [Point & Click Game Engine](https://www.npmjs.com/package/@pointclick-engine/engine-core). +React Three Fiber renderer for the [Point & Click Game Engine](https://www.npmjs.com/package/@pointclick-engine/engine-core). Provides `GameViewport`: a playable game in one component. ## Install @@ -18,17 +18,20 @@ Supported ranges: React 18/19 · Three ≥0.150 · R3F 8/9 · Drei 9/10 · Rapie ## Quick start +The runtime comes from `engine-core`; the viewport from this package. Create the runtime once, mount the viewport when it exists (`GameViewport` is client-only). + ```tsx +"use client"; + +import { useEffect, useState } from "react"; import { - GameCanvasCore, - GameTouchSpriteRuntime, - SceneGround, - SceneWalls, -} from "@pointclick-engine/engine-renderer-r3f"; -import { useSceneStore } from "@pointclick-engine/engine-core/state"; -import type { GameScene } from "@pointclick-engine/engine-core/types"; - -const scene: GameScene = { + createGameRuntime, + type GameRuntime, + type GameSceneConfig, +} from "@pointclick-engine/engine-core"; +import { GameViewport } from "@pointclick-engine/engine-renderer-r3f"; + +const TOWN: GameSceneConfig = { id: "town", label: "Town", background: "/assets/background/town.jpg", @@ -36,54 +39,32 @@ const scene: GameScene = { ground: { minX: -15, maxX: 15, minZ: -10, maxZ: 30, y: -3 }, walls: [], interactions: [], - transitions: [], }; -// Register before first render -useSceneStore.getState().setScenes([scene]); -useSceneStore.getState().setCurrentScene("town"); - -function App() { - return ( - - - - - - ); +export default function Game() { + const [runtime, setRuntime] = useState(null); + + useEffect(() => { + const created = createGameRuntime({ scenes: [TOWN] }); + setRuntime(created); + return () => { + created.dispose(); + setRuntime(null); + }; + }, []); + + if (!runtime) return null; + return ; } ``` -## i18n / Localization +With the defaults the game is playable: built-in character, inventory, item pick-up/placing and scene transitions. No persistence and no audio unless you pass `storage` / `audio`. A complete example that imports only from the packages: `apps/web-demo/app/example-minimal/page.tsx` in the monorepo. Option groups: [consumption guide](https://github.com/DanielMartinezSebastian/pointclick-engine/blob/main/docs/LIBRARY_CONSUMPTION_GUIDE.md). -```tsx -import { - I18nProvider, - LocaleSwitcher, - useI18n, -} from "@pointclick-engine/engine-renderer-r3f"; -import { registerDictionary } from "@pointclick-engine/engine-core"; - -registerDictionary("en", { "ui.start": ["Start game"] }); -registerDictionary("es", { "ui.start": ["Iniciar juego"] }); - -function HUD() { - const { t, locale } = useI18n(); - return

{t("ui.start")}

; -} +Need your own UI around the game state? Use `useGameViewportController` + `GameViewportView` instead of `GameViewport`. -function App() { - return ( - - - - … - - ); -} -``` +## i18n / Localization -Locale is auto-detected from `navigator.language` (via `useLocaleDetection`) and persisted through the `I18nPort`. +`useI18n`, `useLocaleDetection`, `I18nProvider` and `LocaleSwitcher` are exported from the root entry point. Dictionaries are registered with `registerDictionary` from `engine-core`. Next.js recipes: [`docs/integrations/nextjs-i18n.md`](https://github.com/DanielMartinezSebastian/pointclick-engine/blob/main/docs/integrations/nextjs-i18n.md). ## Subpath exports @@ -91,65 +72,76 @@ Locale is auto-detected from `navigator.language` (via `useLocaleDetection`) and // Port adapters (implement engine-core interfaces for R3F / browser) import { useR3FGameLoop, WebKeyboardInput } from "@pointclick-engine/engine-renderer-r3f/adapters"; -// React components (canvas, i18n UI) -import { GameCanvasCore, I18nProvider, LocaleSwitcher } from "@pointclick-engine/engine-renderer-r3f/components"; +// React components (canvas, sprites, a subset of scene primitives) +import { GameCanvasCore, CharacterSprite, SceneGround } from "@pointclick-engine/engine-renderer-r3f/components"; ``` -Everything is also re-exported from the root entry point. +`GameViewport`, the hooks and the i18n components are only in the root entry point. ## What this package provides -### Canvas & runtime +### Viewport | Export | Description | |--------|-------------| -| `GameCanvasCore` | R3F `Canvas` shell with physics world and game loop wired up | -| `GameTouchSpriteRuntime` | Player movement controller — click-to-move, touch, keyboard | +| `GameViewport` | Playable game: controller + view with sensible defaults | +| `useGameViewportController` | Hook (no JSX) that runs the generic game hooks and returns what the view and your UI need | +| `GameViewportView` | Presentational view: Canvas, scene, character, items, fade curtain. Extend with `children`, `canvasChildren`, `overlay` | +| `GameCanvasCore` | Minimal R3F `Canvas` shell | +| `GameTouchSpriteRuntime` | Player movement runtime: click-to-move, touch, keyboard | ### Scene primitives | Export | Description | |--------|-------------| -| `SceneGround` | Invisible ground plane with physics collider | -| `SceneWalls` | Renders `GameSceneWall[]` as collidable wall segments | -| `SceneWallPlane` | Single wall plane primitive | -| `SceneCollisionSphere` | Invisible collision sphere for interaction zones | -| `SceneWallPointPreview` | Editor helper: visualises wall boundary points | -| `SceneTransitions` | Renders scene exit/entry portals from `GameSceneTransition[]` | -| `computeWallSegments` | Pure function: converts wall points → `WallSegment[]` | +| `SceneGround`, `SceneWalls`, `SceneWallPlane` | Ground and collidable walls | +| `SceneBackgroundPlane`, `CameraController`, `CameraFitHeight` | Background and fixed camera | +| `SceneTransitions` | Renders transition zones from `GameSceneTransition[]` | +| `SceneDropTargets`, `PlacedSceneItems` | Inventory drop targets and items placed in the scene | +| `computeWallSegments` | Pure function: converts walls → `WallSegment[]` | ### Sprite | Export | Description | |--------|-------------| -| `DavidSprite` | Billboarded 2D sprite with depth-based scale and animation clips | -| `buildSpeakingAnimation` | Utility: builds lip-sync animation from a dialog entry | -| `SpeechBubble` | In-world speech bubble anchored to a 3D position | +| `CharacterSprite` | Billboarded sprite driven by a `CharacterDefinition` (clips per direction, optional speaking clip) | +| `DavidSprite` | **Deprecated** — use `CharacterSprite` (also the `clips.ts` exports) | +| `SpeechBubble` | In-world speech bubble | ### Hooks | Export | Description | |--------|-------------| -| `usePlayerWalkAnimation` | Drives walk/idle animation clips on `DavidSprite` | -| `useClickToMoveController` | Ground-click → pathfinding → movement commands | +| `useGameState`, `useGameActions` | Read `GameState` / get `GameActions` from React | +| `useSceneRuntime` | Scene seeding and optional scene-id persistence | +| `useTransitionSystem` | Scene transitions with fade and an optional `canLeaveScene` rule | +| `useInventoryRuntime` | Inventory drag/drop, pick-up, initial placed items, `onSceneEnter` | +| `useAudioSystem`, `attachAudioSystem` | Connect an `AudioPort` to runtime events (`attachAudioSystem` has no React) | +| `usePlayerWalkAnimation`, `useClickToMoveController` | Walk animation and ground-click movement | | `useKeyboardMovementInput` | WASD / arrow-key input state | -| `useAudioSystem` | Connects `IAudioPort` to Web Audio API | -| `useI18n` | Access `t()` translator and current locale from a component | -| `useLocaleDetection` | Detects browser locale and writes it to the i18n store | +| `useI18n`, `useLocaleDetection` | Translator access and locale detection | ### Port adapters | Export | Description | |--------|-------------| -| `useR3FGameLoop` | `IGameLoopPort` implementation — delegates to R3F `useFrame` | -| `WebKeyboardInput` | `IInputPort` implementation — browser `KeyboardEvent` listener | +| `useR3FGameLoop` | `GameLoopPort` implementation — delegates to R3F `useFrame` | +| `WebKeyboardInput` | `InputPort` implementation — browser `KeyboardEvent` listener | -### i18n components +### Narrative (0.6.0, unreleased) | Export | Description | |--------|-------------| -| `I18nProvider` | Context provider that initialises the i18n store | -| `LocaleSwitcher` | Headless locale picker (bring your own styles) | +| `SceneHotspots`, `useHotspotInteractions`, `VerbMenu` | Clickable hotspots with a verb menu | +| `SceneNpcs`, `NpcSprite` | NPCs drawn as sprites; pass their characters in the `characters` prop of `GameViewport` | +| `DialogueChoices`, `useDialogue` | Conversation choices UI and its hook | + +Other new `GameViewport` props: `verbMenu`, `dialogueChoices`, `noActionDialogKey`. The advanced callbacks `canLeaveScene`, `onSceneEnter` and `getInitialPlacedItems` keep working; prefer the declarative scene data. See the [authoring guide](https://github.com/DanielMartinezSebastian/pointclick-engine/blob/main/docs/authoring/README.md). + +## Known limitations + +- Doors are not part of the engine (the monorepo demo implements them). +- The scene/item registries live in `engine-core` and are module-global. ## License @@ -157,4 +149,4 @@ MIT © Daniel Martínez Sebastián ## Status -`v0.4.0` — active development. R3F is currently the only supported renderer; the engine is renderer-agnostic by design. +`v0.5.0` — active development. R3F is currently the only supported renderer; the engine is renderer-agnostic by design. diff --git a/packages/engine-renderer-r3f/dist/GameTouchSpriteRuntime.d.ts b/packages/engine-renderer-r3f/dist/GameTouchSpriteRuntime.d.ts deleted file mode 100644 index e8d5283..0000000 --- a/packages/engine-renderer-r3f/dist/GameTouchSpriteRuntime.d.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { type GameCharacterName } from "./sprite/clips"; -import { type RuntimeEventHandler, type GameSceneWall, type WallToolMode } from "@pointclick-engine/engine-core"; -export declare function GameTouchSpriteRuntime({ activeCharacter, debug, showDebugGround, showDebugWalls, showPlayerCollider, wallOpacityMode, wallInteractionsEnabled, wallToolMode, wallPointResetSignal, speechText, speechVisible, speechTrigger, speechCharsPerSecond, onSpeechLetterSound, onBoundaryHit, onSpeechDismiss, onRuntimeEvent, getMobileInput, addWallWithData, getPhrase, selectedWallIndex, onSelectWall, updateSelectedWall, disableClickToMove, getEffectiveClickGoal, }: { - activeCharacter: GameCharacterName; - debug: boolean; - showDebugGround: boolean; - showDebugWalls: boolean; - /** Draws a wireframe over the player's CuboidCollider for inspection. */ - showPlayerCollider?: boolean; - /** Render mode for debug walls. `wireframe` (default) o `opaque` (sólidos). */ - wallOpacityMode?: "wireframe" | "opaque"; - /** - * When false, all wall meshes (wireframes + resize handles) ignore pointer - * events. Used while the camera is in `free` mode so OrbitControls drag - * doesn't pick up scene elements. - */ - wallInteractionsEnabled?: boolean; - wallToolMode: WallToolMode; - wallPointResetSignal: number; - speechText: string; - speechVisible: boolean; - speechTrigger: number; - speechCharsPerSecond: number; - onSpeechLetterSound?: () => void; - onBoundaryHit: (phrase: string) => void; - onSpeechDismiss: () => void; - onRuntimeEvent?: RuntimeEventHandler; - /** - * DI: Returns current joystick/mobile input state. - * Default: no-op (always inactive). Inject `useMobileInputStore.getState` for demo. - */ - getMobileInput?: () => { - active: boolean; - x: number; - z: number; - }; - /** - * DI: Adds a wall to the scene editor store. - * Only used in debug mode. Inject from sceneEditorStore for demo. - */ - addWallWithData?: (wall: GameSceneWall) => void; - /** - * @deprecated Pre-i18n DI. The runtime never reads this prop today — the - * host computes the phrase from the `onCollide` runtime event using the - * engine i18n store (`getRandomPhrase` from `@pointclick-engine/engine-core` - * or the `useI18n` hook). Kept as an optional no-op for backward compat. - */ - getPhrase?: (key: string) => string; - /** - * DI: Currently selected wall index for debug editor. - * Inject from sceneEditorStore for demo. - */ - selectedWallIndex?: number | null; - /** - * DI: Callback to select a wall in the editor. - * Inject from sceneEditorStore for demo. - */ - onSelectWall?: (index: number) => void; - /** - * DI: Mutator for the currently selected wall. - * Required for click-and-drag move/resize to persist into scene state. - * Inject from sceneEditorStore for demo. - */ - updateSelectedWall?: (updater: (wall: GameSceneWall) => GameSceneWall) => void; - /** - * If true, clicks on the ground will not move the player. Used by the - * debug editor mode to avoid race conditions with mouse-driven edits and - * by the free-camera mode to prevent accidental pathfinding triggers. - * The point-tool path keeps working so walls can still be drawn. - */ - disableClickToMove?: boolean; - /** - * DI: optional pre-processor for click-to-move goals. Receives the - * clamped click point and the player's current position; returns a - * possibly redirected goal. Use to snap clicks that would otherwise - * route around an obstacle (e.g. a closed door) to a sensible approach - * point instead. Return `null` or `undefined` to leave the goal as-is. - */ - getEffectiveClickGoal?: (clickX: number, clickZ: number, playerX: number, playerZ: number) => { - x: number; - z: number; - } | null | undefined; -}): import("react/jsx-runtime").JSX.Element; -//# sourceMappingURL=GameTouchSpriteRuntime.d.ts.map \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/GameTouchSpriteRuntime.d.ts.map b/packages/engine-renderer-r3f/dist/GameTouchSpriteRuntime.d.ts.map deleted file mode 100644 index c5ceb0b..0000000 --- a/packages/engine-renderer-r3f/dist/GameTouchSpriteRuntime.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"GameTouchSpriteRuntime.d.ts","sourceRoot":"","sources":["../src/GameTouchSpriteRuntime.tsx"],"names":[],"mappings":"AAUA,OAAO,EAGL,KAAK,iBAAiB,EAEvB,MAAM,gBAAgB,CAAC;AAOxB,OAAO,EAAmF,KAAK,mBAAmB,EAAE,KAAK,aAAa,EAAE,KAAK,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAwElM,wBAAgB,sBAAsB,CAAC,EACrC,eAAe,EACf,KAAK,EACL,eAAe,EACf,cAAc,EACd,kBAA0B,EAC1B,eAA6B,EAC7B,uBAA8B,EAC9B,YAAY,EACZ,oBAAoB,EACpB,UAAU,EACV,aAAa,EACb,aAAa,EACb,oBAAoB,EACpB,mBAAmB,EACnB,aAAa,EACb,eAAe,EACf,cAAc,EAEd,cAAsD,EACtD,eAAe,EACf,SAAoB,EACpB,iBAAwB,EACxB,YAAY,EACZ,kBAAkB,EAClB,kBAA0B,EAC1B,qBAAqB,GACtB,EAAE;IACD,eA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G;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B;;;;;;OAMG;IACH,qBAAqB,CAAC,EAAE,CACtB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,KACZ;QAAE,CAAC,EAAE,MAAM,CAAC;QAAC,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,GAAG,SAAS,CAAC;CAClD,2CAioBA"} \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/GameTouchSpriteRuntime.js b/packages/engine-renderer-r3f/dist/GameTouchSpriteRuntime.js deleted file mode 100644 index 31ec8d1..0000000 --- a/packages/engine-renderer-r3f/dist/GameTouchSpriteRuntime.js +++ /dev/null @@ -1,555 +0,0 @@ -"use client"; -import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime"; -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { useFrame } from "@react-three/fiber"; -import { CuboidCollider, RigidBody } from "@react-three/rapier"; -import { MathUtils, Vector2, Vector3 } from "three"; -import SpeechBubble from "./SpeechBubble"; -import DavidSprite from "./sprite/DavidSprite"; -import { DAVE_IDLE_SPEAKING, GAME_CHARACTER_SPRITES, } from "./sprite/clips"; -import { buildSpeakingAnimation } from "./sprite/speakingAnimation"; -import { SceneCollisionSphere } from "./scene/SceneCollisionSphere"; -import { SceneGround } from "./scene/SceneGround"; -import { SceneWallPointPreview } from "./scene/SceneWallPointPreview"; -import { SceneWalls } from "./scene/SceneWalls"; -import { findPath, useSceneStore, emitRuntimeEvent, resolveTransitionFromClickOnCollider } from "@pointclick-engine/engine-core"; -import { usePlayerWalkAnimation } from "./hooks/usePlayerWalkAnimation"; -import { useClickToMoveController } from "./hooks/useClickToMoveController"; -import { useKeyboardMovementInput } from "./adapters/useKeyboardMovementInput"; -const VERTICAL_ANGLE_THRESHOLD = 55 * (Math.PI / 180); -const DEPTH_FAR_Z = -16; -const DEPTH_NEAR_Z = 8; -const SPRITE_MIN_SCALE = 1.4; -const SPRITE_MAX_SCALE = 2.94; -const MIN_WALL_HALF_EXTENT = 0.15; -const PLAYER_BOUND_MARGIN = 1.55; -const BOUNDARY_HIT_COOLDOWN_MS = 4000; -const CAMERA_POSITION = [0, 5.4, 25.0]; -const CAMERA_FRONT_PLAYABLE_MARGIN = 1.2; -const MOVEMENT_INPUT_DEADZONE = 0.12; -const SHOULD_LOG_STATE_TRANSITIONS = process.env.NODE_ENV !== "production"; -const DEV_DUPLICATE_RESET_WINDOW_MS = 500; -let lastRuntimeResetSnapshot = null; -function logRuntimeState(event, payload) { - if (!SHOULD_LOG_STATE_TRANSITIONS) - return; - if (typeof window !== "undefined") { - const nextEntry = { scope: "runtime", event, payload, ts: Date.now() }; - const currentTrace = (window.__gameTrace ?? []); - window.__gameTrace = [...currentTrace, nextEntry].slice(-300); - } - console.info(`[runtime-state] ${event}`, payload); -} -function applyDeadzone(value, threshold) { - return Math.abs(value) < threshold ? 0 : value; -} -function resolveAction(horizontal, vertical) { - if (horizontal === 0 && vertical === 0) - return "idle"; - const angle = Math.atan2(Math.abs(vertical), Math.abs(horizontal)); - if (angle >= VERTICAL_ANGLE_THRESHOLD) { - return vertical < 0 ? "north" : "south"; - } - return horizontal < 0 ? "west" : "east"; -} -function getWallAxes(rotationY) { - return { - axisX: new Vector2(Math.cos(rotationY), -Math.sin(rotationY)), - axisZ: new Vector2(Math.sin(rotationY), Math.cos(rotationY)), - }; -} -function projectDistance(originX, originZ, pointX, pointZ, axis) { - return (pointX - originX) * axis.x + (pointZ - originZ) * axis.y; -} -export function GameTouchSpriteRuntime({ activeCharacter, debug, showDebugGround, showDebugWalls, showPlayerCollider = false, wallOpacityMode = "wireframe", wallInteractionsEnabled = true, wallToolMode, wallPointResetSignal, speechText, speechVisible, speechTrigger, speechCharsPerSecond, onSpeechLetterSound, onBoundaryHit, onSpeechDismiss, onRuntimeEvent, -// DI props for demo-specific dependencies -getMobileInput = () => ({ active: false, x: 0, z: 0 }), addWallWithData, getPhrase = () => "", selectedWallIndex = null, onSelectWall, updateSelectedWall, disableClickToMove = false, getEffectiveClickGoal, }) { - const spriteRef = useRef(null); - const meshRef = useRef(null); - const characterBodyRef = useRef(null); - const characterColliderRef = useRef(null); - const colliderWireframeRef = useRef(null); - // Reusable vectors for per-frame collider mutation (avoids allocation in useFrame). - const colliderHalfExtentsRef = useRef(new Vector3(0.55, 0.95, 0.18)); - const colliderTranslationRef = useRef(new Vector3(0, 0, 0)); - const currentActionRef = useRef("idle"); - const currentInputModeRef = useRef("auto"); - const hadManualInputRef = useRef(false); - const lastPublishedPositionRef = useRef(null); - const lastResetRef = useRef(null); - const [action, setAction] = useState("idle"); - const [wallPointPreviewState, setWallPointPreviewState] = useState(null); - const wallInteractionRef = useRef(null); - const wallPointStartRef = useRef(null); - const lastBoundaryHitRef = useRef(0); - const lastStuckHitRef = useRef(0); - const playerSpawn = useSceneStore((s) => s.scene.playerSpawn); - const playerPosition = useSceneStore((s) => s.playerPosition); - const playerWalkingState = useSceneStore((s) => s.playerWalkingState); - // if (playerWalkingState?.isActive) { - // console.log(`[GameTouchSpriteRuntime] walk state active, points=${playerWalkingState.pathPoints.length}`); - // } - const sceneId = useSceneStore((s) => s.sceneId); - const ground = useSceneStore((s) => s.scene.ground); - const setPlayerPosition = useSceneStore((s) => s.setPlayerPosition); - const respawnSignal = useSceneStore((s) => s.respawnSignal); - // Keep a ref to walk state so the completion callback captures the latest value. - const playerWalkingStateRef = useRef(playerWalkingState); - useEffect(() => { playerWalkingStateRef.current = playerWalkingState; }, [playerWalkingState]); - // When the walk animation completes, teleport the physics body to where the - // animation actually ended (the last path point) so the sprite doesn't snap - // back to its original position. The animation follows `pathPoints`, whose - // last entry is the reachable endpoint — which may be a partial route's stop - // short of an unreachable target, so prefer it over `targetPosition`. - const handleWalkComplete = useCallback(() => { - const ws = playerWalkingStateRef.current; - const body = characterBodyRef.current; - if (!ws || !body) - return; - const end = ws.pathPoints[ws.pathPoints.length - 1] ?? ws.targetPosition; - body.setTranslation({ x: end[0], y: end[1], z: end[2] }, true); - }, []); - // Use walk animation if active, otherwise use current player position - const { animatedPosition, isWalking } = usePlayerWalkAnimation(playerPosition, playerWalkingState, undefined, handleWalkComplete); - const renderPosition = isWalking ? animatedPosition : playerPosition; - const { setRoute, cancelTarget, resolveDirection, registerProgress } = useClickToMoveController(); - const { clearPressedKeys, getKeyboardMovement } = useKeyboardMovementInput(); - const playableBounds = useMemo(() => { - const minX = ground.minX + PLAYER_BOUND_MARGIN; - const maxX = ground.maxX - PLAYER_BOUND_MARGIN; - const minZ = ground.minZ + PLAYER_BOUND_MARGIN; - const maxZByGround = ground.maxZ - PLAYER_BOUND_MARGIN; - const maxZByCamera = CAMERA_POSITION[2] - CAMERA_FRONT_PLAYABLE_MARGIN; - const maxZ = Math.min(maxZByGround, maxZByCamera); - return { - minX: Math.min(minX, maxX), - maxX: Math.max(minX, maxX), - minZ: Math.min(minZ, maxZ), - maxZ: Math.max(minZ, maxZ), - }; - }, [ground.maxX, ground.maxZ, ground.minX, ground.minZ]); - const clampToPlayableArea = useCallback((x, z) => { - return { - x: MathUtils.clamp(x, playableBounds.minX, playableBounds.maxX), - z: MathUtils.clamp(z, playableBounds.minZ, playableBounds.maxZ), - }; - }, [playableBounds.maxX, playableBounds.maxZ, playableBounds.minX, playableBounds.minZ]); - const handleClickWorld = useCallback((x, z) => { - if (wallInteractionRef.current) - return; - if (debug && wallToolMode === "points") { - const clamped = clampToPlayableArea(x, z); - const clickedPoint = new Vector2(clamped.x, clamped.z); - const startPoint = wallPointStartRef.current?.resetSignal === wallPointResetSignal - ? wallPointStartRef.current.point - : null; - if (!startPoint) { - wallPointStartRef.current = { point: clickedPoint, resetSignal: wallPointResetSignal }; - setWallPointPreviewState({ start: clickedPoint, end: clickedPoint, resetSignal: wallPointResetSignal }); - return; - } - const dx = clickedPoint.x - startPoint.x; - const dz = clickedPoint.y - startPoint.y; - const length = Math.sqrt(dx * dx + dz * dz); - if (length < MIN_WALL_HALF_EXTENT * 2) { - setWallPointPreviewState({ start: startPoint, end: clickedPoint, resetSignal: wallPointResetSignal }); - return; - } - // Default wall height matches addWall in sceneEditorStore — tall enough - // that a subsequent default opening (full-height minus a thin lintel) - // clears the character sprite's worst-case height. - const halfHeight = 4; - const halfThickness = 0.25; - const centerX = (startPoint.x + clickedPoint.x) / 2; - const centerZ = (startPoint.y + clickedPoint.y) / 2; - const rotationY = -Math.atan2(dz, dx); - addWallWithData?.({ - position: [centerX, ground.y + halfHeight, centerZ], - rotationY, - halfSize: [Math.max(MIN_WALL_HALF_EXTENT, length / 2), halfHeight, halfThickness], - }); - wallPointStartRef.current = { point: clickedPoint, resetSignal: wallPointResetSignal }; - setWallPointPreviewState({ start: clickedPoint, end: clickedPoint, resetSignal: wallPointResetSignal }); - return; - } - if (disableClickToMove) - return; - const clamped = clampToPlayableArea(x, z); - const body = characterBodyRef.current; - const scene = useSceneStore.getState().scene; - const startPosition = body?.translation() ?? { x: playerSpawn[0], z: playerSpawn[2] }; - // Check if clicked on a transition collider zone - const transitionMatch = resolveTransitionFromClickOnCollider(scene, clamped.x, clamped.z); - const clickGoal = transitionMatch ? { x: transitionMatch.position[0], z: transitionMatch.position[2] } : clamped; - // Give the host app a chance to redirect the goal. Typical use: when - // the click points past a closed door, snap to the door's approach - // point on the player's side instead of letting A* hunt for a long - // way around the wall. - const redirected = getEffectiveClickGoal?.(clickGoal.x, clickGoal.z, startPosition.x, startPosition.z); - const effectiveGoal = redirected ?? clickGoal; - // findPath returns a route to the goal, or — when the goal is unreachable — - // a partial route toward the closest reachable point (so the character - // always makes progress and never freezes against an obstacle). It only - // returns null when the player is truly trapped with nowhere to move. - const route = findPath({ - start: { x: startPosition.x, z: startPosition.z }, - goal: effectiveGoal, - bounds: playableBounds, - walls: scene.walls, - interactions: scene.interactions, - }); - if (route && route.length > 0) { - setRoute(route); - return; - } - // Truly trapped — notify the host so it can react (e.g. play a blocked sfx). - emitRuntimeEvent(onRuntimeEvent, { - type: "onCollide", - reason: "pathblocked", - position: [effectiveGoal.x, ground.y, effectiveGoal.z], - }); - }, [addWallWithData, clampToPlayableArea, debug, disableClickToMove, getEffectiveClickGoal, ground.y, onRuntimeEvent, playableBounds, playerSpawn, setRoute, wallPointResetSignal, wallToolMode]); - const stopWallInteraction = useCallback(() => { - wallInteractionRef.current = null; - }, []); - const handleStartWallMove = useCallback((index, pointX, pointZ) => { - const wall = useSceneStore.getState().scene.walls[index]; - if (!wall) - return; - wallInteractionRef.current = { - mode: "move", - index, - offsetX: pointX - wall.position[0], - offsetZ: pointZ - wall.position[2], - }; - }, []); - const handleStartWallResize = useCallback((index, handle) => { - onSelectWall?.(index); - wallInteractionRef.current = { - mode: "resize", - index, - handle, - }; - }, [onSelectWall]); - const handleHoverWorld = useCallback((x, z) => { - const interaction = wallInteractionRef.current; - if (!interaction) - return; - if (!updateSelectedWall) - return; - // Read the wall via the interaction's own index — NOT the DI - // `selectedWallIndex` prop. The latter is captured by closure and lags - // behind the store by one render cycle, so the very first `onPointerMove` - // after a click sees the stale value `null` and the drag never starts. - const sceneState = useSceneStore.getState(); - const wall = sceneState.scene.walls[interaction.index]; - if (!wall) - return; - if (interaction.mode === "move") { - const nextX = x - interaction.offsetX; - const nextZ = z - interaction.offsetZ; - updateSelectedWall((prev) => ({ - ...prev, - position: [nextX, prev.position[1], nextZ], - })); - return; - } - // resize: project the cursor onto the wall's local X (length) or Z (thickness) - // axis, halve the resulting distance from the wall's center, and clamp to - // a sane minimum. The wall's center stays fixed during resize. - const rotationY = wall.rotationY ?? 0; - const { axisX, axisZ } = getWallAxes(rotationY); - const projX = projectDistance(wall.position[0], wall.position[2], x, z, axisX); - const projZ = projectDistance(wall.position[0], wall.position[2], x, z, axisZ); - updateSelectedWall((prev) => { - const halfSize = [...prev.halfSize]; - switch (interaction.handle) { - case "x+": - halfSize[0] = Math.max(MIN_WALL_HALF_EXTENT, projX); - break; - case "x-": - halfSize[0] = Math.max(MIN_WALL_HALF_EXTENT, -projX); - break; - case "z+": - halfSize[2] = Math.max(MIN_WALL_HALF_EXTENT, projZ); - break; - case "z-": - halfSize[2] = Math.max(MIN_WALL_HALF_EXTENT, -projZ); - break; - } - return { ...prev, halfSize }; - }); - }, [updateSelectedWall]); - const handleHoverPointWallTool = useCallback((x, z) => { - if (!debug || wallToolMode !== "points") - return; - const startPoint = wallPointStartRef.current?.resetSignal === wallPointResetSignal - ? wallPointStartRef.current.point - : null; - if (!startPoint) - return; - const clamped = clampToPlayableArea(x, z); - setWallPointPreviewState({ - start: startPoint, - end: new Vector2(clamped.x, clamped.z), - resetSignal: wallPointResetSignal, - }); - }, [clampToPlayableArea, debug, wallPointResetSignal, wallToolMode]); - const characterClips = useMemo(() => GAME_CHARACTER_SPRITES[activeCharacter], [activeCharacter]); - const characterAnimations = useMemo(() => [...Object.values(characterClips), DAVE_IDLE_SPEAKING], [characterClips]); - const activeAnimation = useMemo(() => speechVisible && action === "idle" - ? buildSpeakingAnimation(speechTrigger, speechCharsPerSecond) - : characterClips[action], [speechVisible, action, characterClips, speechTrigger, speechCharsPerSecond]); - useEffect(() => { - const body = characterBodyRef.current; - if (!body) - return; - const spawn = useSceneStore.getState().scene.playerSpawn; - const previousReset = lastResetRef.current; - const reason = !previousReset - ? "initial-mount" - : previousReset.sceneId !== sceneId - ? "scene-change" - : "respawn"; - logRuntimeState("player-reset", { - reason, - sceneId, - respawnSignal, - spawn, - }); - const now = Date.now(); - const duplicateDevMountReset = SHOULD_LOG_STATE_TRANSITIONS - && (reason === "initial-mount" || reason === "respawn") - && lastRuntimeResetSnapshot != null - && now - lastRuntimeResetSnapshot.at < DEV_DUPLICATE_RESET_WINDOW_MS - && lastRuntimeResetSnapshot.sceneId === sceneId - && lastRuntimeResetSnapshot.respawnSignal === respawnSignal - && lastRuntimeResetSnapshot.spawn[0] === spawn[0] - && lastRuntimeResetSnapshot.spawn[1] === spawn[1] - && lastRuntimeResetSnapshot.spawn[2] === spawn[2]; - if (duplicateDevMountReset) { - logRuntimeState("player-reset-skipped", { - reason: "duplicate-dev-reset", - originalReason: reason, - sceneId, - respawnSignal, - spawn, - }); - lastResetRef.current = { sceneId, respawnSignal }; - return; - } - body.setTranslation({ x: spawn[0], y: spawn[1], z: spawn[2] }, true); - body.setLinvel({ x: 0, y: 0, z: 0 }, true); - cancelTarget(); - clearPressedKeys(); - setPlayerPosition([spawn[0], spawn[1], spawn[2]]); - lastPublishedPositionRef.current = { x: spawn[0], y: spawn[1], z: spawn[2] }; - lastResetRef.current = { sceneId, respawnSignal }; - lastRuntimeResetSnapshot = { - sceneId, - respawnSignal, - spawn: [spawn[0], spawn[1], spawn[2]], - at: now, - }; - }, [cancelTarget, clearPressedKeys, sceneId, respawnSignal, setPlayerPosition]); - useEffect(() => { - window.addEventListener("pointerup", stopWallInteraction); - return () => { - window.removeEventListener("pointerup", stopWallInteraction); - }; - }, [stopWallInteraction]); - useFrame((_, delta) => { - const body = characterBodyRef.current; - if (!body) { - return; - } - const { moveLeft, moveRight, moveUp, moveDown, anyKeyPressed } = getKeyboardMovement(); - const joystick = getMobileInput(); - // Block input during walk animation - const inputBlocked = isWalking; - const manualInputActive = (anyKeyPressed || joystick.active) && !inputBlocked; - const nextInputMode = joystick.active - ? "joystick" - : anyKeyPressed - ? "keyboard" - : "auto"; - if (currentInputModeRef.current !== nextInputMode) { - logRuntimeState("input-mode-change", { - from: currentInputModeRef.current, - to: nextInputMode, - sceneId, - }); - currentInputModeRef.current = nextInputMode; - } - if (manualInputActive && !hadManualInputRef.current) { - cancelTarget(); - logRuntimeState("click-move-cancelled", { - reason: "manual-input", - inputMode: nextInputMode, - sceneId, - }); - } - hadManualInputRef.current = manualInputActive; - let horizontal = 0; - let vertical = 0; - // During walk animation, ignore all input (joystick, keyboard, auto-move) - if (!inputBlocked) { - if (joystick.active) { - horizontal = joystick.x; - vertical = joystick.z; - } - else if (anyKeyPressed) { - horizontal = Number(moveRight) - Number(moveLeft); - vertical = Number(moveDown) - Number(moveUp); - } - else { - const currentPosition = body.translation(); - const autoMove = resolveDirection(currentPosition.x, currentPosition.z, delta, manualInputActive); - horizontal = autoMove.horizontal; - vertical = autoMove.vertical; - if (autoMove.snapToTarget) { - body.setTranslation({ - x: autoMove.snapToTarget.x, - y: currentPosition.y, - z: autoMove.snapToTarget.z, - }, true); - } - } - } - horizontal = applyDeadzone(horizontal, MOVEMENT_INPUT_DEADZONE); - vertical = applyDeadzone(vertical, MOVEMENT_INPUT_DEADZONE); - // During walk animation, calculate direction from current to target position - let nextAction; - if (isWalking && playerWalkingState?.targetPosition) { - const currentPos = [animatedPosition[0], animatedPosition[2]]; - const targetPos = [playerWalkingState.targetPosition[0], playerWalkingState.targetPosition[2]]; - const dx = targetPos[0] - currentPos[0]; - const dz = targetPos[1] - currentPos[1]; - nextAction = resolveAction(dx, dz); - } - else { - nextAction = resolveAction(horizontal, vertical); - } - if (currentActionRef.current !== nextAction) { - logRuntimeState("action-change", { - from: currentActionRef.current, - to: nextAction, - inputMode: currentInputModeRef.current, - sceneId, - }); - currentActionRef.current = nextAction; - setAction(nextAction); - } - const speed = 7; - const currentVelocity = body.linvel(); - const verticalSpeed = vertical !== 0 ? speed * 3 : speed; - const targetVelocity = { - x: horizontal * speed, - y: currentVelocity.y, - z: vertical * verticalSpeed, - }; - if (horizontal === 0 && vertical === 0) { - body.setLinvel({ x: 0, y: currentVelocity.y, z: 0 }, true); - } - else { - body.setLinvel(targetVelocity, true); - } - const currentPosition = body.translation(); - const clampedPosition = clampToPlayableArea(currentPosition.x, currentPosition.z); - const wasClampedX = clampedPosition.x !== currentPosition.x; - const wasClampedZ = clampedPosition.z !== currentPosition.z; - if (wasClampedX || wasClampedZ) { - body.setTranslation({ x: clampedPosition.x, y: currentPosition.y, z: clampedPosition.z }, true); - const vel = body.linvel(); - body.setLinvel({ - x: wasClampedX - ? (currentPosition.x > clampedPosition.x ? Math.min(0, vel.x) : Math.max(0, vel.x)) - : vel.x, - y: vel.y, - z: wasClampedZ - ? (currentPosition.z > clampedPosition.z ? Math.min(0, vel.z) : Math.max(0, vel.z)) - : vel.z, - }, true); - const now = performance.now(); - if (now - lastBoundaryHitRef.current > BOUNDARY_HIT_COOLDOWN_MS) { - lastBoundaryHitRef.current = now; - emitRuntimeEvent(onRuntimeEvent, { - type: "onCollide", - reason: "boundary", - position: [clampedPosition.x, currentPosition.y, clampedPosition.z], - }); - } - } - const safePosition = body.translation(); - const { stuck } = registerProgress(safePosition.x, safePosition.z, delta, manualInputActive); - if (stuck) { - const vel = body.linvel(); - body.setLinvel({ x: 0, y: vel.y, z: 0 }, true); - // Cancel the route so the character doesn't keep trying to reach an - // unreachable destination (e.g. blocked by a wall with no valid path). - cancelTarget(); - const now = performance.now(); - if (now - lastStuckHitRef.current > BOUNDARY_HIT_COOLDOWN_MS) { - lastStuckHitRef.current = now; - emitRuntimeEvent(onRuntimeEvent, { - type: "onCollide", - reason: "stuck", - position: [safePosition.x, safePosition.y, safePosition.z], - }); - } - } - const depthFactor = MathUtils.clamp(MathUtils.inverseLerp(DEPTH_FAR_Z, DEPTH_NEAR_Z, safePosition.z), 0, 1); - const roundedX = Number(safePosition.x.toFixed(2)); - const roundedY = Number(safePosition.y.toFixed(2)); - const roundedZ = Number(safePosition.z.toFixed(2)); - const lastLogged = lastPublishedPositionRef.current; - if (!lastLogged || lastLogged.x !== roundedX || lastLogged.y !== roundedY || lastLogged.z !== roundedZ) { - lastPublishedPositionRef.current = { x: roundedX, y: roundedY, z: roundedZ }; - setPlayerPosition([roundedX, roundedY, roundedZ]); - emitRuntimeEvent(onRuntimeEvent, { - type: "onMove", - position: [roundedX, roundedY, roundedZ], - action: nextAction, - }); - } - const spriteScale = MathUtils.lerp(SPRITE_MIN_SCALE, SPRITE_MAX_SCALE, depthFactor); - if (meshRef.current) { - const flipX = action === "west" ? -1 : 1; - meshRef.current.scale.set(spriteScale * flipX, spriteScale, 1); - meshRef.current.position.y = spriteScale - 0.95; - } - // The player sprite plane is `planeHeight=2` units tall, scaled by - // `spriteScale` and offset to keep its feet at local Y=-0.95. Match the - // physics collider to that exact box so the player can't slip through - // openings that visually wouldn't let them past. - // bottom (local Y) = -0.95 (foot, fixed) - // top (local Y) = 2 * spriteScale - 0.95 - // halfY = spriteScale - // center = spriteScale - 0.95 - const collider = characterColliderRef.current; - if (collider) { - colliderHalfExtentsRef.current.set(0.55, spriteScale, 0.18); - collider.setHalfExtents(colliderHalfExtentsRef.current); - colliderTranslationRef.current.set(0, spriteScale - 0.95, 0); - collider.setTranslationWrtParent(colliderTranslationRef.current); - } - if (colliderWireframeRef.current) { - colliderWireframeRef.current.scale.set(1, spriteScale, 1); - colliderWireframeRef.current.position.y = spriteScale - 0.95; - } - }); - const wallPointPreview = debug && wallToolMode === "points" && wallPointPreviewState?.resetSignal === wallPointResetSignal - ? wallPointPreviewState - : null; - return (_jsxs(_Fragment, { children: [_jsx(SceneGround, { onClickWorld: handleClickWorld, onHoverWorld: debug - ? (x, z) => { - handleHoverWorld(x, z); - handleHoverPointWallTool(x, z); - } - : undefined, debug: debug && showDebugGround, depthNearZ: DEPTH_NEAR_Z, depthFarZ: DEPTH_FAR_Z }), _jsx(SceneWalls, { debug: debug && showDebugWalls, opacityMode: wallOpacityMode, interactionsEnabled: wallInteractionsEnabled, onStartWallMove: handleStartWallMove, onStartWallResize: handleStartWallResize, selectedWallIndex: selectedWallIndex, onSelectWall: onSelectWall }), debug && wallToolMode === "points" && (_jsx(SceneWallPointPreview, { preview: wallPointPreview, groundY: ground.y })), _jsx(SceneCollisionSphere, {}), _jsxs(RigidBody, { ref: characterBodyRef, type: "dynamic", colliders: false, position: renderPosition, gravityScale: 1.2, linearDamping: 7, angularDamping: 20, ccd: true, enabledRotations: [false, false, false], children: [_jsx(CuboidCollider, { ref: characterColliderRef, args: [0.55, 0.95, 0.18], friction: 2.2, restitution: 0 }), debug && showPlayerCollider && ( - // box base height = 2; the useFrame above scales Y to `spriteScale` - // and offsets Y position so the wireframe exactly mirrors the - // physics collider (whose halfY is also set to `spriteScale`). - _jsxs("mesh", { ref: colliderWireframeRef, raycast: () => null, children: [_jsx("boxGeometry", { args: [1.1, 2, 0.36] }), _jsx("meshBasicMaterial", { color: "#00ffff", wireframe: true, transparent: true, opacity: 0.85 })] })), _jsx(DavidSprite, { ref: spriteRef, meshRef: meshRef, animation: activeAnimation, preloadAnimations: characterAnimations, scale: [SPRITE_MIN_SCALE, SPRITE_MIN_SCALE, 1], isPaused: false }), _jsx(SpeechBubble, { text: speechText, visible: speechVisible, trigger: speechTrigger, charsPerSecond: speechCharsPerSecond, onDismiss: onSpeechDismiss, onLetterRevealed: onSpeechLetterSound }, speechTrigger)] })] })); -} -//# sourceMappingURL=GameTouchSpriteRuntime.js.map \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/GameTouchSpriteRuntime.js.map b/packages/engine-renderer-r3f/dist/GameTouchSpriteRuntime.js.map deleted file mode 100644 index e63e54b..0000000 --- a/packages/engine-renderer-r3f/dist/GameTouchSpriteRuntime.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"GameTouchSpriteRuntime.js","sourceRoot":"","sources":["../src/GameTouchSpriteRuntime.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAC1E,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,SAAS,EAAwB,MAAM,qBAAqB,CAAC;AAEtF,OAAO,EAAE,SAAS,EAAQ,OAAO,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AAE1D,OAAO,YAAY,MAAM,gBAAgB,CAAC;AAC1C,OAAO,WAAuC,MAAM,sBAAsB,CAAC;AAC3E,OAAO,EACL,kBAAkB,EAClB,sBAAsB,GAGvB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,sBAAsB,EAAE,MAAM,4B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,EAAE,cAAc,EACxB,YAAY,EAAE,GAAG,EACjB,aAAa,EAAE,CAAC,EAChB,cAAc,EAAE,EAAE,EAClB,GAAG,QACH,gBAAgB,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,aAEvC,KAAC,cAAc,IACb,GAAG,EAAE,oBAAoB,EACzB,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,EACxB,QAAQ,EAAE,GAAG,EACb,WAAW,EAAE,CAAC,GACd,EACD,KAAK,IAAI,kBAAkB,IAAI;oBAC9B,oEAAoE;oBACpE,8DAA8D;oBAC9D,+DAA+D;oBAC/D,gBAAM,GAAG,EAAE,oBAAoB,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI,aAClD,sBAAa,IAAI,EAAE,CAAC,GAAG,EAAE,CAAC,EAAE,IAAI,CAAC,GAAI,EACrC,4BAAmB,KAAK,EAAC,SAAS,EAAC,SAAS,QAAC,WAAW,QAAC,OAAO,EAAE,IAAI,GAAI,IACrE,CACR,EACD,KAAC,WAAW,IACV,GAAG,EAAE,SAAS,EACd,OAAO,EAAE,OAAO,EAChB,SAAS,EAAE,eAAe,EAC1B,iBAAiB,EAAE,mBAAmB,EACtC,KAAK,EAAE,CAAC,gBAAgB,EAAE,gBAAgB,EAAE,CAAC,CAAC,EAC9C,QAAQ,EAAE,KAAK,GACf,EACF,KAAC,YAAY,IAEX,IAAI,EAAE,UAAU,EAChB,OAAO,EAAE,aAAa,EACtB,OAAO,EAAE,aAAa,EACtB,cAAc,EAAE,oBAAoB,EACpC,SAAS,EAAE,eAAe,EAC1B,gBAAgB,EAAE,mBAAmB,IANhC,aAAa,CAOlB,IACQ,IACX,CACJ,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/SpeechBubble.d.ts b/packages/engine-renderer-r3f/dist/SpeechBubble.d.ts deleted file mode 100644 index 2bb1221..0000000 --- a/packages/engine-renderer-r3f/dist/SpeechBubble.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -type SpeechBubbleProps = { - text: string; - visible: boolean; - trigger: number; - charsPerSecond?: number; - onDismiss?: () => void; - onLetterRevealed?: () => void; -}; -export default function SpeechBubble({ text, visible, trigger, charsPerSecond, onDismiss, onLetterRevealed, }: SpeechBubbleProps): import("react/jsx-runtime").JSX.Element | null; -export {}; -//# sourceMappingURL=SpeechBubble.d.ts.map \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/SpeechBubble.d.ts.map b/packages/engine-renderer-r3f/dist/SpeechBubble.d.ts.map deleted file mode 100644 index efe6553..0000000 --- a/packages/engine-renderer-r3f/dist/SpeechBubble.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"SpeechBubble.d.ts","sourceRoot":"","sources":["../src/SpeechBubble.tsx"],"names":[],"mappings":"AAQA,KAAK,iBAAiB,GAAG;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC;IACvB,gBAAgB,CAAC,EAAE,MAAM,IAAI,CAAC;CAC/B,CAAC;AAsDF,MAAM,CAAC,OAAO,UAAU,YAAY,CAAC,EACnC,IAAI,EACJ,OAAO,EACP,OAAO,EACP,cAAmB,EACnB,SAAS,EACT,gBAAgB,GACjB,EAAE,iBAAiB,kDA+OnB"} \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/SpeechBubble.js b/packages/engine-renderer-r3f/dist/SpeechBubble.js deleted file mode 100644 index 0993659..0000000 --- a/packages/engine-renderer-r3f/dist/SpeechBubble.js +++ /dev/null @@ -1,209 +0,0 @@ -"use client"; -import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; -import { RoundedBox, Text } from "@react-three/drei"; -import { useEffect, useMemo, useRef, useState } from "react"; -import { useSceneStore } from "@pointclick-engine/engine-core"; -const SPRITE_HALF_WIDTH_WORLD = 0.62; -const BUBBLE_GAP_WORLD = 0.22; -const DEPTH_FAR_Z = -16; -const DEPTH_NEAR_Z = 8; -const SPRITE_MIN_SCALE = 1.4; -const SPRITE_MAX_SCALE = 2.94; -const SPRITE_HALF_WIDTH_FACTOR = 0.36; -const BORDER_PADDING = 0.09; -const SPRITE_CENTER_Y_OFFSET = -0.95; -const BUBBLE_HEADROOM = -1; -const TEXT_PADDING_X = 0.2; -const TEXT_PADDING_Y = 0.16; -const FONT_SIZE = 0.2; -const LINE_HEIGHT = 1.18; -const AVG_CHAR_WIDTH_WORLD = 0.096; -const MIN_BUBBLE_WIDTH = 0.6; -const MAX_BUBBLE_WIDTH = 5.2; -const MIN_BUBBLE_HEIGHT = 0.45; -const MAX_BUBBLE_HEIGHT = 3.8; -const MS_PER_WORD_READ = 286; -const MIN_READ_MS = 2080; -const MAX_READ_MS = 10400; -function clamp(value, min, max) { - return Math.max(min, Math.min(max, value)); -} -function lerp(start, end, t) { - return start + (end - start) * t; -} -function wrapParagraphByWords(paragraph, maxCharsPerLine) { - const words = paragraph.trim().split(/\s+/).filter(Boolean); - if (words.length === 0) - return [""]; - const lines = []; - let currentLine = words[0]; - for (let index = 1; index < words.length; index += 1) { - const candidate = `${currentLine} ${words[index]}`; - if (candidate.length <= maxCharsPerLine) { - currentLine = candidate; - } - else { - lines.push(currentLine); - currentLine = words[index]; - } - } - lines.push(currentLine); - return lines; -} -export default function SpeechBubble({ text, visible, trigger, charsPerSecond = 30, onDismiss, onLetterRevealed, }) { - const playerPosition = useSceneStore((state) => state.playerPosition); - const ground = useSceneStore((state) => state.scene.ground); - const normalizedText = useMemo(() => text.trim(), [text]); - const [displayedText, setDisplayedText] = useState(""); - const dismissTimerRef = useRef(null); - const skipTypingRef = useRef(null); - // ── Layout estático: calculado UNA vez por diálogo (dep: normalizedText) ── - const { bubbleWidth, textMaxWidth, fullBubbleHeight, wrappedText } = useMemo(() => { - const fullText = normalizedText.length > 0 ? normalizedText : " "; - const totalChars = Math.max(1, fullText.length); - const targetCPL = clamp(Math.round(Math.sqrt(totalChars) * 2.4), 18, 36); - const paragraphs = fullText.split("\n"); - const wrappedFull = paragraphs.flatMap((p) => p.trim().length === 0 ? [""] : wrapParagraphByWords(p, targetCPL)); - const longestChars = Math.max(1, ...wrappedFull.map((l) => l.length)); - const rawTextWidth = clamp(longestChars * AVG_CHAR_WIDTH_WORLD, MIN_BUBBLE_WIDTH - TEXT_PADDING_X * 2, MAX_BUBBLE_WIDTH - TEXT_PADDING_X * 2); - const bw = clamp(rawTextWidth + TEXT_PADDING_X * 2, MIN_BUBBLE_WIDTH, MAX_BUBBLE_WIDTH); - const fullLineCount = Math.max(1, wrappedFull.length); - const fbh = clamp(fullLineCount * FONT_SIZE * LINE_HEIGHT + TEXT_PADDING_Y * 2, MIN_BUBBLE_HEIGHT, MAX_BUBBLE_HEIGHT); - return { - bubbleWidth: bw, - textMaxWidth: bw - TEXT_PADDING_X * 2, - fullBubbleHeight: fbh, - wrappedText: wrappedFull.join("\n"), - }; - }, [normalizedText]); - // ── Efecto de tipeo ──────────────────────────────────────────────────────── - useEffect(() => { - if (!visible || wrappedText.length === 0) - return; - let index = 0; - let charsSinceLastSound = 0; - const msPerChar = Math.max(14, Math.floor(1000 / Math.max(1, charsPerSecond))); - const charsPerSound = Math.max(1, Math.round(charsPerSecond / 8)); - const timerHolder = { current: null }; - const startDismissTimer = () => { - if (onDismiss) { - const wordCount = normalizedText.trim().split(/\s+/).filter(Boolean).length; - const readMs = clamp(wordCount * MS_PER_WORD_READ, MIN_READ_MS, MAX_READ_MS); - dismissTimerRef.current = globalThis.setTimeout(onDismiss, readMs); - } - }; - skipTypingRef.current = () => { - if (timerHolder.current !== null) { - globalThis.clearInterval(timerHolder.current); - timerHolder.current = null; - } - setDisplayedText(wrappedText); - skipTypingRef.current = null; - startDismissTimer(); - }; - timerHolder.current = globalThis.setInterval(() => { - index += 1; - const newChar = wrappedText[index - 1]; - setDisplayedText(wrappedText.slice(0, index)); - if (onLetterRevealed && newChar && newChar !== " " && newChar !== "\n") { - charsSinceLastSound += 1; - if (charsSinceLastSound >= charsPerSound) { - charsSinceLastSound = 0; - onLetterRevealed(); - } - } - if (index >= wrappedText.length) { - globalThis.clearInterval(timerHolder.current); - timerHolder.current = null; - skipTypingRef.current = null; - startDismissTimer(); - } - }, msPerChar); - return () => { - if (timerHolder.current !== null) { - globalThis.clearInterval(timerHolder.current); - timerHolder.current = null; - } - skipTypingRef.current = null; - if (dismissTimerRef.current !== null) { - globalThis.clearTimeout(dismissTimerRef.current); - dismissTimerRef.current = null; - } - }; - }, [charsPerSecond, wrappedText, normalizedText, onDismiss, onLetterRevealed, trigger, visible]); - const shouldShowLeft = useMemo(() => { - const worldEdgePadding = 0.9; - const spaceLeft = playerPosition[0] - ground.minX - worldEdgePadding; - const spaceRight = ground.maxX - playerPosition[0] - worldEdgePadding; - return spaceLeft > spaceRight; - }, [ground.maxX, ground.minX, playerPosition]); - const depthFactor = useMemo(() => { - return clamp((playerPosition[2] - DEPTH_FAR_Z) / (DEPTH_NEAR_Z - DEPTH_FAR_Z), 0, 1); - }, [playerPosition]); - const spriteScale = useMemo(() => { - return lerp(SPRITE_MIN_SCALE, SPRITE_MAX_SCALE, depthFactor); - }, [depthFactor]); - // ── Alto dinámico: displayedText ya tiene \n → solo contar líneas ───────── - const bubbleHeight = useMemo(() => { - const lineCount = Math.max(1, displayedText.split("\n").length); - const textHeight = lineCount * FONT_SIZE * LINE_HEIGHT; - return clamp(textHeight + TEXT_PADDING_Y * 2, MIN_BUBBLE_HEIGHT, MAX_BUBBLE_HEIGHT); - }, [displayedText]); - // Belt-and-braces guarantee for "dialog must always be readable, even when - // a wall texture would otherwise cover it": - // - drei's RoundedBox / Text wrap their own meshes and may not always - // forward `renderOrder` / material depth flags through JSX shorthand. - // - We traverse the bubble group on every render where the bubble is - // visible and force every Mesh + material to use a very late render - // order with depth tests disabled. - // - // NOTE: useRef and useEffect MUST live above any early `return null` so - // React always counts the same number of hooks per render. - const BUBBLE_RENDER_ORDER = 20000; - const bubbleGroupRef = useRef(null); - useEffect(() => { - if (!visible) - return; - const root = bubbleGroupRef.current; - if (!root) - return; - root.traverse((object) => { - const mesh = object; - if (!mesh.isMesh) - return; - mesh.renderOrder = BUBBLE_RENDER_ORDER; - const material = mesh.material; - if (Array.isArray(material)) { - for (const m of material) { - m.depthTest = false; - m.depthWrite = false; - m.transparent = true; - m.needsUpdate = true; - } - } - else if (material) { - material.depthTest = false; - material.depthWrite = false; - material.transparent = true; - material.needsUpdate = true; - } - }); - }, [visible, displayedText, bubbleWidth, bubbleHeight]); - if (!visible || normalizedText.length === 0) { - return null; - } - const spriteHalfWidthWorld = Math.max(SPRITE_HALF_WIDTH_WORLD, spriteScale * SPRITE_HALF_WIDTH_FACTOR); - const sideOffset = spriteHalfWidthWorld + BUBBLE_GAP_WORLD; - const offsetX = shouldShowLeft ? -sideOffset : sideOffset; - const offsetY = (2 * spriteScale) + SPRITE_CENTER_Y_OFFSET + BUBBLE_HEADROOM; - const bubbleCenterX = shouldShowLeft - ? offsetX - bubbleWidth / 2 - : offsetX + bubbleWidth / 2; - const arrowBaseX = shouldShowLeft ? offsetX + 0.07 : offsetX - 0.07; - const arrowRotationZ = shouldShowLeft ? -Math.PI / 2 : Math.PI / 2; - return (_jsxs("group", { ref: bubbleGroupRef, position: [0, offsetY, 0], onPointerDown: (e) => { - e.stopPropagation(); - skipTypingRef.current?.(); - }, children: [_jsxs("group", { position: [bubbleCenterX, -bubbleHeight / 2, 0.03], children: [_jsx(RoundedBox, { args: [1, 1, 0.02], scale: [bubbleWidth + BORDER_PADDING, bubbleHeight + BORDER_PADDING, 1], radius: 0.14, smoothness: 4, position: [0, 0, -0.003], renderOrder: BUBBLE_RENDER_ORDER, children: _jsx("meshBasicMaterial", { color: "#ffffff", toneMapped: false, depthTest: false }) }), _jsx(RoundedBox, { args: [1, 1, 0.018], scale: [bubbleWidth, bubbleHeight, 1], radius: 0.12, smoothness: 4, position: [0, 0, 0], renderOrder: BUBBLE_RENDER_ORDER + 1, children: _jsx("meshBasicMaterial", { color: "#ffffff", toneMapped: false, depthTest: false }) }), _jsx(Text, { position: [-(bubbleWidth / 2) + TEXT_PADDING_X, 0, 0.012], color: "#121212", anchorX: "left", anchorY: "middle", maxWidth: textMaxWidth, lineHeight: LINE_HEIGHT, fontSize: FONT_SIZE, textAlign: "left", outlineWidth: 0.005, outlineColor: "#ffffff", renderOrder: BUBBLE_RENDER_ORDER + 2, "material-depthTest": false, children: displayedText })] }), _jsxs("mesh", { position: [arrowBaseX, -fullBubbleHeight * 0.3, 0.027], rotation: [0, 0, arrowRotationZ], renderOrder: BUBBLE_RENDER_ORDER, children: [_jsx("coneGeometry", { args: [0.16, 0.27, 3] }), _jsx("meshBasicMaterial", { color: "#ffffff", toneMapped: false, depthTest: false })] }), _jsxs("mesh", { position: [arrowBaseX, -fullBubbleHeight * 0.3, 0.028], rotation: [0, 0, arrowRotationZ], renderOrder: BUBBLE_RENDER_ORDER + 1, children: [_jsx("coneGeometry", { args: [0.13, 0.22, 3] }), _jsx("meshBasicMaterial", { color: "#ffffff", toneMapped: false, depthTest: false })] })] })); -} -//# sourceMappingURL=SpeechBubble.js.map \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/SpeechBubble.js.map b/packages/engine-renderer-r3f/dist/SpeechBubble.js.map deleted file mode 100644 index 9b0ad83..0000000 --- a/packages/engine-renderer-r3f/dist/SpeechBubble.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"SpeechBubble.js","sourceRoot":"","sources":["../src/SpeechBubble.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAG7D,OAAO,EAAE,aAAa,EAAE,MAA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AC,SAAS,EAAC,UAAU,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,GAAI,IACrE,IACD,CACT,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/adapters/gameLoopR3F.d.ts b/packages/engine-renderer-r3f/dist/adapters/gameLoopR3F.d.ts deleted file mode 100644 index 40ea633..0000000 --- a/packages/engine-renderer-r3f/dist/adapters/gameLoopR3F.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { GameLoopPort } from "@pointclick-engine/engine-core"; -/** - * R3F adapter that exposes a GameLoopPort. Must be used inside a Canvas tree. - * - * Usage: - * const loop = useR3FGameLoop(); - * useEffect(() => loop.subscribe(delta => ...), [loop]); - */ -export declare function useR3FGameLoop(): GameLoopPort; -//# sourceMappingURL=gameLoopR3F.d.ts.map \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/adapters/gameLoopR3F.d.ts.map b/packages/engine-renderer-r3f/dist/adapters/gameLoopR3F.d.ts.map deleted file mode 100644 index ffa3eb1..0000000 --- a/packages/engine-renderer-r3f/dist/adapters/gameLoopR3F.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"gameLoopR3F.d.ts","sourceRoot":"","sources":["../../src/adapters/gameLoopR3F.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAoB,YAAY,EAAe,MAAM,gCAAgC,CAAC;AAElG;;;;;;GAMG;AACH,wBAAgB,cAAc,IAAI,YAAY,CAkB7C"} \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/adapters/gameLoopR3F.js b/packages/engine-renderer-r3f/dist/adapters/gameLoopR3F.js deleted file mode 100644 index 6aa0e6f..0000000 --- a/packages/engine-renderer-r3f/dist/adapters/gameLoopR3F.js +++ /dev/null @@ -1,28 +0,0 @@ -"use client"; -import { useFrame } from "@react-three/fiber"; -import { useRef } from "react"; -/** - * R3F adapter that exposes a GameLoopPort. Must be used inside a Canvas tree. - * - * Usage: - * const loop = useR3FGameLoop(); - * useEffect(() => loop.subscribe(delta => ...), [loop]); - */ -export function useR3FGameLoop() { - const callbacksRef = useRef(new Set()); - useFrame((_state, delta) => { - for (const cb of callbacksRef.current) - cb(delta); - }); - // Stable port reference — created once, never recreated - const portRef = useRef({ - subscribe(callback) { - callbacksRef.current.add(callback); - return () => { - callbacksRef.current.delete(callback); - }; - }, - }); - return portRef.current; -} -//# sourceMappingURL=gameLoopR3F.js.map \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/adapters/gameLoopR3F.js.map b/packages/engine-renderer-r3f/dist/adapters/gameLoopR3F.js.map deleted file mode 100644 index aa34b32..0000000 --- a/packages/engine-renderer-r3f/dist/adapters/gameLoopR3F.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"gameLoopR3F.js","sourceRoot":"","sources":["../../src/adapters/gameLoopR3F.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAG/B;;;;;;GAMG;AACH,MAAM,UAAU,cAAc;IAC5B,MAAM,YAAY,GAAG,MAAM,CAAC,IAAI,GAAG,EAAoB,CAAC,CAAC;IAEzD,QAAQ,CAAC,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE;QACzB,KAAK,MAAM,EAAE,IAAI,YAAY,CAAC,OAAO;YAAE,EAAE,CAAC,KAAK,CAAC,CAAC;IACnD,CAAC,CAAC,CAAC;IAEH,wDAAwD;IACxD,MAAM,OAAO,GAAG,MAAM,CAAe;QACnC,SAAS,CAAC,QAA0B;YAClC,YAAY,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACnC,OAAO,GAAG,EAAE;gBACV,YAAY,CAAC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;YACxC,CAAC,CAAC;QACJ,CAAC;KACF,CAAC,CAAC;IAEH,OAAO,OAAO,CAAC,OAAO,CAAC;AACzB,CAAC"} \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/adapters/index.d.ts b/packages/engine-renderer-r3f/dist/adapters/index.d.ts deleted file mode 100644 index 91bfa49..0000000 --- a/packages/engine-renderer-r3f/dist/adapters/index.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export { useR3FGameLoop } from "./gameLoopR3F"; -export { WebKeyboardInput } from "./keyboardInput"; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/adapters/index.d.ts.map b/packages/engine-renderer-r3f/dist/adapters/index.d.ts.map deleted file mode 100644 index a372ce9..0000000 --- a/packages/engine-renderer-r3f/dist/adapters/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/adapters/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC"} \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/adapters/index.js b/packages/engine-renderer-r3f/dist/adapters/index.js deleted file mode 100644 index 8c53ccf..0000000 --- a/packages/engine-renderer-r3f/dist/adapters/index.js +++ /dev/null @@ -1,3 +0,0 @@ -export { useR3FGameLoop } from "./gameLoopR3F"; -export { WebKeyboardInput } from "./keyboardInput"; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/adapters/index.js.map b/packages/engine-renderer-r3f/dist/adapters/index.js.map deleted file mode 100644 index bfb4730..0000000 --- a/packages/engine-renderer-r3f/dist/adapters/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/adapters/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC"} \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/adapters/keyboardInput.d.ts b/packages/engine-renderer-r3f/dist/adapters/keyboardInput.d.ts deleted file mode 100644 index aaa9954..0000000 --- a/packages/engine-renderer-r3f/dist/adapters/keyboardInput.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -import type { InputDirection, InputPort, DirectionListener, PointerListener, InputUnsubscribe, InputPointerEvent } from "@pointclick-engine/engine-core"; -/** - * Web keyboard adapter. Listens to WASD/arrow keys and produces InputDirection. - * - * Usage: - * const kb = new WebKeyboardInput(); - * kb.attach(window); - * // later: - * kb.detach(window); - */ -export declare class WebKeyboardInput implements InputPort { - private direction; - private keys; - private dirListeners; - private ptrListeners; - private readonly onKeyDown; - private readonly onKeyUp; - attach(target: Window | HTMLElement): void; - detach(target: Window | HTMLElement): void; - onDirection(l: DirectionListener): InputUnsubscribe; - onPointer(l: PointerListener): InputUnsubscribe; - getDirection(): InputDirection; - pushPointer(event: InputPointerEvent): void; - private updateDirection; -} -//# sourceMappingURL=keyboardInput.d.ts.map \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/adapters/keyboardInput.d.ts.map b/packages/engine-renderer-r3f/dist/adapters/keyboardInput.d.ts.map deleted file mode 100644 index 9df4b5b..0000000 --- a/packages/engine-renderer-r3f/dist/adapters/keyboardInput.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"keyboardInput.d.ts","sourceRoot":"","sources":["../../src/adapters/keyboardInput.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,cAAc,EACd,SAAS,EACT,iBAAiB,EACjB,eAAe,EACf,gBAAgB,EAChB,iBAAiB,EAClB,MAAM,gCAAgC,CAAC;AAExC;;;;;;;;GAQG;AACH,qBAAa,gBAAiB,YAAW,SAAS;IAChD,OAAO,CAAC,SAAS,CAAkD;IACnE,OAAO,CAAC,IAAI,CAAqB;IACjC,OAAO,CAAC,YAAY,CAAgC;IACpD,OAAO,CAAC,YAAY,CAA8B;IAElD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAGxB;IAEF,OAAO,CAAC,QAAQ,CAAC,OAAO,CAGtB;IAEF,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,WAAW,GAAG,IAAI;IAK1C,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,WAAW,GAAG,IAAI;IAK1C,WAAW,CAAC,CAAC,EAAE,iBAAiB,GAAG,gBAAgB;IAKnD,SAAS,CAAC,CAAC,EAAE,eAAe,GAAG,gBAAgB;IAK/C,YAAY,IAAI,cAAc;IAI9B,WAAW,CAAC,KAAK,EAAE,iBAAiB,GAAG,IAAI;IAI3C,OAAO,CAAC,eAAe;CAUxB"} \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/adapters/keyboardInput.js b/packages/engine-renderer-r3f/dist/adapters/keyboardInput.js deleted file mode 100644 index 9d59b97..0000000 --- a/packages/engine-renderer-r3f/dist/adapters/keyboardInput.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Web keyboard adapter. Listens to WASD/arrow keys and produces InputDirection. - * - * Usage: - * const kb = new WebKeyboardInput(); - * kb.attach(window); - * // later: - * kb.detach(window); - */ -export class WebKeyboardInput { - constructor() { - this.direction = { horizontal: 0, vertical: 0 }; - this.keys = new Set(); - this.dirListeners = new Set(); - this.ptrListeners = new Set(); - this.onKeyDown = (e) => { - this.keys.add(e.key.toLowerCase()); - this.updateDirection(); - }; - this.onKeyUp = (e) => { - this.keys.delete(e.key.toLowerCase()); - this.updateDirection(); - }; - } - attach(target) { - target.addEventListener("keydown", this.onKeyDown); - target.addEventListener("keyup", this.onKeyUp); - } - detach(target) { - target.removeEventListener("keydown", this.onKeyDown); - target.removeEventListener("keyup", this.onKeyUp); - } - onDirection(l) { - this.dirListeners.add(l); - return () => this.dirListeners.delete(l); - } - onPointer(l) { - this.ptrListeners.add(l); - return () => this.ptrListeners.delete(l); - } - getDirection() { - return this.direction; - } - pushPointer(event) { - for (const l of this.ptrListeners) - l(event); - } - updateDirection() { - const h = (this.keys.has("a") || this.keys.has("arrowleft") ? -1 : 0) + - (this.keys.has("d") || this.keys.has("arrowright") ? 1 : 0); - const v = (this.keys.has("w") || this.keys.has("arrowup") ? -1 : 0) + - (this.keys.has("s") || this.keys.has("arrowdown") ? 1 : 0); - this.direction = { horizontal: h, vertical: v }; - for (const l of this.dirListeners) - l(this.direction); - } -} -//# sourceMappingURL=keyboardInput.js.map \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/adapters/keyboardInput.js.map b/packages/engine-renderer-r3f/dist/adapters/keyboardInput.js.map deleted file mode 100644 index 37b4804..0000000 --- a/packages/engine-renderer-r3f/dist/adapters/keyboardInput.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"keyboardInput.js","sourceRoot":"","sources":["../../src/adapters/keyboardInput.ts"],"names":[],"mappings":"AASA;;;;;;;;GAQG;AACH,MAAM,OAAO,gBAAgB;IAA7B;QACU,cAAS,GAAmB,EAAE,UAAU,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC;QAC3D,SAAI,GAAG,IAAI,GAAG,EAAU,CAAC;QACzB,iBAAY,GAAG,IAAI,GAAG,EAAqB,CAAC;QAC5C,iBAAY,GAAG,IAAI,GAAG,EAAmB,CAAC;QAEjC,cAAS,GAAG,CAAC,CAAgB,EAAE,EAAE;YAChD,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC;YACnC,IAAI,CAAC,eAAe,EAAE,CAAC;QACzB,CAAC,CAAC;QAEe,YAAO,GAAG,CAAC,CAAgB,EAAE,EAAE;YAC9C,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC;YACtC,IAAI,CAAC,eAAe,EAAE,CAAC;QACzB,CAAC,CAAC;IAwCJ,CAAC;IAtCC,MAAM,CAAC,MAA4B;QACjC,MAAM,CAAC,gBAAgB,C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AC,CAAC,CAAC;QAC9D,MAAM,CAAC,GACL,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YACzD,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAC7D,IAAI,CAAC,SAAS,GAAG,EAAE,UAAU,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,CAAC;QAChD,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,YAAY;YAAE,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACvD,CAAC;CACF"} \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/adapters/useKeyboardMovementInput.d.ts b/packages/engine-renderer-r3f/dist/adapters/useKeyboardMovementInput.d.ts deleted file mode 100644 index 3d80a76..0000000 --- a/packages/engine-renderer-r3f/dist/adapters/useKeyboardMovementInput.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -export type KeyboardMovementState = { - moveLeft: boolean; - moveRight: boolean; - moveUp: boolean; - moveDown: boolean; - anyKeyPressed: boolean; -}; -export declare function useKeyboardMovementInput(): { - clearPressedKeys: () => void; - getKeyboardMovement: () => KeyboardMovementState; -}; -//# sourceMappingURL=useKeyboardMovementInput.d.ts.map \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/adapters/useKeyboardMovementInput.d.ts.map b/packages/engine-renderer-r3f/dist/adapters/useKeyboardMovementInput.d.ts.map deleted file mode 100644 index a0e01e9..0000000 --- a/packages/engine-renderer-r3f/dist/adapters/useKeyboardMovementInput.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"useKeyboardMovementInput.d.ts","sourceRoot":"","sources":["../../src/adapters/useKeyboardMovementInput.ts"],"names":[],"mappings":"AASA,MAAM,MAAM,qBAAqB,GAAG;IAClC,QAAQ,EAAE,OAAO,CAAC;IAClB,SAAS,EAAE,OAAO,CAAC;IACnB,MAAM,EAAE,OAAO,CAAC;IAChB,QAAQ,EAAE,OAAO,CAAC;IAClB,aAAa,EAAE,OAAO,CAAC;CACxB,CAAC;AAEF,wBAAgB,wBAAwB;;+BAOM,qBAAqB;EA0ClE"} \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/adapters/useKeyboardMovementInput.js b/packages/engine-renderer-r3f/dist/adapters/useKeyboardMovementInput.js deleted file mode 100644 index 05e6d24..0000000 --- a/packages/engine-renderer-r3f/dist/adapters/useKeyboardMovementInput.js +++ /dev/null @@ -1,50 +0,0 @@ -"use client"; -import { useCallback, useEffect, useRef } from "react"; -const MOVEMENT_KEYS = new Set([ - "arrowleft", "arrowright", "arrowup", "arrowdown", - "a", "d", "w", "s", -]); -export function useKeyboardMovementInput() { - const keysPressedRef = useRef(new Set()); - const clearPressedKeys = useCallback(() => { - keysPressedRef.current.clear(); - }, []); - const getKeyboardMovement = useCallback(() => { - const pressed = keysPressedRef.current; - const moveLeft = pressed.has("arrowleft") || pressed.has("a"); - const moveRight = pressed.has("arrowright") || pressed.has("d"); - const moveUp = pressed.has("arrowup") || pressed.has("w"); - const moveDown = pressed.has("arrowdown") || pressed.has("s"); - return { - moveLeft, - moveRight, - moveUp, - moveDown, - anyKeyPressed: moveLeft || moveRight || moveUp || moveDown, - }; - }, []); - useEffect(() => { - const handleKeyDown = (event) => { - const key = event.key.toLowerCase(); - if (MOVEMENT_KEYS.has(key)) { - event.preventDefault(); - keysPressedRef.current.add(key); - } - }; - const handleKeyUp = (event) => { - const key = event.key.toLowerCase(); - if (MOVEMENT_KEYS.has(key)) { - event.preventDefault(); - keysPressedRef.current.delete(key); - } - }; - window.addEventListener("keydown", handleKeyDown, { passive: false }); - window.addEventListener("keyup", handleKeyUp, { passive: false }); - return () => { - window.removeEventListener("keydown", handleKeyDown); - window.removeEventListener("keyup", handleKeyUp); - }; - }, []); - return { clearPressedKeys, getKeyboardMovement }; -} -//# sourceMappingURL=useKeyboardMovementInput.js.map \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/adapters/useKeyboardMovementInput.js.map b/packages/engine-renderer-r3f/dist/adapters/useKeyboardMovementInput.js.map deleted file mode 100644 index a876c53..0000000 --- a/packages/engine-renderer-r3f/dist/adapters/useKeyboardMovementInput.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"useKeyboardMovementInput.js","sourceRoot":"","sources":["../../src/adapters/useKeyboardMovementInput.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAEvD,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC;IAC5B,WAAW,EAAE,YAAY,EAAE,SAAS,EAAE,WAAW;IACjD,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG;CACnB,CAAC,CAAC;AAUH,MAAM,UAAU,wBAAwB;IACtC,MAAM,cAAc,GAAG,MAAM,CAAC,IAAI,GAAG,EAAU,CAAC,CAAC;IAEjD,MAAM,gBAAgB,GAAG,WAAW,CAAC,GAAG,EAAE;QACxC,cAAc,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;IACjC,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,MAAM,mBAAmB,GAAG,WAAW,CAAC,GAA0B,EAAE;QAClE,MAAM,OAAO,GAAG,cAAc,CAAC,OAAO,CAAC;QACvC,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAC9D,MAAM,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,OAAO,CAAC,GAAG,CA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AE,CAAC,CAAC;QAElE,OAAO,GAAG,EAAE;YACV,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC;YACrD,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC,CAAC;IACJ,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,CAAC;AACnD,CAAC"} \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/components/GameCanvasCore.d.ts b/packages/engine-renderer-r3f/dist/components/GameCanvasCore.d.ts deleted file mode 100644 index d06cf9b..0000000 --- a/packages/engine-renderer-r3f/dist/components/GameCanvasCore.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -import type { ReactNode } from "react"; -export type GameCanvasCoreProps = { - /** Enable debug overlay. */ - debug?: boolean; - /** Callback for legacy runtime events (optional). */ - onRuntimeEvent?: (event: unknown) => void; - /** Content to render inside the R3F Canvas (game objects, lights, etc.). */ - children?: ReactNode; - /** Extra CSS class for the outer container div. */ - className?: string; -}; -/** - * Minimal R3F canvas shell for the engine. - * - * Provides the bare setup (gl config, sizing) without any - * demo-specific content. Library consumers use this as a starting point - * and inject their own game objects as children. - * - * The demo uses GameTouchCanvas (which has all demo content wired in). - * External consumers build their own canvas that composes GameCanvasCore. - */ -export declare function GameCanvasCore({ children, className, }: GameCanvasCoreProps): import("react/jsx-runtime").JSX.Element; -//# sourceMappingURL=GameCanvasCore.d.ts.map \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/components/GameCanvasCore.d.ts.map b/packages/engine-renderer-r3f/dist/components/GameCanvasCore.d.ts.map deleted file mode 100644 index 68cf21c..0000000 --- a/packages/engine-renderer-r3f/dist/components/GameCanvasCore.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"GameCanvasCore.d.ts","sourceRoot":"","sources":["../../src/components/GameCanvasCore.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAGvC,MAAM,MAAM,mBAAmB,GAAG;IAChC,4BAA4B;IAC5B,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,qDAAqD;IACrD,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;IAC1C,4EAA4E;IAC5E,QAAQ,CAAC,EAAE,SAAS,CAAC;IACrB,mDAAmD;IACnD,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAgB,cAAc,CAAC,EAC7B,QAAQ,EACR,SAAS,GACV,EAAE,mBAAmB,2CAmBrB"} \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/components/GameCanvasCore.js b/packages/engine-renderer-r3f/dist/components/GameCanvasCore.js deleted file mode 100644 index 5496711..0000000 --- a/packages/engine-renderer-r3f/dist/components/GameCanvasCore.js +++ /dev/null @@ -1,22 +0,0 @@ -"use client"; -import { jsx as _jsx } from "react/jsx-runtime"; -import { Canvas } from "@react-three/fiber"; -/** - * Minimal R3F canvas shell for the engine. - * - * Provides the bare setup (gl config, sizing) without any - * demo-specific content. Library consumers use this as a starting point - * and inject their own game objects as children. - * - * The demo uses GameTouchCanvas (which has all demo content wired in). - * External consumers build their own canvas that composes GameCanvasCore. - */ -export function GameCanvasCore({ children, className, }) { - return (_jsx("div", { style: { position: "relative", width: "100%", height: "100%" }, className: className, children: _jsx(Canvas, { gl: { alpha: false, antialias: true, preserveDrawingBuffer: false }, style: { - position: "absolute", - inset: 0, - width: "100%", - height: "100%", - }, children: children }) })); -} -//# sourceMappingURL=GameCanvasCore.js.map \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/components/GameCanvasCore.js.map b/packages/engine-renderer-r3f/dist/components/GameCanvasCore.js.map deleted file mode 100644 index 7316427..0000000 --- a/packages/engine-renderer-r3f/dist/components/GameCanvasCore.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"GameCanvasCore.js","sourceRoot":"","sources":["../../src/components/GameCanvasCore.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAGb,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAa5C;;;;;;;;;GASG;AACH,MAAM,UAAU,cAAc,CAAC,EAC7B,QAAQ,EACR,SAAS,GACW;IACpB,OAAO,CACL,cACE,KAAK,EAAE,EAAE,QAAQ,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,EAC9D,SAAS,EAAE,SAAS,YAEpB,KAAC,MAAM,IACL,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE,qBAAqB,EAAE,KAAK,EAAE,EACnE,KAAK,EAAE;gBACL,QAAQ,EAAE,UAAU;gBACpB,KAAK,EAAE,CAAC;gBACR,KAAK,EAAE,MAAM;gBACb,MAAM,EAAE,MAAM;aACf,YAEA,QAAQ,GACF,GACL,CACP,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/components/I18nProvider.d.ts b/packages/engine-renderer-r3f/dist/components/I18nProvider.d.ts deleted file mode 100644 index baa19fc..0000000 --- a/packages/engine-renderer-r3f/dist/components/I18nProvider.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { type ReactNode } from "react"; -import { type I18nConfig } from "@pointclick-engine/engine-core"; -export interface I18nProviderProps { - config: I18nConfig; - children: ReactNode; -} -/** - * Optional convenience wrapper: resets the i18n singleton with the given - * config at mount. Most apps just call `resetI18nStore` themselves at boot, - * but this is handy for tests and storybook stories. - */ -export declare function I18nProvider({ config, children }: I18nProviderProps): import("react/jsx-runtime").JSX.Element; -//# sourceMappingURL=I18nProvider.d.ts.map \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/components/I18nProvider.d.ts.map b/packages/engine-renderer-r3f/dist/components/I18nProvider.d.ts.map deleted file mode 100644 index f49af72..0000000 --- a/packages/engine-renderer-r3f/dist/components/I18nProvider.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"I18nProvider.d.ts","sourceRoot":"","sources":["../../src/components/I18nProvider.tsx"],"names":[],"mappings":"AAEA,OAAO,EAAa,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AAClD,OAAO,EAEL,KAAK,UAAU,EAChB,MAAM,gCAAgC,CAAC;AAExC,MAAM,WAAW,iBAAiB;IAChC,MAAM,EAAE,UAAU,CAAC;IACnB,QAAQ,EAAE,SAAS,CAAC;CACrB;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,iBAAiB,2CAOnE"} \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/components/I18nProvider.js b/packages/engine-renderer-r3f/dist/components/I18nProvider.js deleted file mode 100644 index aee976d..0000000 --- a/packages/engine-renderer-r3f/dist/components/I18nProvider.js +++ /dev/null @@ -1,18 +0,0 @@ -"use client"; -import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime"; -import { useEffect } from "react"; -import { resetI18nStore, } from "@pointclick-engine/engine-core"; -/** - * Optional convenience wrapper: resets the i18n singleton with the given - * config at mount. Most apps just call `resetI18nStore` themselves at boot, - * but this is handy for tests and storybook stories. - */ -export function I18nProvider({ config, children }) { - useEffect(() => { - resetI18nStore(config); - // No cleanup — leaving the singleton in place is fine; consumers can call - // resetI18nStore again to swap configs. - }, [config]); - return _jsx(_Fragment, { children: children }); -} -//# sourceMappingURL=I18nProvider.js.map \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/components/I18nProvider.js.map b/packages/engine-renderer-r3f/dist/components/I18nProvider.js.map deleted file mode 100644 index 46930de..0000000 --- a/packages/engine-renderer-r3f/dist/components/I18nProvider.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"I18nProvider.js","sourceRoot":"","sources":["../../src/components/I18nProvider.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAO,EAAE,SAAS,EAAkB,MAAM,OAAO,CAAC;AAClD,OAAO,EACL,cAAc,GAEf,MAAM,gCAAgC,CAAC;AAOxC;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAqB;IAClE,SAAS,CAAC,GAAG,EAAE;QACb,cAAc,CAAC,MAAM,CAAC,CAAC;QACvB,0EAA0E;QAC1E,wCAAwC;IAC1C,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;IACb,OAAO,4BAAG,QAAQ,GAAI,CAAC;AACzB,CAAC"} \ No newline at end of file diff --git a/packages/engine-renderer-r3f/dist/components/LocaleSwitcher.d.ts b/packages/engine-renderer-r3f/dist/components/LocaleSwitcher.d.ts deleted file mode 100644 index 44b4743..0000000 --- a/packages/engine-renderer-r3f/dist/components/LocaleSwitcher.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -import type { ReactNode } from "react"; -import type { Locale } from "@pointclick-engine/engine-core"; -/** Render-prop payload exposed for fully custom markup. */ -export interface LocaleSwitcherRenderOption { - locale: Locale; - isActive: boolean; - label: string; - onClick: () => void; -} -export interface LocaleSwitcherProps { - /** Visual mode for the built-in markup. Default `"buttons"`. */ - as?: "buttons" | "select"; - /** Human-readable label per locale (e.g. `{ es: "Español" }`). */ - labels?: Record; - /** - * Render-prop. When provided, the component renders nothing of its own - * and lets the caller decide markup. Receives one payload per locale. - */ - renderOption?: (opts: LocaleSwitcherRenderOption) => ReactNode; - className?: string; - /** Accessible group / select label. Default `"Language"`. */ - ariaLabel?: string; -} -/** - * Drop-in language switcher backed by the engine's i18n store. Three modes: - * - * 1. `as="buttons"` (default): one ` + ))} + + ); +} diff --git a/packages/engine-renderer-r3f/src/components/index.ts b/packages/engine-renderer-r3f/src/components/index.ts index e60c0ca..69e749f 100644 --- a/packages/engine-renderer-r3f/src/components/index.ts +++ b/packages/engine-renderer-r3f/src/components/index.ts @@ -7,6 +7,20 @@ export type { GameCanvasCoreProps } from "./GameCanvasCore"; // Sprite export { default as DavidSprite } from "../sprite/DavidSprite"; export type { DavidSpriteHandle } from "../sprite/DavidSprite"; +export { default as CharacterSprite } from "../sprite/CharacterSprite"; +export type { CharacterSpriteHandle } from "../sprite/CharacterSprite"; +export type { + CharacterClip, + CharacterDefinition, + CharacterDirection, +} from "../sprite/character"; +export { + buildFrameUrls, + selectClip, + resolveCharacterSprites, + listCharacterAnimations, + toSpriteAnimation, +} from "../sprite/character"; export * from "../sprite/clips"; export { buildSpeakingAnimation } from "../sprite/speakingAnimation"; diff --git a/packages/engine-renderer-r3f/src/hooks/attachAudioSystem.ts b/packages/engine-renderer-r3f/src/hooks/attachAudioSystem.ts new file mode 100644 index 0000000..cca58ee --- /dev/null +++ b/packages/engine-renderer-r3f/src/hooks/attachAudioSystem.ts @@ -0,0 +1,107 @@ +import { + resolveAudioEvents, + type AudioDefaultsConfig, + type AudioRulesContext, + type AudioPort, + type AudioSettingsStore, + type GameEvent, + type GameScene, + type ItemDefinition, + type GameSceneTransition, + type SceneMusicConfig, +} from "@pointclick-engine/engine-core"; + +export interface MinimalRuntime { + on(type: GameEvent["type"], handler: (e: GameEvent) => void): () => void; +} + +export interface AttachAudioSystemOpts { + runtime: MinimalRuntime; + port: AudioPort; + defaults: AudioDefaultsConfig; + scenes: Record; + items: Record; + transitions: Record; + settingsStore: AudioSettingsStore; +} + +/** + * Suscribe el puerto de audio a los eventos del runtime y sincroniza los + * settings hacia el puerto. Devuelve la función de limpieza. + * Sin dependencias de React: testeable como función normal. + */ +export function attachAudioSystem(opts: AttachAudioSystemOpts): () => void { + const { runtime, port, defaults, items, transitions, settingsStore } = opts; + + let previousMusic: SceneMusicConfig | undefined = undefined; + + const ctxFor = (): AudioRulesContext => ({ + defaults, + currentScene: undefined, + previousMusic, + items, + transitions, + }); + + const dispatchAudio = (events: GameEvent[]) => { + for (const e of events) { + if (e.type === "audio:sfxRequested") { + port.playSound({ + id: e.soundUrl, + url: e.soundUrl, + category: e.category, + volume: e.volume, + }); + } else if (e.type === "audio:musicRequested") { + port.playMusic( + { + id: e.trackUrl, + url: e.trackUrl, + category: "music", + loop: e.loop ?? true, + volume: e.volume, + }, + { fadeMs: e.fadeMs }, + ); + } else if (e.type === "audio:musicStopped") { + port.stopMusic({ fadeMs: e.fadeMs }); + } + } + }; + + const handle = (event: GameEvent) => { + const out = resolveAudioEvents(event, ctxFor()); + dispatchAudio(out); + + // Actualizar previousMusic cuando la escena cambia + if (event.type === "scene:changed") { + previousMusic = event.scene.music; + } + }; + + const subs = [ + runtime.on("scene:changed", handle), + runtime.on("item:pickedUp", handle), + runtime.on("item:dropped", handle), + runtime.on("transition:triggered", handle), + runtime.on("dialog:triggered", handle), + ]; + + // Sync inicial de settings hacia el port + const applySettings = () => { + const s = settingsStore.getState(); + port.setMuted("master", s.masterMuted); + port.setMuted("music", s.musicMuted); + port.setMuted("sfx", s.sfxMuted); + port.setVolume("master", s.masterVolume); + port.setVolume("music", s.musicVolume); + port.setVolume("sfx", s.sfxVolume); + }; + applySettings(); + const unsubSettings = settingsStore.subscribe(applySettings); + + return () => { + subs.forEach((u) => u()); + unsubSettings(); + }; +} diff --git a/packages/engine-renderer-r3f/src/hooks/dialogueLogic.ts b/packages/engine-renderer-r3f/src/hooks/dialogueLogic.ts new file mode 100644 index 0000000..b6009b0 --- /dev/null +++ b/packages/engine-renderer-r3f/src/hooks/dialogueLogic.ts @@ -0,0 +1,71 @@ +/** + * Decisiones puras de la UI de dialogo (sin React ni DOM), para poder probarlas aparte. + * + * Contrato con el core (`dialogue.ts`): un nodo sin opciones espera el cierre del bocadillo + * (`dialog:dismissed`); un nodo con opciones espera `dialogue:choose`. + */ + +/** El bocadillo no debe cerrarse solo cuando el nodo activo ofrece opciones. */ +export function shouldHoldBubble(active: boolean, choiceCount: number): boolean { + return active && choiceCount > 0; +} + +export interface ShowChoicesInput { + active: boolean; + choiceCount: number; + /** El nodo tiene linea (bocadillo). Sin linea las opciones salen de inmediato. */ + hasLine: boolean; + /** `triggerCount` del bocadillo cuya linea ya termino de escribirse (-1 si ninguno). */ + typedTrigger: number; + /** `triggerCount` actual del bocadillo. */ + triggerCount: number; +} + +/** Las opciones aparecen cuando termina de escribirse la linea del nodo (o ya, si no hay linea). */ +export function shouldShowChoices(i: ShowChoicesInput): boolean { + if (!i.active || i.choiceCount === 0) return false; + return !i.hasLine || i.typedTrigger === i.triggerCount; +} + +/** + * Que hacer cuando el bocadillo se cierra solo o por click: con dialogo activo se avanza + * por el comando del core (que emite `dialog:dismissed`); si no, solo se oculta como siempre. + */ +export function resolveSpeechDismiss(dialogueActive: boolean): "advance" | "hide" { + return dialogueActive ? "advance" : "hide"; +} + +export type ChoiceKeyAction = + | { kind: "focus"; position: number } + | { kind: "choose"; position: number } + | { kind: "none" }; + +const NONE: ChoiceKeyAction = { kind: "none" }; + +/** + * Navegacion por teclado de la lista de opciones. `current` y el resultado son posiciones + * en la lista visible (no el `index` original de la opcion). Flechas con vuelta, Inicio/Fin, + * Enter/Espacio eligen la actual, 1-9 eligen esa posicion si existe. + */ +export function navigateChoices(key: string, current: number, count: number): ChoiceKeyAction { + if (count <= 0) return NONE; + const cur = Math.min(Math.max(current, 0), count - 1); + switch (key) { + case "ArrowDown": + case "ArrowRight": + return { kind: "focus", position: (cur + 1) % count }; + case "ArrowUp": + case "ArrowLeft": + return { kind: "focus", position: (cur - 1 + count) % count }; + case "Home": + return { kind: "focus", position: 0 }; + case "End": + return { kind: "focus", position: count - 1 }; + case "Enter": + case " ": + return { kind: "choose", position: cur }; + default: + if (/^[1-9]$/.test(key) && Number(key) <= count) return { kind: "choose", position: Number(key) - 1 }; + return NONE; + } +} diff --git a/packages/engine-renderer-r3f/src/hooks/transitionRules.ts b/packages/engine-renderer-r3f/src/hooks/transitionRules.ts new file mode 100644 index 0000000..d3dcb32 --- /dev/null +++ b/packages/engine-renderer-r3f/src/hooks/transitionRules.ts @@ -0,0 +1,41 @@ +import type { GameScene, GameVec3 } from "@pointclick-engine/engine-core"; + +export type LeaveSceneTransition = { + transitionId: string; + fromSceneId: string; + targetSceneId: string; +}; + +export type LeaveSceneBlock = { text: string; dialogKey?: string }; + +/** Regla opcional del juego: `true` deja salir; un objeto bloquea y muestra ese dialogo. */ +export type CanLeaveScene = (transition: LeaveSceneTransition) => true | LeaveSceneBlock; + +/** + * Decide si la transicion puede continuar. Pura, sin React. + * Sin regla -> se puede salir. + */ +export function decideLeaveScene( + canLeaveScene: CanLeaveScene | undefined, + transition: LeaveSceneTransition, +): { allowed: true } | { allowed: false; text: string; dialogKey?: string } { + const result = canLeaveScene?.(transition) ?? true; + if (result === true) return { allowed: true }; + return { allowed: false, text: result.text, dialogKey: result.dialogKey }; +} + +/** + * Resuelve spawn y destino de caminata de la transicion usada, a partir de la + * escena de origen. Pura, sin React. + */ +export function resolveUsedTransition( + fromScene: Pick, + transitionId: string, +): { spawnPosition: GameVec3 | undefined; walkTarget: GameVec3 | undefined } { + const used = fromScene.transitions?.find((t) => t.id === transitionId); + if (!used) return { spawnPosition: undefined, walkTarget: undefined }; + const spawnPosition = "spawnPosition" in used ? used.spawnPosition : undefined; + const walkTarget = + "targetPosition" in used && used.targetPosition ? used.targetPosition : undefined; + return { spawnPosition, walkTarget }; +} diff --git a/packages/engine-renderer-r3f/src/hooks/useAudioSystem.ts b/packages/engine-renderer-r3f/src/hooks/useAudioSystem.ts index 6290c3e..bfe36b9 100644 --- a/packages/engine-renderer-r3f/src/hooks/useAudioSystem.ts +++ b/packages/engine-renderer-r3f/src/hooks/useAudioSystem.ts @@ -1,109 +1,14 @@ -import { useEffect, useRef } from "react"; +import { useEffect } from "react"; import { - resolveAudioEvents, - type AudioDefaultsConfig, - type AudioRulesContext, - type AudioPort, - type AudioSettingsStore, - type GameEvent, - type GameScene, - type ItemDefinition, - type GameSceneTransition, - type SceneMusicConfig, -} from "@pointclick-engine/engine-core"; + attachAudioSystem, + type AttachAudioSystemOpts, +} from "./attachAudioSystem"; -interface MinimalRuntime { - on(type: GameEvent["type"], handler: (e: GameEvent) => void): () => void; -} - -interface UseAudioSystemOpts { - runtime: MinimalRuntime; - port: AudioPort; - defaults: AudioDefaultsConfig; - scenes: Record; - items: Record; - transitions: Record; - settingsStore: AudioSettingsStore; -} +type UseAudioSystemOpts = AttachAudioSystemOpts; export function useAudioSystem(opts: UseAudioSystemOpts): void { - const previousMusicRef = useRef(undefined); - useEffect(() => { - const { runtime, port, defaults, scenes, items, transitions, settingsStore } = - opts; - - const ctxFor = (): AudioRulesContext => ({ - defaults, - currentScene: undefined, - previousMusic: previousMusicRef.current, - items, - transitions, - }); - - const dispatchAudio = (events: GameEvent[]) => { - for (const e of events) { - if (e.type === "audio:sfxRequested") { - port.playSound( - { - id: e.soundUrl, - url: e.soundUrl, - category: e.category, - volume: e.volume, - }, - ); - } else if (e.type === "audio:musicRequested") { - port.playMusic( - { - id: e.trackUrl, - url: e.trackUrl, - category: "music", - loop: e.loop ?? true, - volume: e.volume, - }, - { fadeMs: e.fadeMs }, - ); - } else if (e.type === "audio:musicStopped") { - port.stopMusic({ fadeMs: e.fadeMs }); - } - } - }; - - const handle = (event: GameEvent) => { - const out = resolveAudioEvents(event, ctxFor()); - dispatchAudio(out); - - // Actualizar previousMusicRef cuando la escena cambia - if (event.type === "scene:changed") { - previousMusicRef.current = event.scene.music; - } - }; - - const subs = [ - runtime.on("scene:changed", handle), - runtime.on("item:pickedUp", handle), - runtime.on("item:dropped", handle), - runtime.on("transition:triggered", handle), - runtime.on("dialog:triggered", handle), - ]; - - // Sync inicial de settings hacia el port - const applySettings = () => { - const s = settingsStore.getState(); - port.setMuted("master", s.masterMuted); - port.setMuted("music", s.musicMuted); - port.setMuted("sfx", s.sfxMuted); - port.setVolume("master", s.masterVolume); - port.setVolume("music", s.musicVolume); - port.setVolume("sfx", s.sfxVolume); - }; - applySettings(); - const unsubSettings = settingsStore.subscribe(applySettings); - - return () => { - subs.forEach((u) => u()); - unsubSettings(); - }; + return attachAudioSystem(opts); // eslint-disable-next-line react-hooks/exhaustive-deps }, [opts.runtime, opts.port, opts.settingsStore]); } diff --git a/packages/engine-renderer-r3f/src/hooks/useClickToMoveController.ts b/packages/engine-renderer-r3f/src/hooks/useClickToMoveController.ts index 1ca2116..85359d5 100644 --- a/packages/engine-renderer-r3f/src/hooks/useClickToMoveController.ts +++ b/packages/engine-renderer-r3f/src/hooks/useClickToMoveController.ts @@ -28,8 +28,29 @@ type AutoMoveDirection = { horizontal: number; vertical: number; snapToTarget?: { x: number; z: number }; + /** Signed distance left to the current waypoint, to avoid overshooting it. */ + remaining?: { x: number; z: number }; }; +/** + * Limits a velocity so one frame of movement cannot carry the body past the + * waypoint. Without it, a long frame overshoots and the character bounces + * back and forth around the target, flipping its walk direction every frame. + */ +export function clampVelocityToRemaining( + velocity: { x: number; z: number }, + remaining: { x: number; z: number }, + delta: number, +): { x: number; z: number } { + if (delta <= 0) return velocity; + const maxX = Math.abs(remaining.x) / delta; + const maxZ = Math.abs(remaining.z) / delta; + return { + x: Math.max(-maxX, Math.min(maxX, velocity.x)), + z: Math.max(-maxZ, Math.min(maxZ, velocity.z)), + }; +} + const DEFAULT_CONFIG: UseClickToMoveControllerConfig = { arrivalThreshold: 0.15, stuckMovementEpsilon: 0.015, @@ -118,6 +139,7 @@ export function useClickToMoveController( return { horizontal: MathUtils.clamp(dx / dist, -1, 1), vertical: MathUtils.clamp(dz / dist, -1, 1), + remaining: { x: dx, z: dz }, }; }, [mergedConfig.arrivalThreshold], diff --git a/packages/engine-renderer-r3f/src/hooks/useDialogue.ts b/packages/engine-renderer-r3f/src/hooks/useDialogue.ts new file mode 100644 index 0000000..d3325f8 --- /dev/null +++ b/packages/engine-renderer-r3f/src/hooks/useDialogue.ts @@ -0,0 +1,44 @@ +"use client"; + +import { useCallback, useMemo } from "react"; +import { getGameRuntime, useDialogueStore } from "@pointclick-engine/engine-core"; + +import { useI18n } from "./useI18n"; + +export interface DialogueChoiceItem { + /** Posicion original en `node.choices`; es lo que espera `dialogue:choose`. */ + index: number; + /** Texto ya traducido. */ + text: string; +} + +export interface UseDialogueResult { + active: boolean; + /** Id del NPC que habla ("player" o un id de NPC), si el nodo lo indica. */ + speaker?: string; + choices: DialogueChoiceItem[]; + choose(index: number): void; + advance(): void; + end(): void; +} + +/** Vista React de la conversacion activa y atajos a sus comandos (`dialogue:*`). */ +export function useDialogue(): UseDialogueResult { + const active = useDialogueStore((s) => s.activeDialogueId !== null); + const speaker = useDialogueStore((s) => s.speaker); + const views = useDialogueStore((s) => s.choices); + const { t } = useI18n(); + + const choices = useMemo( + () => views.map((v) => ({ index: v.index, text: t(v.textKey) })), + [views, t], + ); + const choose = useCallback( + (index: number) => getGameRuntime()?.executeCommand({ type: "dialogue:choose", index }), + [], + ); + const advance = useCallback(() => getGameRuntime()?.executeCommand({ type: "dialogue:advance" }), []); + const end = useCallback(() => getGameRuntime()?.executeCommand({ type: "dialogue:end" }), []); + + return { active, speaker, choices, choose, advance, end }; +} diff --git a/packages/engine-renderer-r3f/src/hooks/useGameActions.ts b/packages/engine-renderer-r3f/src/hooks/useGameActions.ts new file mode 100644 index 0000000..fa7dd20 --- /dev/null +++ b/packages/engine-renderer-r3f/src/hooks/useGameActions.ts @@ -0,0 +1,7 @@ +import { useShallow } from "zustand/react/shallow"; +import { useSceneStore, toGameActions, type GameActions } from "@pointclick-engine/engine-core"; + +/** Hook para obtener acciones públicas con referencia estable. */ +export function useGameActions(): GameActions { + return useSceneStore(useShallow((state) => toGameActions(state))); +} diff --git a/packages/engine-renderer-r3f/src/hooks/useGameState.ts b/packages/engine-renderer-r3f/src/hooks/useGameState.ts new file mode 100644 index 0000000..a7825d1 --- /dev/null +++ b/packages/engine-renderer-r3f/src/hooks/useGameState.ts @@ -0,0 +1,6 @@ +import { useSceneStore, toGameState, type GameState } from "@pointclick-engine/engine-core"; + +/** Hook para seleccionar estado de juego desde la API pública. */ +export function useGameState(selector: (state: GameState) => T): T { + return useSceneStore((state) => selector(toGameState(state))); +} diff --git a/packages/engine-renderer-r3f/src/hooks/useHotspotInteractions.ts b/packages/engine-renderer-r3f/src/hooks/useHotspotInteractions.ts new file mode 100644 index 0000000..867220b --- /dev/null +++ b/packages/engine-renderer-r3f/src/hooks/useHotspotInteractions.ts @@ -0,0 +1,152 @@ +"use client"; + +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { + getGameRuntime, + getInputLockState, + useInputLockStore, + useInventoryStateStore, + usePlacedItemsStateStore, + useSceneStore, + useWorldStateStore, + type ConditionContext, + type GameSceneHotspot, + type Verb, +} from "@pointclick-engine/engine-core"; + +import { ENGINE_NO_ACTION_KEY, ensureEngineTexts } from "../i18n/engineTexts"; +import { buildVerbLabels, filterVisibleHotspots, planHotspotClick } from "../scene/hotspotLogic"; +import { useI18n } from "./useI18n"; + +const NO_HOTSPOTS: GameSceneHotspot[] = []; + +export type HotspotMenuState = { + hotspot: GameSceneHotspot; + verbs: Verb[]; + position: { x: number; y: number }; +}; + +export type UseHotspotInteractionsOptions = { + /** Muestra una frase en el bocadillo (el de `useGameViewportController`). */ + showSpeechBubble: (text: string, meta?: { dialogKey?: string }) => void; + /** Cancela el arrastre del inventario en curso. */ + clearDrag: () => void; + /** Clave de la frase generica de `hotspot:noAction`. Por defecto, la del motor. */ + noActionDialogKey?: string; +}; + +/** Hotspots visibles de la escena activa (incluye los NPC proyectados); se recalcula al cambiar el estado. */ +export function useVisibleHotspots(): GameSceneHotspot[] { + const hotspots = useSceneStore((s) => s.scene.hotspots); + const sceneId = useSceneStore((s) => s.sceneId); + const flags = useWorldStateStore((s) => s.flags); + const visitedSceneIds = useWorldStateStore((s) => s.visitedSceneIds); + const inventory = useInventoryStateStore((s) => s.slots); + const placedItems = usePlacedItemsStateStore((s) => s.items); + return useMemo(() => { + if (!hotspots?.length) return NO_HOTSPOTS; + const ctx: ConditionContext = { flags, inventory, placedItems, sceneId, visitedSceneIds }; + return filterVisibleHotspots(hotspots, ctx); + }, [hotspots, flags, inventory, placedItems, sceneId, visitedSceneIds]); +} + +/** + * Logica de interaccion con hotspots: click (verbo por defecto o menu), suelta de un + * item (`useItem`) y frase generica de `hotspot:noAction`. Respeta `inputLocked`. + */ +export function useHotspotInteractions({ + showSpeechBubble, + clearDrag, + noActionDialogKey = ENGINE_NO_ACTION_KEY, +}: UseHotspotInteractionsOptions) { + const hotspots = useVisibleHotspots(); + const sceneId = useSceneStore((s) => s.sceneId); + const { t, getPhrase } = useI18n(); + const [menu, setMenu] = useState(null); + const hasHotspots = hotspots.length > 0; + + useEffect(() => { + if (hasHotspots) ensureEngineTexts(); + }, [hasHotspots]); + + // Ultimos valores por ref: el listener de eventos no se re-suscribe al cambiar la frase o el bocadillo. + const latestRef = useRef({ showSpeechBubble, getPhrase, noActionDialogKey }); + useEffect(() => { + latestRef.current = { showSpeechBubble, getPhrase, noActionDialogKey }; + }); + + useEffect(() => { + if (!hasHotspots) return; + const runtime = getGameRuntime(); + if (!runtime) return; + return runtime.on("hotspot:noAction", () => { + const { showSpeechBubble: show, getPhrase: phrase, noActionDialogKey: key } = latestRef.current; + show(phrase(key), { dialogKey: key }); + }); + }, [hasHotspots]); + + // Cierra el menu al cambiar de escena o al bloquearse la entrada. + useEffect(() => setMenu(null), [sceneId]); + useEffect( + () => + useInputLockStore.subscribe((s) => { + if (s.inputLocked) setMenu(null); + }), + [], + ); + + const run = useCallback((hotspotId: string, verb: Verb | "useItem", itemId?: string) => { + getGameRuntime()?.executeCommand({ + type: "hotspot:interact", + hotspotId, + verb, + ...(itemId !== undefined ? { itemId } : {}), + }); + }, []); + + /** Click sobre un hotspot en `position` (pixeles de pantalla). */ + const activate = useCallback( + (hotspot: GameSceneHotspot, position: { x: number; y: number }) => { + if (getInputLockState().inputLocked) return; + const world = useWorldStateStore.getState(); + const ctx: ConditionContext = { + flags: world.flags, + inventory: useInventoryStateStore.getState().slots, + placedItems: usePlacedItemsStateStore.getState().items, + sceneId: useSceneStore.getState().sceneId, + visitedSceneIds: world.visitedSceneIds, + }; + const plan = planHotspotClick(hotspot, ctx); + if (plan.kind === "menu") setMenu({ hotspot, verbs: plan.verbs, position }); + else run(hotspot.id, plan.verb); + }, + [run], + ); + + /** Suelta un item del inventario sobre un hotspot. */ + const dropItem = useCallback( + (hotspot: GameSceneHotspot, itemId: string) => { + clearDrag(); + if (getInputLockState().inputLocked) return; + run(hotspot.id, "useItem", itemId); + }, + [clearDrag, run], + ); + + const select = useCallback( + (verb: Verb) => { + if (menu && !getInputLockState().inputLocked) run(menu.hotspot.id, verb); + setMenu(null); + }, + [menu, run], + ); + const closeMenu = useCallback(() => setMenu(null), []); + // Los textos del motor se registran antes de traducir: en el primer render el efecto de + // arriba aun no ha corrido y las etiquetas saldrian como claves crudas. + const labels = useMemo(() => { + ensureEngineTexts(); + return buildVerbLabels(t); + }, [t]); + + return { hotspots, menu, labels, activate, dropItem, select, closeMenu }; +} diff --git a/packages/engine-renderer-r3f/src/hooks/useInventoryRuntime.ts b/packages/engine-renderer-r3f/src/hooks/useInventoryRuntime.ts new file mode 100644 index 0000000..f360f60 --- /dev/null +++ b/packages/engine-renderer-r3f/src/hooks/useInventoryRuntime.ts @@ -0,0 +1,338 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { + createInventoryRuleContext, + emitRuntimeEvent, + getDeclaredScene, + getGameRuntime, + getSceneRuleContext, + getRandomPhrase as engineGetRandomPhrase, + useDialogStore, + useInventoryStateStore, + resolveEnterScript, + useInventoryUiStore, + usePlacedItemsStateStore, + type GameSceneInteractionFull, + type InventoryRuleContext, + type PlacedSceneItem, + type RuntimeEventHandler, +} from "@pointclick-engine/engine-core"; + +import { + applyDropHit, + applyDropMiss, + applyDropOnPlayer, +} from "../inventory/dropHandlers"; +import { applyPickup, releaseStaleLocks } from "../inventory/pickupHandlers"; +import { seedSceneItems, type GetInitialPlacedItems } from "../inventory/seedScene"; +import type { + DraggedInventoryPayload, + RuntimeDraggedStack, +} from "../inventory/inventoryRuntimeTypes"; +import { buildEnv, cancelFrame, requestFrame } from "../inventory/inventoryEnv"; +import { useProximityHintController } from "./useProximityHintController"; + +type SceneInteraction = GameSceneInteractionFull; + +export type SceneEnterApi = { + /** Muestra el dialogo de la clave (texto via `getPhrase`) como bocadillo del jugador. */ + showDialog(key: string): void; +}; + +export type UseInventoryRuntimeOptions = { + sceneId: string; + sceneInteractions: SceneInteraction[]; + playerPosition: [number, number, number]; + onRuntimeEvent?: RuntimeEventHandler; + /** Texto de una clave de dialogo. Por defecto, el `getRandomPhrase` del core. */ + getPhrase?: (key: string) => string; + /** + * Items iniciales de una escena. Se llama una vez por escena no sembrada; si + * devuelve un array (aunque sea vacio) se anade y la escena se marca sembrada. + * `null` = esa escena no se siembra (no se marca). Sin callback no se siembra nada. + */ + getInitialPlacedItems?: GetInitialPlacedItems; + /** + * Se llama al entrar en una escena (y cuando cambia `showSpeechBubble`), tras dos + * `requestAnimationFrame` para que R3F haya corrido al menos un `useFrame`. + * Corre DESPUES del guion declarativo `scene.onEnter`, que tiene la misma temporizacion + * pero se ejecuta una sola vez por entrada. + */ + onSceneEnter?: (sceneId: string, api: SceneEnterApi) => void; + /** Contexto de reglas de items. Por defecto, el registro del runtime activo. */ + itemContext?: InventoryRuleContext; +}; + +// Origen del registro de items: el runtime activo. Se resuelve en cada uso, no al montar. +// Sin runtime el registro esta vacio (items desconocidos). +const defaultItemContext = createInventoryRuleContext( + () => getGameRuntime()?.getItems() ?? {}, +); + +const defaultGetPhrase = (key: string): string => engineGetRandomPhrase(key); + +/** + * Inventario e items colocados del runtime: arrastre, drops, recogida, pistas por + * proximidad, bocadillo, siembra por escena y edicion de posicion de items. + * No persiste nada: la persistencia es del consumidor. + */ +export function useInventoryRuntime({ + sceneId, + sceneInteractions, + playerPosition, + onRuntimeEvent, + getPhrase = defaultGetPhrase, + getInitialPlacedItems, + onSceneEnter, + itemContext = defaultItemContext, +}: UseInventoryRuntimeOptions) { + // Dialog state lives in the core dialog store (wirable via dialog:trigger / dialog:dismiss) + const showDialog = useDialogStore((s) => s.show); + const dismissDialog = useDialogStore((s) => s.dismiss); + + // Inventory visibility lives in the core UI store (wirable via inventory:toggle) + const isInventoryOpen = useInventoryUiStore((s) => s.isOpen); + + const inventorySlots = useInventoryStateStore((s) => s.slots); + const placedItems = usePlacedItemsStateStore((s) => s.items); + const [draggedStack, setDraggedStack] = useState(null); + const pickupLockRef = useRef>(new Set()); + + // Opciones inyectadas: se leen por ref para no alterar las dependencias de callbacks y efectos. + const injectedRef = useRef({ getPhrase, itemContext, getInitialPlacedItems, onSceneEnter }); + useEffect(() => { + injectedRef.current = { getPhrase, itemContext, getInitialPlacedItems, onSceneEnter }; + }); + + useEffect(() => { + releaseStaleLocks(pickupLockRef.current, placedItems); + }, [placedItems]); + + // Siembra por escena: una vez por escena no sembrada. Idempotente (StrictMode). + useEffect(() => { + seedSceneItems(sceneId, injectedRef.current.getInitialPlacedItems); + }, [sceneId]); + + const handleBoundaryHit = useCallback( + (phrase: string) => { + showDialog(phrase, "boundaryHit"); + emitRuntimeEvent(onRuntimeEvent, { + type: "onDialog", + source: "boundary", + text: phrase, + dialogKey: "boundaryHit", + }); + }, + [onRuntimeEvent, showDialog], + ); + + const showSpeechBubble = useCallback( + ( + nextText: string, + meta?: { source?: "inventory" | "debug"; dialogKey?: string }, + ) => { + showDialog(nextText, meta?.dialogKey); + emitRuntimeEvent(onRuntimeEvent, { + type: "onDialog", + source: meta?.source ?? "inventory", + text: nextText, + dialogKey: meta?.dialogKey, + }); + }, + [onRuntimeEvent, showDialog], + ); + + const hideSpeechBubble = useCallback(() => { + dismissDialog(); + }, [dismissDialog]); + + const handleInventoryDropHit = useCallback( + (interaction: SceneInteraction, payload: DraggedInventoryPayload) => { + applyDropHit( + buildEnv(injectedRef.current, showSpeechBubble, onRuntimeEvent, setDraggedStack), + sceneId, + interaction, + payload, + ); + }, + [onRuntimeEvent, showSpeechBubble], + ); + + const handleInventoryDropMiss = useCallback( + (payload: DraggedInventoryPayload, interaction?: SceneInteraction) => { + applyDropMiss( + buildEnv(injectedRef.current, showSpeechBubble, onRuntimeEvent, setDraggedStack), + sceneInteractions, + payload, + interaction, + ); + }, + [onRuntimeEvent, sceneInteractions, showSpeechBubble], + ); + + const handleInventoryDropOnPlayer = useCallback( + (payload: DraggedInventoryPayload) => { + applyDropOnPlayer( + buildEnv(injectedRef.current, showSpeechBubble, onRuntimeEvent, setDraggedStack), + payload, + ); + }, + [onRuntimeEvent, showSpeechBubble], + ); + + const handlePickupPlacedItem = useCallback( + (placedItem: PlacedSceneItem) => { + applyPickup( + buildEnv(injectedRef.current, showSpeechBubble, onRuntimeEvent, setDraggedStack), + pickupLockRef.current, + isInventoryOpen, + placedItem, + ); + }, + [isInventoryOpen, onRuntimeEvent, showSpeechBubble], + ); + + const updatePlacedItemPosition = useCallback( + (id: string, axis: 0 | 1 | 2, value: number) => { + usePlacedItemsStateStore.getState().updateItemPosition(id, axis, value); + }, + [], + ); + + const movePlacedItemToPlayer = useCallback( + (id: string) => { + const state = usePlacedItemsStateStore.getState(); + const item = state.items.find((i) => i.id === id); + if (!item) return; + state.setItemPosition(id, [playerPosition[0], item.worldPosition[1], playerPosition[2]]); + }, + [playerPosition], + ); + + const removePlacedItemById = useCallback((id: string) => { + usePlacedItemsStateStore.getState().removeItem(id); + }, []); + + const handleStartInventoryDrag = useCallback( + (slotIndex: number, clientX: number, clientY: number) => { + const stack = inventorySlots[slotIndex]; + if (!stack) return; + + useInventoryUiStore.getState().close(); + setDraggedStack({ + stack, + fromSlotIndex: slotIndex, + pointerX: clientX, + pointerY: clientY, + }); + }, + [inventorySlots], + ); + + const handleInteractionInspect = useCallback( + (interaction: SceneInteraction) => { + if (!interaction.hintDialogKeys) return; + + // Si hay un ítem colocado que puede recogerse, no disparamos el hint: + // el click será gestionado por el sistema de pickup, no por el de pistas. + const hasPickableItem = placedItems.some( + (item) => item.interactionId === interaction.id && item.canPickup, + ); + if (hasPickableItem) return; + + const isOccupied = placedItems.some((item) => item.interactionId === interaction.id); + const dialogKey = isOccupied + ? interaction.hintDialogKeys.occupied + : interaction.hintDialogKeys.empty; + + showSpeechBubble(injectedRef.current.getPhrase(dialogKey), { dialogKey }); + }, + [placedItems, showSpeechBubble], + ); + + useProximityHintController({ + playerPosition, + interactions: sceneInteractions, + placedItems, + showSpeechBubble, + getPhrase, + }); + + // Escena cuyo `onEnter` declarativo ya corrio: evita repetirlo si solo cambia `showSpeechBubble`. + const enteredSceneRef = useRef(null); + + useEffect(() => { + if (!injectedRef.current.onSceneEnter && !getDeclaredScene(sceneId)?.onEnter) { + enteredSceneRef.current = null; + return; + } + + // Double-rAF: el dialogo de entrada dispara DESPUÉS de que R3F haya corrido + // al menos un useFrame. setTimeout(0) se ejecutaba antes del primer + // requestAnimationFrame, dejando el sprite en SPRITE_MIN_SCALE sin que + // useFrame hubiera corregido aún la escala por profundidad. + let outerHandle: number | null = null; + let innerHandle: number | null = null; + + outerHandle = requestFrame(() => { + outerHandle = null; + innerHandle = requestFrame(() => { + innerHandle = null; + if (enteredSceneRef.current !== sceneId) { + enteredSceneRef.current = sceneId; + const script = resolveEnterScript( + getDeclaredScene(sceneId)?.onEnter, + getSceneRuleContext(sceneId), + ); + if (script) getGameRuntime()?.runScript(script); + } + injectedRef.current.onSceneEnter?.(sceneId, { + showDialog: (key) => + showSpeechBubble(injectedRef.current.getPhrase(key), { dialogKey: key }), + }); + }); + }); + + return () => { + if (outerHandle !== null) cancelFrame(outerHandle); + if (innerHandle !== null) cancelFrame(innerHandle); + }; + }, [sceneId, showSpeechBubble]); + + /** Cancela el arrastre en curso sin mostrar frase (lo usa la suelta sobre un hotspot). */ + const clearDrag = useCallback(() => setDraggedStack(null), []); + + const handleItemInteract = useCallback( + (item: PlacedSceneItem) => { + // Emit item interaction event — useTransitionSystem listens for this + // to check if there's a matching transition + emitRuntimeEvent(onRuntimeEvent, { + type: "onDrop", + outcome: "item-interact", + itemId: item.itemId, + interactionId: item.interactionId, + }); + }, + [onRuntimeEvent], + ); + + return { + isInventoryOpen, + inventorySlots, + draggedStack, + placedItems, + handleBoundaryHit, + showSpeechBubble, + hideSpeechBubble, + handleInteractionInspect, + handleInventoryDropHit, + handleInventoryDropMiss, + handleInventoryDropOnPlayer, + handlePickupPlacedItem, + updatePlacedItemPosition, + movePlacedItemToPlayer, + removePlacedItemById, + handleStartInventoryDrag, + handleItemInteract, + clearDrag, + }; +} diff --git a/packages/engine-renderer-r3f/src/hooks/usePlayerWalkAnimation.ts b/packages/engine-renderer-r3f/src/hooks/usePlayerWalkAnimation.ts index aa9f5ac..f7d499b 100644 --- a/packages/engine-renderer-r3f/src/hooks/usePlayerWalkAnimation.ts +++ b/packages/engine-renderer-r3f/src/hooks/usePlayerWalkAnimation.ts @@ -3,7 +3,8 @@ import { useRef, useEffect } from "react"; import { useFrame } from "@react-three/fiber"; import type { GameVec3, PlayerWalkingState } from "@pointclick-engine/engine-core"; -import { useSceneStore } from "@pointclick-engine/engine-core"; +import { useSceneStore, getGameRuntime } from "@pointclick-engine/engine-core"; +import { decideWalkEvent } from "./walkEventTransition"; /** World units per second at which the character walks. */ const WALK_SPEED = 4.5; @@ -41,6 +42,20 @@ export function usePlayerWalkAnimation( durationMs: number; } | null>(null); + // Aviso de fin/interrupción de caminata (solo notifica; no altera la animación). + const trackedWalkRef = useRef(null); + const completedWalkIdRef = useRef(null); + const abortedByCoreRef = useRef(false); + const emittingRef = useRef(false); + const subscriptionRef = useRef<{ runtime: unknown; unsubscribe: () => void } | null>(null); + + useEffect(() => { + return () => { + subscriptionRef.current?.unsubscribe(); + subscriptionRef.current = null; + }; + }, []); + useEffect(() => { walkingStateRef.current = walkingState; playerPositionRef.current = playerPosition; @@ -48,16 +63,58 @@ export function usePlayerWalkAnimation( _onWalkAbortRef.current = onWalkAbort; }); + /** Avanza el seguimiento de la caminata y emite el evento que toque, si alguno. */ + const trackWalk = (current: string | null, reached: boolean, endPosition: GameVec3 | null) => { + const runtime = getGameRuntime(); + // Escucha los avisos del core para no duplicar `player:stop` (que ya emite walkAborted). + if (subscriptionRef.current?.runtime !== runtime) { + subscriptionRef.current?.unsubscribe(); + subscriptionRef.current = runtime + ? { + runtime, + unsubscribe: runtime.on("player:walkAborted", (e) => { + if (emittingRef.current || e.reason === "unreachable") return; + if (trackedWalkRef.current !== null) abortedByCoreRef.current = true; + }), + } + : null; + } + + // Tras completar, el estado puede verse un instante más: no re-seguir esa misma caminata. + if (current !== null && current === completedWalkIdRef.current) current = null; + else if (current !== completedWalkIdRef.current) completedWalkIdRef.current = null; + + const decision = decideWalkEvent({ + tracked: trackedWalkRef.current, + current, + reached, + endPosition, + abortedByCore: abortedByCoreRef.current, + }); + if (decision.tracked !== trackedWalkRef.current) abortedByCoreRef.current = false; + trackedWalkRef.current = decision.tracked; + if (!decision.event) return; + if (decision.event.type === "player:walkCompleted") completedWalkIdRef.current = current; + emittingRef.current = true; + try { + runtime?.emit(decision.event); + } finally { + emittingRef.current = false; + } + }; + useFrame((_, delta) => { const state = walkingStateRef.current; if (!state?.isActive) { + trackWalk(null, false, null); animatedPositionRef.current = playerPositionRef.current; return; } const { pathPoints, targetPosition } = state; if (pathPoints.length < 2) { + trackWalk(null, false, null); animatedPositionRef.current = playerPositionRef.current; return; } @@ -84,6 +141,8 @@ export function usePlayerWalkAnimation( animatedPositionRef.current = samplePathPosition(pathPoints, distances, total, progress); updateWalkProgress(progress); + trackWalk(walkId, progress >= 1, pathPoints[pathPoints.length - 1] ?? targetPosition); + if (progress >= 1) { onWalkCompleteRef.current?.(); useSceneStore.getState().setPlayerWalkingState(null); diff --git a/apps/web-demo/app/lib/engine/runtime/useProximityHintController.ts b/packages/engine-renderer-r3f/src/hooks/useProximityHintController.ts similarity index 84% rename from apps/web-demo/app/lib/engine/runtime/useProximityHintController.ts rename to packages/engine-renderer-r3f/src/hooks/useProximityHintController.ts index a239939..ba34b03 100644 --- a/apps/web-demo/app/lib/engine/runtime/useProximityHintController.ts +++ b/packages/engine-renderer-r3f/src/hooks/useProximityHintController.ts @@ -1,8 +1,14 @@ import { useEffect, useRef } from "react"; -import { getRandomPhrase } from "../../../../demo-content/dialogs/getRandomPhrase"; -import type { SceneInteraction } from "../../../../demo-content/scenes/scenes"; -import type { PlacedSceneItem } from "../types/gameRuntime"; +import { getRandomPhrase as engineGetRandomPhrase } from "@pointclick-engine/engine-core"; +import type { + GameSceneInteractionFull, + PlacedSceneItem, +} from "@pointclick-engine/engine-core"; + +type SceneInteraction = GameSceneInteractionFull; + +const defaultGetPhrase = (key: string): string => engineGetRandomPhrase(key); /** * Radio máximo (en unidades de mundo, XZ) para activar el hint de proximidad. @@ -34,11 +40,13 @@ export function useProximityHintController({ interactions, placedItems, showSpeechBubble, + getPhrase = defaultGetPhrase, }: { playerPosition: [number, number, number]; interactions: SceneInteraction[]; placedItems: PlacedSceneItem[]; showSpeechBubble: ShowSpeechBubble; + getPhrase?: (key: string) => string; }) { // Tracks si el jugador ESTABA dentro de cada zona en el tick anterior const wasInsideRef = useRef>({}); @@ -71,7 +79,7 @@ export function useProximityHintController({ ? interaction.hintDialogKeys.occupied : interaction.hintDialogKeys.empty; - showSpeechBubble(getRandomPhrase(dialogKey), { dialogKey }); + showSpeechBubble(getPhrase(dialogKey), { dialogKey }); lastHintAtRef.current[interaction.id] = now; } } diff --git a/packages/engine-renderer-r3f/src/hooks/useSceneRuntime.ts b/packages/engine-renderer-r3f/src/hooks/useSceneRuntime.ts new file mode 100644 index 0000000..df6ee0f --- /dev/null +++ b/packages/engine-renderer-r3f/src/hooks/useSceneRuntime.ts @@ -0,0 +1,102 @@ +import { useEffect } from "react"; +import { + getGameRuntime, + toRuntimeScene, + useSceneStore, + type GameScene, +} from "@pointclick-engine/engine-core"; + +/** + * Puerto de persistencia del progreso. Hoy solo la escena; un paso posterior + * añadirá el inventario al mismo puerto. + */ +export type SceneProgressStorage = { + loadSceneId(): string | null; + saveSceneId(id: string): void; +}; + +export type UseSceneRuntimeOptions = { + /** Escena a sembrar si no hay una guardada (o la guardada no existe). */ + initialSceneId?: string; + /** Sin él no se persiste nada. */ + storage?: SceneProgressStorage; + /** + * Resuelve la escena completa por id. Por defecto, el registro del runtime + * pasado por `toRuntimeScene`. + */ + resolveScene?: (id: string) => GameScene | null; +}; + +/** + * Decide que escena sembrar: la guardada si existe; si no, la inicial si + * existe; si no, `null` (no se siembra nada). Pura, sin React. + */ +export function resolveInitialSceneId(args: { + savedId: string | null | undefined; + initialSceneId: string | undefined; + hasScene: (id: string) => boolean; +}): string | null { + const { savedId, initialSceneId, hasScene } = args; + const wanted = savedId || initialSceneId; + if (wanted && hasScene(wanted)) return wanted; + if (initialSceneId && hasScene(initialSceneId)) return initialSceneId; + return null; +} + +/** Resolutor por defecto: registro del runtime; `null` si no hay runtime. */ +export function resolveSceneFromRuntime(id: string): GameScene | null { + const config = getGameRuntime()?.getScenes()[id]; + return config ? toRuntimeScene(config) : null; +} + +/** + * Estado de escena del `useSceneStore`, siembra de la escena inicial al montar + * (si el store esta vacio) y persistencia del id de escena. + */ +export function useSceneRuntime(options: UseSceneRuntimeOptions = {}) { + const { initialSceneId, storage, resolveScene = resolveSceneFromRuntime } = options; + + const sceneId = useSceneStore((s) => s.sceneId); + const sceneBackground = useSceneStore((s) => s.scene.background); + const storeSetScene = useSceneStore((s) => s.setScene); + const sceneInteractions = useSceneStore((s) => s.scene.interactions); + const requestRespawn = useSceneStore((s) => s.requestRespawn); + const playerPosition = useSceneStore((s) => s.playerPosition); + const scenePlayerSpawn = useSceneStore((s) => s.scene.playerSpawn); + const updateInteraction = useSceneStore((s) => s.updateInteraction); + const resetInteractionsFromSceneConfig = useSceneStore( + (s) => s.resetInteractionsFromSceneConfig, + ); + + // El store del core arranca vacio: se siembra una sola vez al montar. + useEffect(() => { + if (useSceneStore.getState().sceneId) return; + const id = resolveInitialSceneId({ + savedId: storage?.loadSceneId() ?? null, + initialSceneId, + hasScene: (candidate) => resolveScene(candidate) !== null, + }); + if (!id) return; + const scene = resolveScene(id); + if (scene) storeSetScene(id, scene); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + // Persistir la escena actual cada vez que cambia. + useEffect(() => { + if (sceneId) storage?.saveSceneId(sceneId); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [sceneId]); + + return { + sceneId, + sceneBackground, + storeSetScene, + sceneInteractions, + requestRespawn, + playerPosition, + scenePlayerSpawn, + updateInteraction, + resetInteractionsFromSceneConfig, + }; +} diff --git a/packages/engine-renderer-r3f/src/hooks/useTransitionSystem.ts b/packages/engine-renderer-r3f/src/hooks/useTransitionSystem.ts new file mode 100644 index 0000000..60a3d24 --- /dev/null +++ b/packages/engine-renderer-r3f/src/hooks/useTransitionSystem.ts @@ -0,0 +1,210 @@ +"use client"; + +import { useCallback, useEffect, useRef } from "react"; +import { + evaluateTransitionGate, + getGameRuntime, + getSceneRuleContext, + useDialogStore, + useSceneStore, + resolveTransitionFromItemDrop, + resolveTransitionFromItemInteraction, +} from "@pointclick-engine/engine-core"; +import type { RuntimeEvent, GameScene, GameSceneTransition } from "@pointclick-engine/engine-core"; +import { preloadSceneBackground } from "../scene/SceneBackgroundPlane"; +import { resolveSceneFromRuntime } from "./useSceneRuntime"; +import { + decideLeaveScene, + resolveUsedTransition, + type CanLeaveScene, +} from "./transitionRules"; + +export type { CanLeaveScene, LeaveSceneTransition, LeaveSceneBlock } from "./transitionRules"; + +/** + * Cablea las transiciones de escena: + * - Por colision (via el callback `handleTransitionTriggered`) + * - Por soltar/interactuar con un item (via `wrapRuntimeEventForTransitions`) + */ +export interface UseTransitionSystemOpts { + onBeforeChange?: () => void; + /** Resuelve el objeto de escena completo por ID. Por defecto, el registro del runtime. */ + resolveScene?: (sceneId: string) => GameScene | null; + /** + * Regla del juego para permitir salir de la escena. Si devuelve un objeto, + * se muestra ese dialogo y no se cambia de escena. Se evalua al disparar la transicion. + * Se evalua DESPUES de `transition.when` (declarativo): si `when` no se cumple corre + * `transition.blocked` y esta regla no se llama; si se cumple, esta regla puede vetar. + */ + canLeaveScene?: CanLeaveScene; +} + +/** + * Aplica `when`/`blocked` de la transicion. Si no se cumple `when`, corre `blocked` + * y devuelve false (no hay cambio de escena). Aplica a todos los tipos de transicion. + */ +function passesDeclarativeGate(transition: GameSceneTransition): boolean { + const gate = evaluateTransitionGate(transition, getSceneRuleContext(useSceneStore.getState().sceneId)); + if (gate.allowed) return true; + if (gate.blocked.length > 0) getGameRuntime()?.runScript(gate.blocked); + return false; +} + +export function useTransitionSystem(opts?: UseTransitionSystemOpts) { + const storeSetScene = useSceneStore((s) => s.setScene); + const isTransitioningRef = useRef(false); + const showDialog = useDialogStore((s) => s.show); + const dialogVisible = useDialogStore((s) => s.visible); + const pendingTransitionRef = useRef<{ id: string; targetSceneId: string } | null>(null); + const optsRef = useRef(opts); + useEffect(() => { optsRef.current = opts; }); + + const changeScene = useCallback( + (targetSceneId: string, transitionId: string) => { + if (isTransitioningRef.current) return; + + const resolvedScene = (optsRef.current?.resolveScene ?? resolveSceneFromRuntime)(targetSceneId); + if (!resolvedScene) { + // Sin escena destino no se cambia nada; la guarda no llega a tomarse. + console.warn(`[transition] target scene could not be resolved: ${targetSceneId}`); + return; + } + + isTransitioningRef.current = true; + + getGameRuntime()?.emit({ + type: "transition:started", + transitionId, + }); + + // Notify caller synchronously so it can show the curtain overlay before + // any state update causes a re-render with the new (backgroundless) scene. + optsRef.current?.onBeforeChange?.(); + + const fromSceneId = useSceneStore.getState().sceneId; + const fromScene = useSceneStore.getState().scene; + + const { spawnPosition, walkTarget } = resolveUsedTransition(fromScene, transitionId); + + // Change scene first with optional custom spawn position + storeSetScene(targetSceneId, resolvedScene, spawnPosition); + + // Then emit walk command in the new scene with correct pathfinding context + if (walkTarget) { + getGameRuntime()?.executeCommand({ + type: "player:walkTo", + position: walkTarget, + }); + } + + getGameRuntime()?.emit({ + type: "transition:completed", + fromSceneId, + toSceneId: targetSceneId, + }); + + // Reset guard after a brief delay so re-entering the same zone works + setTimeout(() => { + isTransitioningRef.current = false; + }, 800); + }, + [storeSetScene], + ); + + /** Called by SceneTransitions renderer when player enters a collision zone. */ + const handleTransitionTriggered = useCallback( + (transitionId: string, targetSceneId: string) => { + const currentSceneId = useSceneStore.getState().sceneId; + const currentScene = useSceneStore.getState().scene; + const transition = currentScene.transitions?.find((t) => t.id === transitionId); + + if (!transition) { + console.warn(`[transition] transition not found: ${transitionId}`); + return; + } + + if (!passesDeclarativeGate(transition)) return; + + const decision = decideLeaveScene(optsRef.current?.canLeaveScene, { + transitionId, + fromSceneId: currentSceneId, + targetSceneId, + }); + if (!decision.allowed) { + showDialog(decision.text, decision.dialogKey); + return; + } + + // Preload the target scene background so it's in browser cache when we switch. + const resolveScene = optsRef.current?.resolveScene ?? resolveSceneFromRuntime; + const targetBg = resolveScene(targetSceneId)?.background; + if (targetBg) preloadSceneBackground(targetBg); + + getGameRuntime()?.emit({ + type: "transition:triggered", + transitionId, + targetSceneId, + }); + changeScene(targetSceneId, transitionId); + }, + [changeScene, showDialog], + ); + + /** + * Handles item-drop and item-interact events from the inventory system. + * Returns a passthrough handler that checks if the drop/interact matches a transition. + * Defers the scene change until the dialog is dismissed. + */ + const wrapRuntimeEventForTransitions = useCallback( + (passthrough: (event: RuntimeEvent) => void) => + (event: RuntimeEvent) => { + const scene = useSceneStore.getState().scene; + + if (event.type === "onDrop" && (event.outcome === "consume" || event.outcome === "place") && event.interactionId) { + const gameEvent = { + type: "item:dropped" as const, + itemId: event.itemId, + outcome: event.outcome as "consume" | "place", + interactionId: event.interactionId, + }; + const matching = resolveTransitionFromItemDrop(scene, gameEvent); + if (matching && passesDeclarativeGate(matching)) { + getGameRuntime()?.emit({ + type: "transition:triggered", + transitionId: matching.id, + targetSceneId: matching.targetSceneId, + }); + // Store transition to trigger after dialog closes + pendingTransitionRef.current = { id: matching.id, targetSceneId: matching.targetSceneId }; + } + } + + if (event.type === "onDrop" && event.outcome === "item-interact" && event.interactionId) { + const matching = resolveTransitionFromItemInteraction(scene, event.itemId, event.interactionId); + if (matching && passesDeclarativeGate(matching)) { + getGameRuntime()?.emit({ + type: "transition:triggered", + transitionId: matching.id, + targetSceneId: matching.targetSceneId, + }); + // Store transition to trigger after dialog closes + pendingTransitionRef.current = { id: matching.id, targetSceneId: matching.targetSceneId }; + } + } + + passthrough(event); + }, + [], + ); + + // Execute pending transition after dialog is dismissed + useEffect(() => { + if (!dialogVisible && pendingTransitionRef.current) { + const t = pendingTransitionRef.current; + pendingTransitionRef.current = null; + changeScene(t.targetSceneId, t.id); + } + }, [dialogVisible, changeScene]); + + return { handleTransitionTriggered, wrapRuntimeEventForTransitions }; +} diff --git a/packages/engine-renderer-r3f/src/hooks/walkEventTransition.ts b/packages/engine-renderer-r3f/src/hooks/walkEventTransition.ts new file mode 100644 index 0000000..1434bd8 --- /dev/null +++ b/packages/engine-renderer-r3f/src/hooks/walkEventTransition.ts @@ -0,0 +1,62 @@ +import type { GameVec3 } from "@pointclick-engine/engine-core"; + +/** Motivos con los que el renderer puede avisar de una caminata interrumpida. */ +export type WalkInterruptionReason = "user-input" | "collision"; + +/** Evento que toca emitir en una transición (o `null` si ninguno). */ +export type WalkEventDecision = + | { type: "player:walkCompleted"; position: GameVec3 } + | { type: "player:walkAborted"; reason: WalkInterruptionReason } + | null; + +export interface WalkTransitionInput { + /** Identidad de la caminata que se seguía en el fotograma anterior (`null` si ninguna). */ + tracked: string | null; + /** Identidad de la caminata por ruta activa ahora (`null` si no hay). */ + current: string | null; + /** La caminata actual ha alcanzado progreso 1 en este fotograma. */ + reached: boolean; + /** Último punto de la ruta; posición reportada al llegar. */ + endPosition: GameVec3 | null; + /** El core ya avisó de la interrupción (p. ej. `player:stop` emite `walkAborted`). */ + abortedByCore: boolean; + /** Causa de una interrupción detectada por el renderer. Por defecto, `user-input`. */ + interruption?: WalkInterruptionReason; +} + +export interface WalkTransitionResult { + event: WalkEventDecision; + /** Caminata a seguir a partir de ahora. */ + tracked: string | null; +} + +/** + * Decide qué evento toca emitir al pasar de la caminata seguida a la actual. + * Pura: sin bus, sin store, sin React. + * + * - llegada de la caminata seguida -> `walkCompleted` (una sola vez; se deja de seguir); + * - caminata seguida que desaparece o es sustituida por otra ruta -> `walkAborted`, + * salvo que el core ya lo haya emitido (`player:stop`); + * - sin caminata seguida no se emite nada (el movimiento manual nunca avisa). + */ +export function decideWalkEvent(input: WalkTransitionInput): WalkTransitionResult { + const { tracked, current, reached, endPosition, abortedByCore } = input; + const reason = input.interruption ?? "user-input"; + + if (tracked === null) { + return { event: null, tracked: current }; + } + + if (current === tracked) { + if (reached && endPosition) { + return { event: { type: "player:walkCompleted", position: endPosition }, tracked: null }; + } + return { event: null, tracked }; + } + + // La caminata seguida ya no está (parada) o fue sustituida por otra ruta. + return { + event: abortedByCore ? null : { type: "player:walkAborted", reason }, + tracked: current, + }; +} diff --git a/packages/engine-renderer-r3f/src/hooks/wallSlide.ts b/packages/engine-renderer-r3f/src/hooks/wallSlide.ts new file mode 100644 index 0000000..1e294f9 --- /dev/null +++ b/packages/engine-renderer-r3f/src/hooks/wallSlide.ts @@ -0,0 +1,39 @@ +export type SlideBlock = { x: boolean; z: boolean }; + +export const NO_SLIDE_BLOCK: SlideBlock = { x: false, z: false }; + +type Point = { x: number; z: number }; + +/** + * Wall-slide detection: compares the velocity set last frame against the + * displacement the physics actually produced. An axis that barely moved + * relative to what was expected is blocked by a rigid body. + * + * Physics runs at a fixed timestep, so a render frame can arrive with no + * physics step in between (high refresh-rate displays, uneven frame times). + * The body then has not moved at all, which says nothing about walls: in that + * case the previous result is kept instead of reporting both axes as blocked. + */ +export function detectSlideBlock( + previousPosition: Point | null, + position: Point, + previousVelocity: { vx: number; vz: number }, + delta: number, + previous: SlideBlock, +): SlideBlock { + const { vx, vz } = previousVelocity; + if (!previousPosition || (Math.abs(vx) <= 0.3 && Math.abs(vz) <= 0.3)) { + return NO_SLIDE_BLOCK; + } + const adx = position.x - previousPosition.x; + const adz = position.z - previousPosition.z; + if (adx === 0 && adz === 0) return previous; + // Expected displacement (approximated with the current delta: consecutive + // frame durations are close enough for this heuristic). + const edx = vx * delta; + const edz = vz * delta; + return { + x: Math.abs(edx) > 0.002 && Math.abs(adx) < Math.abs(edx) * 0.25, + z: Math.abs(edz) > 0.002 && Math.abs(adz) < Math.abs(edz) * 0.25, + }; +} diff --git a/packages/engine-renderer-r3f/src/i18n/engineTexts.ts b/packages/engine-renderer-r3f/src/i18n/engineTexts.ts new file mode 100644 index 0000000..ba33d5c --- /dev/null +++ b/packages/engine-renderer-r3f/src/i18n/engineTexts.ts @@ -0,0 +1,46 @@ +import { + getDictionary, + registerDictionary, + type DialogDictionary, + type Verb, +} from "@pointclick-engine/engine-core"; + +/** Claves de i18n propias del motor (renderer). El host puede sobrescribirlas registrando las suyas. */ +export const ENGINE_VERB_LABEL_KEYS: Record = { + look: "engine.verb.look", + use: "engine.verb.use", + talk: "engine.verb.talk", +}; + +/** Frase generica cuando un hotspot no tiene accion para lo pedido. */ +export const ENGINE_NO_ACTION_KEY = "engine.hotspot.noAction"; + +const DEFAULTS: Record = { + es: { + [ENGINE_VERB_LABEL_KEYS.look]: { phrases: ["Mirar"] }, + [ENGINE_VERB_LABEL_KEYS.use]: { phrases: ["Usar"] }, + [ENGINE_VERB_LABEL_KEYS.talk]: { phrases: ["Hablar"] }, + [ENGINE_NO_ACTION_KEY]: { phrases: ["No sé qué hacer con eso."] }, + }, + en: { + [ENGINE_VERB_LABEL_KEYS.look]: { phrases: ["Look"] }, + [ENGINE_VERB_LABEL_KEYS.use]: { phrases: ["Use"] }, + [ENGINE_VERB_LABEL_KEYS.talk]: { phrases: ["Talk"] }, + [ENGINE_NO_ACTION_KEY]: { phrases: ["I don't know what to do with that."] }, + }, +}; + +/** + * Registra los textos por defecto (es, en) solo para las claves que el host no haya + * definido ya. Idempotente; se llama al montar la capa de hotspots, no al importar. + */ +export function ensureEngineTexts(): void { + for (const [locale, defaults] of Object.entries(DEFAULTS)) { + const existing = getDictionary(locale); + const missing: DialogDictionary = {}; + for (const [key, entry] of Object.entries(defaults)) { + if (!existing?.[key]) missing[key] = entry; + } + if (Object.keys(missing).length > 0) registerDictionary(locale, missing); + } +} diff --git a/packages/engine-renderer-r3f/src/index.ts b/packages/engine-renderer-r3f/src/index.ts index 179a25a..ca61bde 100644 --- a/packages/engine-renderer-r3f/src/index.ts +++ b/packages/engine-renderer-r3f/src/index.ts @@ -1,4 +1,4 @@ -export const RENDERER_VERSION = "0.4.0"; +export const RENDERER_VERSION = "0.6.0"; // Canvas core export { GameCanvasCore } from "./components/GameCanvasCore"; @@ -11,8 +11,25 @@ export { WebKeyboardInput } from "./adapters/keyboardInput"; // Sprite export { default as DavidSprite } from "./sprite/DavidSprite"; export type { DavidSpriteHandle } from "./sprite/DavidSprite"; +export { default as CharacterSprite } from "./sprite/CharacterSprite"; +export type { CharacterSpriteHandle } from "./sprite/CharacterSprite"; +export type { + CharacterClip, + CharacterDefinition, + CharacterDirection, +} from "./sprite/character"; +export { + buildFrameUrls, + selectClip, + resolveCharacterSprites, + listCharacterAnimations, + toSpriteAnimation, +} from "./sprite/character"; export * from "./sprite/clips"; export { buildSpeakingAnimation } from "./sprite/speakingAnimation"; +export { NpcSprite, type NpcSpriteProps, type NpcSpeech } from "./sprite/NpcSprite"; +export { selectNpcAnimation } from "./sprite/npcAnimation"; +export { spriteScaleAtDepth, DEPTH_FAR_Z, DEPTH_NEAR_Z } from "./sprite/depthScale"; // Scene export { SceneGround } from "./scene/SceneGround"; @@ -23,15 +40,115 @@ export { computeWallSegments } from "./scene/wallSegments"; export type { WallSegment } from "./scene/wallSegments"; export { SceneCollisionSphere } from "./scene/SceneCollisionSphere"; export { SceneWallPointPreview } from "./scene/SceneWallPointPreview"; +export { SceneNpcs, useVisibleNpcs, type SceneNpcsProps } from "./scene/SceneNpcs"; +export { filterVisibleNpcs, resolveSpeakingNpcId } from "./scene/visibleNpcs"; export { SceneTransitions } from "./scene/SceneTransitions"; +export { SceneHotspots, type SceneHotspotsProps } from "./scene/SceneHotspots"; +export { + filterVisibleHotspots, + planHotspotClick, + buildVerbLabels, + resolveDropOwner, + pointInVolume, + clampMenuPosition, + type HotspotClickPlan, + type VolumeLike, +} from "./scene/hotspotLogic"; +export { + SceneBackgroundPlane, + preloadSceneBackground, +} from "./scene/SceneBackgroundPlane"; +export { + CameraController, + CameraFitHeight, +} from "./scene/SceneCameraControllers"; +export { + WORLD_VIEW_HEIGHT, + CAMERA_POSITION, + CAMERA_ROTATION, +} from "./scene/cameraConstants"; + +// Inventory (scene-side) +export { PlacedSceneItems } from "./inventory/PlacedSceneItems"; +export { + SceneDropTargets, + type SceneDropTargetsProps, + type SceneDropTargetInteraction, + type DraggedInventoryPayload, +} from "./inventory/SceneDropTargets"; + +// Viewport (juego jugable completo) +export { GameViewport, type GameViewportProps } from "./viewport/GameViewport"; +export { + GameViewportView, + type GameViewportViewProps, + type GameViewportSpriteRuntimeProps, +} from "./viewport/GameViewportView"; +export { + useGameViewportController, + type GameViewportController, + type GameViewportControllerOptions, + type GameViewportAudioOptions, +} from "./viewport/useGameViewportController"; // Runtime export { GameTouchSpriteRuntime } from "./GameTouchSpriteRuntime"; export { default as SpeechBubble } from "./SpeechBubble"; +// Hotspots y verbos +export { VerbMenu, type VerbMenuProps } from "./components/VerbMenu"; +export { + useHotspotInteractions, + useVisibleHotspots, + type HotspotMenuState, + type UseHotspotInteractionsOptions, +} from "./hooks/useHotspotInteractions"; +export { + ENGINE_VERB_LABEL_KEYS, + ENGINE_NO_ACTION_KEY, + ensureEngineTexts, +} from "./i18n/engineTexts"; + +// Conversaciones +export { DialogueChoices, type DialogueChoicesProps } from "./components/DialogueChoices"; +export { useDialogue, type UseDialogueResult, type DialogueChoiceItem } from "./hooks/useDialogue"; + // Hooks export { usePlayerWalkAnimation } from "./hooks/usePlayerWalkAnimation"; export { useAudioSystem } from "./hooks/useAudioSystem"; +export { + attachAudioSystem, + type AttachAudioSystemOpts, +} from "./hooks/attachAudioSystem"; +export { useProximityHintController } from "./hooks/useProximityHintController"; +export { + useSceneRuntime, + resolveInitialSceneId, + resolveSceneFromRuntime, + type SceneProgressStorage, + type UseSceneRuntimeOptions, +} from "./hooks/useSceneRuntime"; +export { + useTransitionSystem, + type UseTransitionSystemOpts, +} from "./hooks/useTransitionSystem"; +export { + decideLeaveScene, + resolveUsedTransition, + type CanLeaveScene, + type LeaveSceneTransition, + type LeaveSceneBlock, +} from "./hooks/transitionRules"; +export { + useInventoryRuntime, + type UseInventoryRuntimeOptions, + type SceneEnterApi, +} from "./hooks/useInventoryRuntime"; +export { + seedSceneItems, + type GetInitialPlacedItems, + type SeedStore, +} from "./inventory/seedScene"; export { useClickToMoveController } from "./hooks/useClickToMoveController"; export { useKeyboardMovementInput } from "./adapters/useKeyboardMovementInput"; export type { KeyboardMovementState } from "./adapters/useKeyboardMovementInput"; @@ -48,3 +165,7 @@ export { type LocaleSwitcherProps, type LocaleSwitcherRenderOption, } from "./components/LocaleSwitcher"; + +// Game state hooks +export { useGameState } from "./hooks/useGameState"; +export { useGameActions } from "./hooks/useGameActions"; diff --git a/apps/web-demo/app/components/inventory/PlacedSceneItems.tsx b/packages/engine-renderer-r3f/src/inventory/PlacedSceneItems.tsx similarity index 97% rename from apps/web-demo/app/components/inventory/PlacedSceneItems.tsx rename to packages/engine-renderer-r3f/src/inventory/PlacedSceneItems.tsx index 3cbfc2c..26190b8 100644 --- a/apps/web-demo/app/components/inventory/PlacedSceneItems.tsx +++ b/packages/engine-renderer-r3f/src/inventory/PlacedSceneItems.tsx @@ -3,7 +3,7 @@ import { useEffect, useState } from "react"; import { CuboidCollider, RigidBody } from "@react-three/rapier"; import { Texture, TextureLoader } from "three"; -import type { PlacedSceneItem } from "../../lib/engine/types/gameRuntime"; +import type { PlacedSceneItem } from "@pointclick-engine/engine-core"; function PlacedSceneItemMesh({ item, diff --git a/apps/web-demo/app/components/inventory/SceneDropTargets.tsx b/packages/engine-renderer-r3f/src/inventory/SceneDropTargets.tsx similarity index 87% rename from apps/web-demo/app/components/inventory/SceneDropTargets.tsx rename to packages/engine-renderer-r3f/src/inventory/SceneDropTargets.tsx index 95cdee4..da6aef1 100644 --- a/apps/web-demo/app/components/inventory/SceneDropTargets.tsx +++ b/packages/engine-renderer-r3f/src/inventory/SceneDropTargets.tsx @@ -3,16 +3,23 @@ import { useEffect, useRef } from "react"; import { CuboidCollider, RigidBody } from "@react-three/rapier"; -import type { SceneInteraction } from "../../../demo-content/scenes/scenes"; -import { browserEnvironmentAdapter } from "../../lib/platform-web"; -import type { InventoryStack } from "../InventoryUI"; +import type { + GameSceneInteractionFull, + InventoryStackState, +} from "@pointclick-engine/engine-core"; + +/** Target de drop: interaccion del core mas el flag visual `invisible`. */ +export type SceneDropTargetInteraction = GameSceneInteractionFull & { + invisible?: boolean; +}; +type SceneInteraction = SceneDropTargetInteraction; export type DraggedInventoryPayload = { - stack: InventoryStack; + stack: InventoryStackState; fromSlotIndex: number; }; -type SceneDropTargetsProps = { +export type SceneDropTargetsProps = { targets: SceneInteraction[]; draggedStack: DraggedInventoryPayload | null; onDropHit: (interaction: SceneInteraction, payload: DraggedInventoryPayload) => void; @@ -112,10 +119,11 @@ export function SceneDropTargets({ onDropMiss(draggedStack); }; - return browserEnvironmentAdapter.addWindowEventListener( - "pointerup", - handleWindowPointerUp, - ); + if (typeof window === "undefined") return; + window.addEventListener("pointerup", handleWindowPointerUp, undefined); + return () => { + window.removeEventListener("pointerup", handleWindowPointerUp, undefined); + }; }, [draggedStack, onDropMiss]); if (targets.length === 0 && !playerDropTarget) { diff --git a/packages/engine-renderer-r3f/src/inventory/dropHandlers.ts b/packages/engine-renderer-r3f/src/inventory/dropHandlers.ts new file mode 100644 index 0000000..e5df164 --- /dev/null +++ b/packages/engine-renderer-r3f/src/inventory/dropHandlers.ts @@ -0,0 +1,139 @@ +import { + emitRuntimeEvent, + getInventoryState, + getPlacedItemsState, + removeOneFromSlot, + resolveInventoryDropHitDecision, + resolveInventoryDropMissDialogKey, + resolveInventoryDropOnPlayerMessage, +} from "@pointclick-engine/engine-core"; + +import type { + DraggedInventoryPayload, + DropInteraction, + InventoryHandlerEnv, +} from "./inventoryRuntimeTypes"; + +/** Suelta un item sobre un target que lo acepta: aplica la decision de las reglas. */ +export function applyDropHit( + env: InventoryHandlerEnv, + sceneId: string, + interaction: DropInteraction, + payload: DraggedInventoryPayload, +): void { + const { ctx, getPhrase, showSpeechBubble, onRuntimeEvent, clearDrag } = env; + const decision = resolveInventoryDropHitDecision(ctx, { + interaction, + payload, + now: Date.now(), + }); + + if (decision.kind === "unknown-item") { + emitRuntimeEvent(onRuntimeEvent, { + type: "onDrop", + outcome: "unknown-item", + itemId: payload.stack.id, + interactionId: interaction.id, + }); + showSpeechBubble(decision.message); + clearDrag(); + return; + } + + if (decision.kind === "rule-miss") { + emitRuntimeEvent(onRuntimeEvent, { + type: "onDrop", + outcome: "rule-miss", + itemId: payload.stack.id, + interactionId: interaction.id, + }); + showSpeechBubble(getPhrase(decision.dialogKey), { dialogKey: decision.dialogKey }); + clearDrag(); + return; + } + + if (decision.kind === "place") { + emitRuntimeEvent(onRuntimeEvent, { + type: "onDrop", + outcome: "place", + itemId: payload.stack.id, + interactionId: interaction.id, + }); + getInventoryState().setSlots( + removeOneFromSlot(getInventoryState().slots, decision.fromSlotIndex), + ); + getPlacedItemsState().addItem({ ...decision.placedItem, sceneId }); // sceneId: escena a la que pertenece + showSpeechBubble(getPhrase(decision.dialogKey), { dialogKey: decision.dialogKey }); + clearDrag(); + return; + } + + if (decision.kind === "consume") { + emitRuntimeEvent(onRuntimeEvent, { + type: "onDrop", + outcome: "consume", + itemId: payload.stack.id, + interactionId: interaction.id, + }); + getInventoryState().setSlots( + removeOneFromSlot(getInventoryState().slots, decision.fromSlotIndex), + ); + showSpeechBubble(getPhrase(decision.dialogKey), { dialogKey: decision.dialogKey }); + clearDrag(); + return; + } + + emitRuntimeEvent(onRuntimeEvent, { + type: "onDrop", + outcome: "return", + itemId: payload.stack.id, + interactionId: interaction.id, + }); + showSpeechBubble(getPhrase(decision.dialogKey), { dialogKey: decision.dialogKey }); + clearDrag(); +} + +/** Suelta fuera de un target valido (o sobre uno que no acepta el item): el item vuelve. */ +export function applyDropMiss( + env: InventoryHandlerEnv, + sceneInteractions: DropInteraction[], + payload: DraggedInventoryPayload, + interaction?: DropInteraction, +): void { + const { ctx, getPhrase, showSpeechBubble, onRuntimeEvent, clearDrag } = env; + const fallbackMiss = resolveInventoryDropMissDialogKey(ctx, { + payload, + interaction, + sceneInteractions, + }); + + emitRuntimeEvent(onRuntimeEvent, { + type: "onDrop", + outcome: "return", + itemId: payload.stack.id, + interactionId: interaction?.id, + }); + showSpeechBubble(getPhrase(fallbackMiss), { dialogKey: fallbackMiss }); + clearDrag(); +} + +/** Suelta un item sobre el jugador. */ +export function applyDropOnPlayer( + env: InventoryHandlerEnv, + payload: DraggedInventoryPayload, +): void { + const { ctx, getPhrase, showSpeechBubble, onRuntimeEvent, clearDrag } = env; + const message = resolveInventoryDropOnPlayerMessage(ctx, { payload }); + emitRuntimeEvent(onRuntimeEvent, { + type: "onDrop", + outcome: "on-player", + itemId: payload.stack.id, + }); + if (message.kind === "dialog-key") { + showSpeechBubble(getPhrase(message.dialogKey), { dialogKey: message.dialogKey }); + } else { + showSpeechBubble(message.text); + } + + clearDrag(); +} diff --git a/packages/engine-renderer-r3f/src/inventory/inventoryEnv.ts b/packages/engine-renderer-r3f/src/inventory/inventoryEnv.ts new file mode 100644 index 0000000..07050c6 --- /dev/null +++ b/packages/engine-renderer-r3f/src/inventory/inventoryEnv.ts @@ -0,0 +1,34 @@ +import type { InventoryRuleContext, RuntimeEventHandler } from "@pointclick-engine/engine-core"; + +import type { InventoryHandlerEnv } from "./inventoryRuntimeTypes"; + +export function buildEnv( + injected: { getPhrase: (key: string) => string; itemContext: InventoryRuleContext }, + showSpeechBubble: InventoryHandlerEnv["showSpeechBubble"], + onRuntimeEvent: RuntimeEventHandler | undefined, + setDraggedStack: (value: null) => void, +): InventoryHandlerEnv { + return { + ctx: injected.itemContext, + getPhrase: injected.getPhrase, + showSpeechBubble, + onRuntimeEvent, + clearDrag: () => setDraggedStack(null), + }; +} + +type RafHandle = number; + +export function requestFrame(callback: () => void): RafHandle { + if (typeof window === "undefined") return Number(globalThis.setTimeout(callback, 16)); + return window.requestAnimationFrame(callback); +} + +export function cancelFrame(handle: RafHandle): void { + if (typeof window === "undefined") { + globalThis.clearTimeout(handle); + return; + } + window.cancelAnimationFrame(handle); +} + diff --git a/packages/engine-renderer-r3f/src/inventory/inventoryRuntimeTypes.ts b/packages/engine-renderer-r3f/src/inventory/inventoryRuntimeTypes.ts new file mode 100644 index 0000000..8e7fbba --- /dev/null +++ b/packages/engine-renderer-r3f/src/inventory/inventoryRuntimeTypes.ts @@ -0,0 +1,30 @@ +import type { + GameSceneInteractionFull, + InventoryRuleContext, + InventoryStackState, + RuntimeEventHandler, +} from "@pointclick-engine/engine-core"; + +export type DraggedInventoryPayload = { + stack: InventoryStackState; + fromSlotIndex: number; +}; + +export type RuntimeDraggedStack = DraggedInventoryPayload & { + pointerX: number; + pointerY: number; +}; + +export type SpeechMeta = { source?: "inventory" | "debug"; dialogKey?: string }; +export type ShowSpeechBubble = (text: string, meta?: SpeechMeta) => void; + +/** Dependencias comunes de los manejadores de drop/pickup (puros, sin React). */ +export type InventoryHandlerEnv = { + ctx: InventoryRuleContext; + getPhrase: (key: string) => string; + showSpeechBubble: ShowSpeechBubble; + onRuntimeEvent?: RuntimeEventHandler; + clearDrag: () => void; +}; + +export type DropInteraction = GameSceneInteractionFull; diff --git a/packages/engine-renderer-r3f/src/inventory/pickupHandlers.ts b/packages/engine-renderer-r3f/src/inventory/pickupHandlers.ts new file mode 100644 index 0000000..74c77e4 --- /dev/null +++ b/packages/engine-renderer-r3f/src/inventory/pickupHandlers.ts @@ -0,0 +1,85 @@ +import { + addOneToInventory, + emitRuntimeEvent, + getInventoryState, + getPlacedItemsState, + inventoryRuleMessages, + resolvePickupPlacedItemDecision, + type PlacedSceneItem, +} from "@pointclick-engine/engine-core"; + +import type { InventoryHandlerEnv } from "./inventoryRuntimeTypes"; + +/** + * Recoge un item colocado. `lock` evita dobles recogidas del mismo item mientras + * se resuelve. Los cambios de inventario y de items colocados se aplican juntos. + */ +export function applyPickup( + env: InventoryHandlerEnv, + lock: Set, + isInventoryOpen: boolean, + placedItem: PlacedSceneItem, +): void { + const { ctx, getPhrase, showSpeechBubble, onRuntimeEvent } = env; + if (isInventoryOpen) { + return; + } + + if (lock.has(placedItem.id)) { + return; + } + + lock.add(placedItem.id); + + const decision = resolvePickupPlacedItemDecision(ctx, { placedItem }); + if (decision.kind === "ignore") { + lock.delete(placedItem.id); + return; + } + + if (decision.kind === "blocked") { + emitRuntimeEvent(onRuntimeEvent, { + type: "onDrop", + outcome: "pickup-blocked", + itemId: placedItem.itemId, + interactionId: placedItem.interactionId, + }); + showSpeechBubble(getPhrase(decision.dialogKey), { dialogKey: decision.dialogKey }); + lock.delete(placedItem.id); + return; + } + + // Try to add to inventory first, but don't apply state changes yet + const inventoryResult = addOneToInventory(getInventoryState().slots, decision.stack); + + if (!inventoryResult.added) { + showSpeechBubble(inventoryRuleMessages.inventoryFull); + lock.delete(placedItem.id); + return; + } + + // If we get here, inventory has space. Apply both changes atomically: + // 1. Update inventory + getInventoryState().setSlots(inventoryResult.slots); + + // 2. Remove from placed items + getPlacedItemsState().removeItem(decision.placedItemId); + + emitRuntimeEvent(onRuntimeEvent, { + type: "onDrop", + outcome: "pickup-success", + itemId: placedItem.itemId, + interactionId: placedItem.interactionId, + }); + showSpeechBubble(getPhrase(decision.successDialogKey)); +} + +/** Libera del bloqueo los items que ya no estan colocados. */ +export function releaseStaleLocks(lock: Set, placedItems: PlacedSceneItem[]): void { + if (lock.size === 0) return; + for (const lockedItemId of Array.from(lock)) { + if (!placedItems.some((item) => item.id === lockedItemId)) { + lock.delete(lockedItemId); + } + } +} diff --git a/packages/engine-renderer-r3f/src/inventory/seedScene.ts b/packages/engine-renderer-r3f/src/inventory/seedScene.ts new file mode 100644 index 0000000..4cb8c2e --- /dev/null +++ b/packages/engine-renderer-r3f/src/inventory/seedScene.ts @@ -0,0 +1,52 @@ +import { + getDeclaredScene, + getPlacedItemsState, + getSceneRuleContext, + resolveInitialItems, + type PlacedSceneItem, +} from "@pointclick-engine/engine-core"; + +/** + * Callback de siembra por escena. Devuelve los items a anadir (puede ser `[]`: + * la escena se marca sembrada sin anadir nada) o `null` para indicar que la + * escena no se siembra y NO debe marcarse como sembrada. Un item devuelto sin + * `sceneId` se asigna a la escena que se esta sembrando. + */ +export type GetInitialPlacedItems = ( + sceneId: string, + allItems: PlacedSceneItem[], +) => PlacedSceneItem[] | null; + +/** Subconjunto del store de items colocados que usa la siembra. */ +export type SeedStore = Pick< + ReturnType, + "items" | "setItems" | "markSceneSeeded" | "isSceneSeeded" +>; + +/** + * Siembra los items iniciales de una escena una sola vez. Idempotente. Devuelve true si marco la escena. + * Orden: primero `scene.initialItems` (declarativo, evaluado contra el estado previo a la + * siembra); despues `getInitialPlacedItems`, que ve ya los items declarativos y anade los suyos. + * Sin ninguno de los dos, o con la escena ya sembrada, no hace nada. Si la escena declara + * `initialItems` se marca sembrada aunque el callback devuelva `null`. + */ +export function seedSceneItems( + sceneId: string, + getInitialPlacedItems: GetInitialPlacedItems | undefined, + state: SeedStore = getPlacedItemsState(), +): boolean { + const declared = getDeclaredScene(sceneId)?.initialItems; + if (!getInitialPlacedItems && !Array.isArray(declared)) return false; + if (state.isSceneSeeded(sceneId)) return false; + const fromScene = resolveInitialItems(sceneId, declared, getSceneRuleContext(sceneId, state.items)); + const base = fromScene ? [...state.items, ...fromScene] : state.items; + const fromCallback = getInitialPlacedItems?.(sceneId, base) ?? null; + if (fromScene === null && fromCallback === null) return false; + const owned = (fromCallback ?? []).map((item) => + item.sceneId === undefined ? { ...item, sceneId } : item, + ); + const added = [...(fromScene ?? []), ...owned]; + if (added.length > 0) state.setItems([...state.items, ...added]); + state.markSceneSeeded(sceneId); + return true; +} diff --git a/apps/web-demo/app/components/scene/SceneBackgroundPlane.tsx b/packages/engine-renderer-r3f/src/scene/SceneBackgroundPlane.tsx similarity index 96% rename from apps/web-demo/app/components/scene/SceneBackgroundPlane.tsx rename to packages/engine-renderer-r3f/src/scene/SceneBackgroundPlane.tsx index 4ddbf50..56fcb56 100644 --- a/apps/web-demo/app/components/scene/SceneBackgroundPlane.tsx +++ b/packages/engine-renderer-r3f/src/scene/SceneBackgroundPlane.tsx @@ -5,6 +5,7 @@ import { useFrame } from "@react-three/fiber"; import { DoubleSide, Mesh, TextureLoader, Vector3 } from "three"; import { useSceneStore } from "@pointclick-engine/engine-core"; +import { WORLD_VIEW_HEIGHT } from "./cameraConstants"; /** Precarga el fondo de una escena en el caché del navegador. */ export function preloadSceneBackground(url: string): void { @@ -71,7 +72,7 @@ export function SceneBackgroundPlane({ aspect = textureImage.width / textureImage.height; } - const height = 19.28; + const height = WORLD_VIEW_HEIGHT; const groundCenterX = groundCenterXRef.current; const width = height * aspect; diff --git a/apps/web-demo/app/components/scene/SceneCameraControllers.tsx b/packages/engine-renderer-r3f/src/scene/SceneCameraControllers.tsx similarity index 88% rename from apps/web-demo/app/components/scene/SceneCameraControllers.tsx rename to packages/engine-renderer-r3f/src/scene/SceneCameraControllers.tsx index 30040d4..84d75ac 100644 --- a/apps/web-demo/app/components/scene/SceneCameraControllers.tsx +++ b/packages/engine-renderer-r3f/src/scene/SceneCameraControllers.tsx @@ -4,8 +4,8 @@ import { useFrame } from "@react-three/fiber"; import { MathUtils, OrthographicCamera as ThreeOrthoCamera } from "three"; import { useRef, useEffect } from "react"; -import { browserEnvironmentAdapter } from "../../lib/platform-web"; import { useSceneStore } from "@pointclick-engine/engine-core"; +import { WORLD_VIEW_HEIGHT } from "./cameraConstants"; export function CameraController() { const groundCenterXRef = useRef(0); @@ -44,14 +44,14 @@ export function CameraController() { return null; } -export function CameraFitHeight({ desiredWorldHeight = 19.28 }: { desiredWorldHeight?: number }) { +export function CameraFitHeight({ desiredWorldHeight = WORLD_VIEW_HEIGHT }: { desiredWorldHeight?: number }) { useFrame(({ camera, size }) => { const cam = camera as ThreeOrthoCamera; if (!cam) return; const pixelHeight = Math.max( 1, - size.height || browserEnvironmentAdapter.getInnerHeight(800), + size.height || (typeof window === "undefined" ? 800 : window.innerHeight), ); const targetZoom = pixelHeight / desiredWorldHeight; diff --git a/packages/engine-renderer-r3f/src/scene/SceneCollisionSphere.tsx b/packages/engine-renderer-r3f/src/scene/SceneCollisionSphere.tsx index e5abac6..d0962cb 100644 --- a/packages/engine-renderer-r3f/src/scene/SceneCollisionSphere.tsx +++ b/packages/engine-renderer-r3f/src/scene/SceneCollisionSphere.tsx @@ -2,12 +2,16 @@ import { useLoader } from "@react-three/fiber"; import { BallCollider, RigidBody } from "@react-three/rapier"; -import { TextureLoader } from "three"; +import { TextureLoader, type Texture } from "three"; import { useSceneStore } from "@pointclick-engine/engine-core"; -export function SceneCollisionSphere() { - const globeTexture = useLoader(TextureLoader, "/globe.svg"); +export type SceneCollisionSphereProps = { + /** Textura opcional de la esfera. Sin ella se pinta con un material liso. */ + textureUrl?: string; +}; + +function SphereBody({ texture }: { texture?: Texture }) { const groundY = useSceneStore((s) => s.scene.ground.y); const posY = groundY + 0.1 + 0.5; @@ -24,8 +28,21 @@ export function SceneCollisionSphere() { - + ); } + +function TexturedSphere({ textureUrl }: { textureUrl: string }) { + const texture = useLoader(TextureLoader, textureUrl); + return ; +} + +/** + * Esfera física suelta para probar colisiones. El paquete no trae ningún asset: + * la textura, si se quiere, la aporta el host. + */ +export function SceneCollisionSphere({ textureUrl }: SceneCollisionSphereProps = {}) { + return textureUrl ? : ; +} diff --git a/packages/engine-renderer-r3f/src/scene/SceneHotspots.tsx b/packages/engine-renderer-r3f/src/scene/SceneHotspots.tsx new file mode 100644 index 0000000..0242e18 --- /dev/null +++ b/packages/engine-renderer-r3f/src/scene/SceneHotspots.tsx @@ -0,0 +1,74 @@ +"use client"; + +import type { ThreeEvent } from "@react-three/fiber"; +import type { GameSceneHotspot } from "@pointclick-engine/engine-core"; + +import type { DraggedInventoryPayload } from "../inventory/SceneDropTargets"; +import { DROP_HIT_SCALE, pointInVolume, resolveDropOwner, type VolumeLike } from "./hotspotLogic"; + +export type SceneHotspotsProps = { + hotspots: readonly GameSceneHotspot[]; + /** Item arrastrado ahora, o `null`. */ + draggedStack: DraggedInventoryPayload | null; + /** Dianas de `SceneDropTargets`: si el punto cae en una, gana ella. */ + dropTargets: readonly VolumeLike[]; + onActivate: (hotspot: GameSceneHotspot, screenPosition: { x: number; y: number }) => void; + onDropItem: (hotspot: GameSceneHotspot, itemId: string) => void; + debug?: boolean; +}; + +function toTuple(e: ThreeEvent): [number, number, number] { + return [e.point.x, e.point.y, e.point.z]; +} + +/** + * Volumenes clicables de los hotspots (los NPC incluidos: llegan ya proyectados en + * `scene.hotspots`). Sin hotspots no renderiza nada. El click NO llega al suelo + * (no hay click-to-move) salvo que caiga sobre una diana de arrastre. + */ +export function SceneHotspots({ + hotspots, + draggedStack, + dropTargets, + onActivate, + onDropItem, + debug = false, +}: SceneHotspotsProps) { + if (hotspots.length === 0) return null; + const k = DROP_HIT_SCALE * 2; + return ( + <> + {hotspots.map((hotspot) => { + const [hx, hy, hz] = hotspot.halfSize; + return ( + + { + if (draggedStack) return; + // Sobre una diana, el click sigue su camino de siempre (inspeccion / suelo). + if (dropTargets.some((t) => pointInVolume(toTuple(e), t))) return; + e.stopPropagation(); + onActivate(hotspot, { x: e.clientX, y: e.clientY }); + }} + onPointerUp={(e) => { + if (!draggedStack) return; + if (resolveDropOwner(toTuple(e), dropTargets) === "target") return; + e.stopPropagation(); + onDropItem(hotspot, draggedStack.stack.id); + }} + > + + + + {debug && ( + null}> + + + + )} + + ); + })} + + ); +} diff --git a/packages/engine-renderer-r3f/src/scene/SceneNpcs.tsx b/packages/engine-renderer-r3f/src/scene/SceneNpcs.tsx new file mode 100644 index 0000000..4e0402d --- /dev/null +++ b/packages/engine-renderer-r3f/src/scene/SceneNpcs.tsx @@ -0,0 +1,86 @@ +"use client"; + +import { Suspense, useMemo } from "react"; +import { + useInventoryStateStore, + usePlacedItemsStateStore, + useSceneStore, + useWorldStateStore, + type GameSceneNpc, +} from "@pointclick-engine/engine-core"; + +import type { CharacterDefinition } from "../sprite/character"; +import { NpcSprite } from "../sprite/NpcSprite"; +import { filterVisibleNpcs } from "./visibleNpcs"; + +const NO_NPCS: GameSceneNpc[] = []; + +/** NPCs de la escena activa cuyo `visibleWhen` se cumple; se recalcula al cambiar el estado. */ +export function useVisibleNpcs(): GameSceneNpc[] { + const npcs = useSceneStore((s) => s.scene.npcs); + const sceneId = useSceneStore((s) => s.sceneId); + const flags = useWorldStateStore((s) => s.flags); + const visitedSceneIds = useWorldStateStore((s) => s.visitedSceneIds); + const inventory = useInventoryStateStore((s) => s.slots); + const placedItems = usePlacedItemsStateStore((s) => s.items); + return useMemo( + () => + npcs?.length + ? filterVisibleNpcs(npcs, { flags, inventory, placedItems, sceneId, visitedSceneIds }) + : NO_NPCS, + [npcs, flags, inventory, placedItems, sceneId, visitedSceneIds], + ); +} + +export type SceneNpcsProps = { + /** NPCs a pintar (normalmente `useVisibleNpcs()`). */ + npcs: readonly GameSceneNpc[]; + /** Personajes disponibles por `characterId`. */ + characters?: Record; + /** Id del NPC que habla ahora (ver `resolveSpeakingNpcId`), o `null`. */ + speakingNpcId?: string | null; + speechText?: string; + speechTrigger?: number; + speechCharsPerSecond?: number; + onSpeechDismiss?: () => void; + /** El bocadillo del NPC no se cierra solo. */ + speechPersistent?: boolean; + /** La linea del bocadillo termino de escribirse. */ + onSpeechTypingDone?: (trigger: number) => void; + debug?: boolean; +}; + +const noop = () => {}; + +/** Pinta los sprites de los NPCs. Sin NPCs no renderiza nada. */ +export function SceneNpcs({ + npcs, + characters, + speakingNpcId = null, + speechText = "", + speechTrigger = 0, + speechCharsPerSecond = 28, + onSpeechDismiss = noop, + speechPersistent, + onSpeechTypingDone, + debug = false, +}: SceneNpcsProps) { + if (npcs.length === 0) return null; + return ( + + {npcs.map((npc) => ( + + ))} + + ); +} diff --git a/packages/engine-renderer-r3f/src/scene/cameraConstants.ts b/packages/engine-renderer-r3f/src/scene/cameraConstants.ts new file mode 100644 index 0000000..63af4f8 --- /dev/null +++ b/packages/engine-renderer-r3f/src/scene/cameraConstants.ts @@ -0,0 +1,8 @@ +/** Altura del mundo visible (unidades) con camara ortografica fija. */ +export const WORLD_VIEW_HEIGHT = 19.28; + +/** Posicion de la OrthographicCamera por defecto del juego. */ +export const CAMERA_POSITION: [number, number, number] = [0, 5.4, 25.0]; + +/** Rotacion (Euler XYZ) de la OrthographicCamera por defecto del juego. */ +export const CAMERA_ROTATION: [number, number, number] = [-0.24, 0, 0]; diff --git a/packages/engine-renderer-r3f/src/scene/hotspotLogic.ts b/packages/engine-renderer-r3f/src/scene/hotspotLogic.ts new file mode 100644 index 0000000..f57308d --- /dev/null +++ b/packages/engine-renderer-r3f/src/scene/hotspotLogic.ts @@ -0,0 +1,85 @@ +import { + getAvailableVerbs, + isHotspotVisible, + type ConditionContext, + type GameSceneHotspot, + type Verb, +} from "@pointclick-engine/engine-core"; + +import { ENGINE_VERB_LABEL_KEYS } from "../i18n/engineTexts"; + +type Vec3 = readonly [number, number, number]; + +/** Hotspots cuyo `visibleWhen` se cumple en `ctx`. Puro. */ +export function filterVisibleHotspots( + hotspots: readonly GameSceneHotspot[] | undefined, + ctx: ConditionContext, +): GameSceneHotspot[] { + return (hotspots ?? []).filter((h) => isHotspotVisible(h, ctx)); +} + +/** Que hacer al hacer click: ejecutar un verbo, o abrir el menu si hay varios. */ +export type HotspotClickPlan = + | { kind: "verb"; verb: Verb } + | { kind: "menu"; verbs: Verb[] }; + +/** + * Con un solo verbo aplicable (o ninguno) se ejecuta directo; sin verbos se pide `look`, + * que el core responde con `hotspot:noAction` (frase generica). Con varios, menu. + */ +export function planHotspotClick(hotspot: GameSceneHotspot, ctx: ConditionContext): HotspotClickPlan { + const verbs = getAvailableVerbs(hotspot, ctx); + if (verbs.length > 1) return { kind: "menu", verbs }; + return { kind: "verb", verb: verbs[0] ?? "look" }; +} + +/** Etiquetas de los verbos ya traducidas con `t` (clave del motor, sobrescribible por el host). */ +export function buildVerbLabels(t: (key: string) => string): Record { + return { + look: t(ENGINE_VERB_LABEL_KEYS.look), + use: t(ENGINE_VERB_LABEL_KEYS.use), + talk: t(ENGINE_VERB_LABEL_KEYS.talk), + }; +} + +/** Volumen que usa una diana de arrastre para detectar la suelta (caja de 2.2 x halfSize). */ +export const DROP_HIT_SCALE = 1.1; + +export type VolumeLike = { position: Vec3; halfSize: Vec3; rotationY?: number }; + +/** true si `point` cae dentro de la caja del volumen (rotada en Y), con `scale` sobre `halfSize`. */ +export function pointInVolume(point: Vec3, volume: VolumeLike, scale = DROP_HIT_SCALE): boolean { + const dx = point[0] - volume.position[0]; + const dy = point[1] - volume.position[1]; + const dz = point[2] - volume.position[2]; + const a = volume.rotationY ?? 0; + const lx = dx * Math.cos(a) - dz * Math.sin(a); + const lz = dx * Math.sin(a) + dz * Math.cos(a); + return ( + Math.abs(lx) <= volume.halfSize[0] * scale && + Math.abs(dy) <= volume.halfSize[1] * scale && + Math.abs(lz) <= volume.halfSize[2] * scale + ); +} + +/** + * Conflicto al soltar un item: si el punto cae sobre alguna diana de `SceneDropTargets` + * gana la diana (comportamiento de 0.5.0); si no, es del hotspot. + */ +export function resolveDropOwner(point: Vec3, dropTargets: readonly VolumeLike[]): "target" | "hotspot" { + return dropTargets.some((t) => pointInVolume(point, t)) ? "target" : "hotspot"; +} + +/** Coloca un menu de `size` junto a `pos` sin salirse de la ventana. */ +export function clampMenuPosition( + pos: { x: number; y: number }, + size: { width: number; height: number }, + viewport: { width: number; height: number }, + margin = 8, +): { x: number; y: number } { + const clamp = (v: number, max: number) => Math.max(margin, Math.min(v, max - margin)); + return { + x: clamp(pos.x, viewport.width - size.width), + y: clamp(pos.y, viewport.height - size.height), + }; +} diff --git a/packages/engine-renderer-r3f/src/scene/visibleNpcs.ts b/packages/engine-renderer-r3f/src/scene/visibleNpcs.ts new file mode 100644 index 0000000..3e03bc8 --- /dev/null +++ b/packages/engine-renderer-r3f/src/scene/visibleNpcs.ts @@ -0,0 +1,22 @@ +import { evaluateCondition, type ConditionContext, type GameSceneNpc } from "@pointclick-engine/engine-core"; + +/** NPCs cuyo `visibleWhen` se cumple en `ctx` (sin `visibleWhen`, siempre). Puro. */ +export function filterVisibleNpcs( + npcs: readonly GameSceneNpc[] | undefined, + ctx: ConditionContext, +): GameSceneNpc[] { + return (npcs ?? []).filter((npc) => evaluateCondition(npc.visibleWhen, ctx)); +} + +/** + * Id del NPC visible que habla ahora, o `null` si el bocadillo es del jugador + * (sin `speaker`, "player", un id desconocido o un NPC oculto). + */ +export function resolveSpeakingNpcId( + visibleNpcs: readonly GameSceneNpc[], + speaker: string | undefined, + speechVisible: boolean, +): string | null { + if (!speechVisible || speaker === undefined || speaker === "player") return null; + return visibleNpcs.some((npc) => npc.id === speaker) ? speaker : null; +} diff --git a/packages/engine-renderer-r3f/src/sprite/CharacterSprite.tsx b/packages/engine-renderer-r3f/src/sprite/CharacterSprite.tsx new file mode 100644 index 0000000..eef5f91 --- /dev/null +++ b/packages/engine-renderer-r3f/src/sprite/CharacterSprite.tsx @@ -0,0 +1,230 @@ +"use client"; + +import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from "react"; +import { useFrame, useLoader, useThree } from "@react-three/fiber"; +import { + ClampToEdgeWrapping, + FrontSide, + Mesh, + MeshBasicMaterial, + NearestFilter, + SRGBColorSpace, + Texture, + TextureLoader, +} from "three"; + +import type { ResolvedSpriteAnimation as SpriteAnimation } from "./character"; + +const SHOULD_LOG_SPRITE_STATE = process.env.NODE_ENV !== "production"; +let spriteInstanceCounter = 0; + +function logSpriteState(event: string, payload: Record) { + if (!SHOULD_LOG_SPRITE_STATE) return; + if (typeof window !== "undefined") { + const nextEntry = { scope: "sprite", event, payload, ts: Date.now() }; + const currentTrace = ((window as unknown as { __gameTrace?: unknown[] }).__gameTrace ?? []); + (window as unknown as { __gameTrace: unknown[] }).__gameTrace = [...currentTrace, nextEntry].slice(-300); + } + console.info(`[sprite-state] ${event}`, payload); +} + +type CharacterSpriteProps = { + animation: SpriteAnimation; + preloadAnimations?: readonly SpriteAnimation[]; + meshRef?: React.RefObject; + scale?: [number, number, number]; + isPaused?: boolean; +}; + +export type CharacterSpriteHandle = { + nextFrame: () => void; +}; + +function cloneTexture(sourceTexture: Texture) { + const clonedTexture = sourceTexture.clone(); + clonedTexture.colorSpace = SRGBColorSpace; + clonedTexture.magFilter = NearestFilter; + clonedTexture.minFilter = NearestFilter; + clonedTexture.wrapS = ClampToEdgeWrapping; + clonedTexture.wrapT = ClampToEdgeWrapping; + clonedTexture.generateMipmaps = false; + clonedTexture.needsUpdate = true; + return clonedTexture; +} + +const CharacterSprite = forwardRef( + ({ animation, preloadAnimations, meshRef, scale = [2.2, 2.2, 1], isPaused = false }, ref) => { + const spriteInstanceIdRef = useRef(null); + if (spriteInstanceIdRef.current == null) { + spriteInstanceIdRef.current = ++spriteInstanceCounter; + } + + const internalRef = useRef(null); + const targetRef = meshRef ?? internalRef; + const materialRef = useRef(null); + const renderer = useThree((state) => state.gl); + const preloadedFrames = useMemo(() => { + if (!preloadAnimations?.length) { + return null; + } + + const uniqueFrames = new Set(); + preloadAnimations.forEach((clip) => { + clip.frames.forEach((frame) => { + uniqueFrames.add(frame); + }); + }); + + return Array.from(uniqueFrames); + }, [preloadAnimations]); + + const framesToLoad = preloadedFrames ?? animation.frames; + + const sourceTextures = useLoader(TextureLoader, framesToLoad) as unknown as Texture[]; + + const texturesByFrame = useMemo(() => { + const byFrame = new Map(); + framesToLoad.forEach((frame, index) => { + const sourceTexture = sourceTextures[index]; + if (!sourceTexture) return; + byFrame.set(frame, cloneTexture(sourceTexture)); + }); + return byFrame; + }, [framesToLoad, sourceTextures]); + + const textures = useMemo( + () => + animation.frames + .map((frame) => texturesByFrame.get(frame)) + .filter((texture): texture is Texture => Boolean(texture)), + [animation.frames, texturesByFrame], + ); + + useEffect(() => { + const initTexture = (renderer as unknown as { initTexture?: (texture: Texture) => void }).initTexture; + if (!initTexture) return; + + texturesByFrame.forEach((texture) => { + initTexture(texture); + }); + }, [renderer, texturesByFrame]); + + const frameAspect = useMemo(() => { + const image = textures[0]?.image as { width?: number; height?: number } | undefined; + if (!image?.width || !image?.height) { + return 1; + } + + return image.width / image.height; + }, [textures]); + const frameCursorRef = useRef(0); + const frameTimeRef = useRef(0); + + useEffect(() => { + const instanceId = spriteInstanceIdRef.current; + logSpriteState("mount", { + instanceId, + preloadClipCount: preloadAnimations?.length ?? 1, + loadedFrameCount: framesToLoad.length, + }); + + return () => { + logSpriteState("unmount", { instanceId }); + }; + }, [framesToLoad.length, preloadAnimations]); + + useEffect(() => { + logSpriteState("animation-change", { + instanceId: spriteInstanceIdRef.current, + fps: animation.fps, + frameCount: animation.frames.length, + firstFrame: animation.frames[0], + }); + }, [animation]); + + useEffect(() => { + frameCursorRef.current = 0; + frameTimeRef.current = 0; + + const firstTexture = textures[0]; + const material = materialRef.current; + + if (material && firstTexture) { + material.map = firstTexture; + material.needsUpdate = true; + } + }, [animation, textures]); + + useImperativeHandle( + ref, + () => ({ + nextFrame: () => { + if (textures.length <= 1) { + return; + } + + const clipLength = textures.length; + frameCursorRef.current = animation.loop ?? true + ? (frameCursorRef.current + 1) % clipLength + : Math.min(frameCursorRef.current + 1, clipLength - 1); + + const material = materialRef.current; + const nextTexture = textures[frameCursorRef.current]; + + if (material && nextTexture) { + material.map = nextTexture; + material.needsUpdate = true; + } + }, + }), + [animation.loop, textures], + ); + + useFrame((_, delta) => { + if (isPaused || textures.length <= 1) { + return; + } + + frameTimeRef.current += delta; + const stepTime = 1 / animation.fps; + + if (frameTimeRef.current < stepTime) { + return; + } + + const steps = Math.floor(frameTimeRef.current / stepTime); + frameTimeRef.current -= steps * stepTime; + + frameCursorRef.current = animation.loop ?? true + ? (frameCursorRef.current + steps) % textures.length + : Math.min(frameCursorRef.current + steps, textures.length - 1); + + const material = materialRef.current; + const nextTexture = textures[frameCursorRef.current]; + + if (material && nextTexture) { + material.map = nextTexture; + material.needsUpdate = true; + } + }); + + const [sx, sy, sz] = scale; + const meshScale = useMemo<[number, number, number]>( + () => [animation.flipX ? -Math.abs(sx) : Math.abs(sx), sy, sz], + [animation.flipX, sx, sy, sz], + ); + const planeWidth = 2 * frameAspect; + const planeHeight = 2; + + return ( + + + + + ); + }, +); + +CharacterSprite.displayName = "CharacterSprite"; + +export default CharacterSprite; diff --git a/packages/engine-renderer-r3f/src/sprite/DavidSprite.tsx b/packages/engine-renderer-r3f/src/sprite/DavidSprite.tsx index a3ce1c9..40642a0 100644 --- a/packages/engine-renderer-r3f/src/sprite/DavidSprite.tsx +++ b/packages/engine-renderer-r3f/src/sprite/DavidSprite.tsx @@ -1,230 +1,11 @@ "use client"; -import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from "react"; -import { useFrame, useLoader, useThree } from "@react-three/fiber"; -import { - ClampToEdgeWrapping, - FrontSide, - Mesh, - MeshBasicMaterial, - NearestFilter, - SRGBColorSpace, - Texture, - TextureLoader, -} from "three"; +import CharacterSprite, { type CharacterSpriteHandle } from "./CharacterSprite"; -import type { SpriteAnimation } from "./clips"; +/** @deprecated Use `CharacterSprite`. */ +const DavidSprite = CharacterSprite; -const SHOULD_LOG_SPRITE_STATE = process.env.NODE_ENV !== "production"; -let spriteInstanceCounter = 0; - -function logSpriteState(event: string, payload: Record) { - if (!SHOULD_LOG_SPRITE_STATE) return; - if (typeof window !== "undefined") { - const nextEntry = { scope: "sprite", event, payload, ts: Date.now() }; - const currentTrace = ((window as unknown as { __gameTrace?: unknown[] }).__gameTrace ?? []); - (window as unknown as { __gameTrace: unknown[] }).__gameTrace = [...currentTrace, nextEntry].slice(-300); - } - console.info(`[sprite-state] ${event}`, payload); -} - -type DavidSpriteProps = { - animation: SpriteAnimation; - preloadAnimations?: readonly SpriteAnimation[]; - meshRef?: React.RefObject; - scale?: [number, number, number]; - isPaused?: boolean; -}; - -export type DavidSpriteHandle = { - nextFrame: () => void; -}; - -function cloneTexture(sourceTexture: Texture) { - const clonedTexture = sourceTexture.clone(); - clonedTexture.colorSpace = SRGBColorSpace; - clonedTexture.magFilter = NearestFilter; - clonedTexture.minFilter = NearestFilter; - clonedTexture.wrapS = ClampToEdgeWrapping; - clonedTexture.wrapT = ClampToEdgeWrapping; - clonedTexture.generateMipmaps = false; - clonedTexture.needsUpdate = true; - return clonedTexture; -} - -const DavidSprite = forwardRef( - ({ animation, preloadAnimations, meshRef, scale = [2.2, 2.2, 1], isPaused = false }, ref) => { - const spriteInstanceIdRef = useRef(null); - if (spriteInstanceIdRef.current == null) { - spriteInstanceIdRef.current = ++spriteInstanceCounter; - } - - const internalRef = useRef(null); - const targetRef = meshRef ?? internalRef; - const materialRef = useRef(null); - const renderer = useThree((state) => state.gl); - const preloadedFrames = useMemo(() => { - if (!preloadAnimations?.length) { - return null; - } - - const uniqueFrames = new Set(); - preloadAnimations.forEach((clip) => { - clip.frames.forEach((frame) => { - uniqueFrames.add(frame); - }); - }); - - return Array.from(uniqueFrames); - }, [preloadAnimations]); - - const framesToLoad = preloadedFrames ?? animation.frames; - - const sourceTextures = useLoader(TextureLoader, framesToLoad) as unknown as Texture[]; - - const texturesByFrame = useMemo(() => { - const byFrame = new Map(); - framesToLoad.forEach((frame, index) => { - const sourceTexture = sourceTextures[index]; - if (!sourceTexture) return; - byFrame.set(frame, cloneTexture(sourceTexture)); - }); - return byFrame; - }, [framesToLoad, sourceTextures]); - - const textures = useMemo( - () => - animation.frames - .map((frame) => texturesByFrame.get(frame)) - .filter((texture): texture is Texture => Boolean(texture)), - [animation.frames, texturesByFrame], - ); - - useEffect(() => { - const initTexture = (renderer as unknown as { initTexture?: (texture: Texture) => void }).initTexture; - if (!initTexture) return; - - texturesByFrame.forEach((texture) => { - initTexture(texture); - }); - }, [renderer, texturesByFrame]); - - const frameAspect = useMemo(() => { - const image = textures[0]?.image as { width?: number; height?: number } | undefined; - if (!image?.width || !image?.height) { - return 1; - } - - return image.width / image.height; - }, [textures]); - const frameCursorRef = useRef(0); - const frameTimeRef = useRef(0); - - useEffect(() => { - const instanceId = spriteInstanceIdRef.current; - logSpriteState("mount", { - instanceId, - preloadClipCount: preloadAnimations?.length ?? 1, - loadedFrameCount: framesToLoad.length, - }); - - return () => { - logSpriteState("unmount", { instanceId }); - }; - }, [framesToLoad.length, preloadAnimations]); - - useEffect(() => { - logSpriteState("animation-change", { - instanceId: spriteInstanceIdRef.current, - fps: animation.fps, - frameCount: animation.frames.length, - firstFrame: animation.frames[0], - }); - }, [animation]); - - useEffect(() => { - frameCursorRef.current = 0; - frameTimeRef.current = 0; - - const firstTexture = textures[0]; - const material = materialRef.current; - - if (material && firstTexture) { - material.map = firstTexture; - material.needsUpdate = true; - } - }, [animation, textures]); - - useImperativeHandle( - ref, - () => ({ - nextFrame: () => { - if (textures.length <= 1) { - return; - } - - const clipLength = textures.length; - frameCursorRef.current = animation.loop ?? true - ? (frameCursorRef.current + 1) % clipLength - : Math.min(frameCursorRef.current + 1, clipLength - 1); - - const material = materialRef.current; - const nextTexture = textures[frameCursorRef.current]; - - if (material && nextTexture) { - material.map = nextTexture; - material.needsUpdate = true; - } - }, - }), - [animation.loop, textures], - ); - - useFrame((_, delta) => { - if (isPaused || textures.length <= 1) { - return; - } - - frameTimeRef.current += delta; - const stepTime = 1 / animation.fps; - - if (frameTimeRef.current < stepTime) { - return; - } - - const steps = Math.floor(frameTimeRef.current / stepTime); - frameTimeRef.current -= steps * stepTime; - - frameCursorRef.current = animation.loop ?? true - ? (frameCursorRef.current + steps) % textures.length - : Math.min(frameCursorRef.current + steps, textures.length - 1); - - const material = materialRef.current; - const nextTexture = textures[frameCursorRef.current]; - - if (material && nextTexture) { - material.map = nextTexture; - material.needsUpdate = true; - } - }); - - const [sx, sy, sz] = scale; - const meshScale = useMemo<[number, number, number]>( - () => [animation.flipX ? -Math.abs(sx) : Math.abs(sx), sy, sz], - [animation.flipX, sx, sy, sz], - ); - const planeWidth = 2 * frameAspect; - const planeHeight = 2; - - return ( - - - - - ); - }, -); - -DavidSprite.displayName = "DavidSprite"; +/** @deprecated Use `CharacterSpriteHandle`. */ +export type DavidSpriteHandle = CharacterSpriteHandle; export default DavidSprite; diff --git a/packages/engine-renderer-r3f/src/sprite/NpcSprite.tsx b/packages/engine-renderer-r3f/src/sprite/NpcSprite.tsx new file mode 100644 index 0000000..b5068dc --- /dev/null +++ b/packages/engine-renderer-r3f/src/sprite/NpcSprite.tsx @@ -0,0 +1,95 @@ +"use client"; + +import { useEffect, useMemo } from "react"; +import { CuboidCollider, RigidBody } from "@react-three/rapier"; +import type { GameSceneNpc } from "@pointclick-engine/engine-core"; + +import SpeechBubble from "../SpeechBubble"; +import CharacterSprite from "./CharacterSprite"; +import { DEFAULT_CHARACTER_SIZE, listCharacterAnimations, type CharacterDefinition } from "./character"; +import { spriteScaleAtDepth } from "./depthScale"; +import { selectNpcAnimation } from "./npcAnimation"; + +export type NpcSpeech = { + text: string; + trigger: number; + charsPerSecond: number; + onDismiss: () => void; + persistent?: boolean; + onTypingDone?: (trigger: number) => void; +}; + +export type NpcSpriteProps = { + npc: GameSceneNpc; + /** Personaje registrado para `npc.characterId`; `undefined` si falta. */ + character: CharacterDefinition | undefined; + /** Datos del bocadillo si este NPC es quien habla. */ + speech?: NpcSpeech; + debug?: boolean; +}; + +const warnedMissing = new Set(); + +/** + * Sprite de un NPC. `npc.position` usa la convencion de `playerSpawn` (centro del cuerpo; + * los pies quedan en `y - 0.95`). Con un `characterId` sin registrar avisa una vez por consola + * y solo pinta un volumen en `debug`. + */ +export function NpcSprite({ npc, character, speech, debug = false }: NpcSpriteProps) { + const missing = character === undefined; + useEffect(() => { + if (!missing || warnedMissing.has(npc.characterId)) return; + warnedMissing.add(npc.characterId); + console.warn( + `[npcs] El NPC "${npc.id}" usa el personaje no registrado "${npc.characterId}" (prop \`characters\` del viewport).`, + ); + }, [missing, npc.characterId, npc.id]); + + const size = character?.size ?? DEFAULT_CHARACTER_SIZE; + const scale = spriteScaleAtDepth(npc.position[2], size); + const speaking = speech !== undefined; + const animation = useMemo( + () => + character + ? selectNpcAnimation(character, npc.facing, speaking, speech?.trigger ?? 0, speech?.charsPerSecond ?? 28) + : null, + [character, npc.facing, speaking, speech?.trigger, speech?.charsPerSecond], + ); + const preload = useMemo(() => (character ? listCharacterAnimations(character) : undefined), [character]); + + const centerY = scale - 0.95; + return ( + + {npc.hasCollision && ( + + + + )} + {animation ? ( + + + + ) : ( + debug && ( + null}> + + + + ) + )} + {speech && ( + + )} + + ); +} diff --git a/packages/engine-renderer-r3f/src/sprite/character.ts b/packages/engine-renderer-r3f/src/sprite/character.ts new file mode 100644 index 0000000..6d39994 --- /dev/null +++ b/packages/engine-renderer-r3f/src/sprite/character.ts @@ -0,0 +1,133 @@ +/** + * Agnostic character definition: pure data + pure helpers (no React/Three). + * A consumer describes its own character with `CharacterDefinition` and passes + * it to the runtime. David's definition below is the embedded default kept for + * backwards compatibility. + */ + +export type CharacterDirection = "idle" | "north" | "south" | "west" | "east"; + +export interface CharacterClip { + /** Frame image URLs, in playback order. */ + frames: string[]; + fps: number; + /** Defaults to true. */ + loop?: boolean; + /** Mirror the sprite horizontally while this clip plays. */ + mirror?: boolean; +} + +export interface CharacterDefinition { + id: string; + clips: Record; + /** Clip played while the character speaks and stands idle. */ + speaking?: CharacterClip; + /** + * `[minScale, maxScale]`: sprite scale at the nearest/farthest depth + * (the plane is 2 world units tall before scaling). Default `[1.4, 2.94]`. + */ + size?: [number, number]; +} + +/** Shape consumed by the sprite component (kept for the legacy exports). */ +export interface ResolvedSpriteAnimation { + frames: readonly string[]; + fps: number; + loop?: boolean; + flipX?: boolean; +} + +export const DEFAULT_CHARACTER_SIZE: [number, number] = [1.4, 2.94]; + +/** `/_0001.png`, `_0002.png`, ... (4-digit zero padded). */ +export function buildFrameUrls( + root: string, + prefix: string, + count: number, + startIndex = 1, +): string[] { + return Array.from( + { length: count }, + (_, index) => `${root}/${prefix}_${String(startIndex + index).padStart(4, "0")}.png`, + ); +} + +export function toSpriteAnimation(clip: CharacterClip): ResolvedSpriteAnimation { + const animation: ResolvedSpriteAnimation = { frames: clip.frames, fps: clip.fps }; + if (clip.loop !== undefined) animation.loop = clip.loop; + if (clip.mirror) animation.flipX = true; + return animation; +} + +/** Clip for a direction/action. */ +export function selectClip( + character: CharacterDefinition, + direction: CharacterDirection, +): CharacterClip { + return character.clips[direction]; +} + +/** Resolved animations per direction. */ +export function resolveCharacterSprites( + character: CharacterDefinition, +): Record { + return { + idle: toSpriteAnimation(character.clips.idle), + north: toSpriteAnimation(character.clips.north), + south: toSpriteAnimation(character.clips.south), + west: toSpriteAnimation(character.clips.west), + east: toSpriteAnimation(character.clips.east), + }; +} + +/** Every animation to preload: the 5 direction clips, then speaking (if any). */ +export function listCharacterAnimations( + character: CharacterDefinition, +): ResolvedSpriteAnimation[] { + const sprites = resolveCharacterSprites(character); + const all: ResolvedSpriteAnimation[] = [...Object.values(sprites)]; + if (character.speaking) all.push(toSpriteAnimation(character.speaking)); + return all; +} + +/** Base frames for the varied speaking animation. Falls back to idle frames. */ +export function speakingBaseFrames(character: CharacterDefinition): readonly string[] { + return character.speaking?.frames ?? character.clips.idle.frames; +} + +const DAVE_SPRITE_ROOT = "/assets/sprites/david"; + +/** @deprecated Embedded default. Define your own `CharacterDefinition`. */ +export const DAVE_CHARACTER_DEFINITION: CharacterDefinition = { + id: "david", + clips: { + idle: { frames: [`${DAVE_SPRITE_ROOT}/david_idle.png`], fps: 1, loop: true }, + north: { + frames: buildFrameUrls(DAVE_SPRITE_ROOT, "david-walk-north", 9).reverse(), + fps: 16, + loop: true, + }, + south: { + frames: buildFrameUrls(DAVE_SPRITE_ROOT, "david-walk-south", 8, 3), + fps: 16, + loop: true, + }, + west: { + frames: buildFrameUrls(DAVE_SPRITE_ROOT, "david-walk-west", 9).reverse(), + fps: 16, + loop: true, + mirror: true, + }, + east: { + frames: buildFrameUrls(DAVE_SPRITE_ROOT, "david-walk-west", 9).reverse(), + fps: 16, + loop: true, + }, + }, + speaking: { + frames: buildFrameUrls(DAVE_SPRITE_ROOT, "david_speaking", 8), + fps: 8, + loop: true, + }, + size: [1.4, 2.94], +}; diff --git a/packages/engine-renderer-r3f/src/sprite/clips.ts b/packages/engine-renderer-r3f/src/sprite/clips.ts index b9d63ab..781151b 100644 --- a/packages/engine-renderer-r3f/src/sprite/clips.ts +++ b/packages/engine-renderer-r3f/src/sprite/clips.ts @@ -1,9 +1,11 @@ -export type SpriteAnimation = { - frames: readonly string[]; - fps: number; - loop?: boolean; - flipX?: boolean; -}; +import { + DAVE_CHARACTER_DEFINITION, + resolveCharacterSprites, + toSpriteAnimation, + type ResolvedSpriteAnimation, +} from "./character"; + +export type SpriteAnimation = ResolvedSpriteAnimation; export type GameCharacterName = "Dave"; @@ -17,56 +19,24 @@ type CharacterGridPosition = { row: 0 | 1 | 2; }; -const DAVE_SPRITE_ROOT = "/assets/sprites/david"; - -const createFrameUrls = (prefix: string, count: number, startIndex = 1) => - Array.from( - { length: count }, - (_, index) => - `${DAVE_SPRITE_ROOT}/${prefix}_${String(startIndex + index).padStart(4, "0")}.png`, - ); +const DAVE_CHARACTER_SPRITES: CharacterSprites = resolveCharacterSprites( + DAVE_CHARACTER_DEFINITION, +); -const DAVE_CHARACTER_SPRITES: CharacterSprites = { - idle: { - frames: [`${DAVE_SPRITE_ROOT}/david_idle.png`], - fps: 1, - loop: true, - }, - north: { - frames: createFrameUrls("david-walk-north", 9).slice().reverse(), - fps: 16, - loop: true, - }, - south: { - frames: createFrameUrls("david-walk-south", 8, 3), - fps: 16, - loop: true, - }, - west: { - frames: createFrameUrls("david-walk-west", 9).slice().reverse(), - fps: 16, - loop: true, - flipX: true, - }, - east: { - frames: createFrameUrls("david-walk-west", 9).slice().reverse(), - fps: 16, - loop: true, - }, -}; - -export const DAVE_IDLE_SPEAKING: SpriteAnimation = { - frames: createFrameUrls("david_speaking", 8), - fps: 8, - loop: true, -}; +/** @deprecated Use `CharacterDefinition.speaking`. */ +export const DAVE_IDLE_SPEAKING: SpriteAnimation = toSpriteAnimation( + DAVE_CHARACTER_DEFINITION.speaking!, +); +/** @deprecated Pass a `CharacterDefinition` via the `character` prop. */ export const GAME_CHARACTERS = [ { name: "Dave", column: 0, row: 0 }, ] as const satisfies ReadonlyArray; +/** @deprecated Pass a `CharacterDefinition` via the `character` prop. */ export const GAME_CHARACTER_SPRITES = Object.fromEntries( GAME_CHARACTERS.map((character) => [character.name, DAVE_CHARACTER_SPRITES]), ) as Record; +/** @deprecated Pass a `CharacterDefinition` via the `character` prop. */ export const DAVE_SPRITES = DAVE_CHARACTER_SPRITES; diff --git a/packages/engine-renderer-r3f/src/sprite/depthScale.ts b/packages/engine-renderer-r3f/src/sprite/depthScale.ts new file mode 100644 index 0000000..8ab2084 --- /dev/null +++ b/packages/engine-renderer-r3f/src/sprite/depthScale.ts @@ -0,0 +1,19 @@ +import { MathUtils } from "three"; + +import { DEFAULT_CHARACTER_SIZE } from "./character"; + +/** Z del mundo donde el sprite tiene el tamano minimo / maximo del personaje. */ +export const DEPTH_FAR_Z = -16; +export const DEPTH_NEAR_Z = 8; + +/** + * Escala del sprite segun la profundidad (`z`). Es la formula del jugador: un NPC + * con el mismo `size` y la misma `z` tiene exactamente el mismo tamano. + */ +export function spriteScaleAtDepth( + z: number, + size: readonly [number, number] = DEFAULT_CHARACTER_SIZE, +): number { + const depthFactor = MathUtils.clamp(MathUtils.inverseLerp(DEPTH_FAR_Z, DEPTH_NEAR_Z, z), 0, 1); + return MathUtils.lerp(size[0], size[1], depthFactor); +} diff --git a/packages/engine-renderer-r3f/src/sprite/npcAnimation.ts b/packages/engine-renderer-r3f/src/sprite/npcAnimation.ts new file mode 100644 index 0000000..0c75e8e --- /dev/null +++ b/packages/engine-renderer-r3f/src/sprite/npcAnimation.ts @@ -0,0 +1,29 @@ +import type { GameSceneNpc } from "@pointclick-engine/engine-core"; + +import { + speakingBaseFrames, + toSpriteAnimation, + type CharacterDefinition, + type ResolvedSpriteAnimation, +} from "./character"; +import { buildSpeakingAnimation } from "./speakingAnimation"; + +/** + * Animacion de un NPC (puro): + * - hablando: el clip `speaking` variado (como el jugador); sin `speaking` usa los frames de `idle`. + * - en reposo: el primer frame del clip de `facing` (sin `facing`, el clip `idle`), en bucle. + */ +export function selectNpcAnimation( + character: CharacterDefinition, + facing: GameSceneNpc["facing"], + speaking: boolean, + speechTrigger: number, + charsPerSecond: number, +): ResolvedSpriteAnimation { + if (speaking) { + return buildSpeakingAnimation(speechTrigger, charsPerSecond, speakingBaseFrames(character)); + } + const clip = character.clips[facing ?? "idle"] ?? character.clips.idle; + const still = toSpriteAnimation({ ...clip, frames: clip.frames.slice(0, 1), fps: 1, loop: true }); + return still; +} diff --git a/packages/engine-renderer-r3f/src/sprite/speakingAnimation.ts b/packages/engine-renderer-r3f/src/sprite/speakingAnimation.ts index 2752f47..e1dc237 100644 --- a/packages/engine-renderer-r3f/src/sprite/speakingAnimation.ts +++ b/packages/engine-renderer-r3f/src/sprite/speakingAnimation.ts @@ -1,7 +1,6 @@ import { DAVE_IDLE_SPEAKING, type SpriteAnimation } from "./clips"; -const BASE_FRAMES = DAVE_IDLE_SPEAKING.frames; -const FRAME_COUNT = BASE_FRAMES.length; +const DEFAULT_BASE_FRAMES = DAVE_IDLE_SPEAKING.frames; /** * Builds a varied speaking animation from the base idle-speaking frames. @@ -14,11 +13,16 @@ const FRAME_COUNT = BASE_FRAMES.length; * @param seed speechTrigger value — stabilises the pattern for one * speech event; different dialogues get different patterns. * @param charsPerSecond text reveal speed → drives fps so mouth matches pace. + * @param baseFrames frames of the character's speaking clip (defaults to + * David's, so existing callers behave exactly as before). */ export function buildSpeakingAnimation( seed: number, charsPerSecond: number, + baseFrames: readonly string[] = DEFAULT_BASE_FRAMES, ): SpriteAnimation { + const BASE_FRAMES = baseFrames; + const FRAME_COUNT = BASE_FRAMES.length; const result: string[] = []; let pos = seed % FRAME_COUNT; diff --git a/packages/engine-renderer-r3f/src/viewport/GameViewport.tsx b/packages/engine-renderer-r3f/src/viewport/GameViewport.tsx new file mode 100644 index 0000000..a28ae72 --- /dev/null +++ b/packages/engine-renderer-r3f/src/viewport/GameViewport.tsx @@ -0,0 +1,35 @@ +"use client"; + +import type { GameRuntimeEventHandler, RuntimeEventHandler } from "@pointclick-engine/engine-core"; + +import { + useGameViewportController, + type GameViewportControllerOptions, +} from "./useGameViewportController"; +import { GameViewportView, type GameViewportViewProps } from "./GameViewportView"; + +/** Props del punto de integracion GameViewport (opciones del controlador + props de la vista). */ +export type GameViewportProps = Omit & + Omit & { + /** Activa la depuracion del viewport. */ + debug?: boolean; + /** + * Callback de eventos de runtime (contrato v1). Acepta el tipo publico + * (`GameRuntimeEventHandler`) y el que el motor emite realmente (`RuntimeEventHandler`). + */ + onRuntimeEvent?: GameRuntimeEventHandler | RuntimeEventHandler; + }; + +/** + * Juego jugable en un solo componente. Con los valores por defecto usa el runtime + * activo (`getGameRuntime()`), sin persistencia ni audio y con el personaje incluido. + * Si el host necesita el controlador para su propia UI, usa `useGameViewportController` + * y `GameViewportView` por separado. + */ +export function GameViewport(props: GameViewportProps) { + const controller = useGameViewportController({ + ...props, + onRuntimeEvent: props.onRuntimeEvent as RuntimeEventHandler | undefined, + }); + return ; +} diff --git a/packages/engine-renderer-r3f/src/viewport/GameViewportView.tsx b/packages/engine-renderer-r3f/src/viewport/GameViewportView.tsx new file mode 100644 index 0000000..5c8eb7d --- /dev/null +++ b/packages/engine-renderer-r3f/src/viewport/GameViewportView.tsx @@ -0,0 +1,300 @@ +"use client"; + +import { Suspense, useCallback, useEffect, useRef, type ComponentProps, type ComponentType, type ReactNode } from "react"; +import { Canvas } from "@react-three/fiber"; +import { OrthographicCamera } from "@react-three/drei"; +import { Physics } from "@react-three/rapier"; +import { useInventoryUiStore } from "@pointclick-engine/engine-core"; + +import { DialogueChoices, type DialogueChoicesProps } from "../components/DialogueChoices"; +import { VerbMenu, type VerbMenuProps } from "../components/VerbMenu"; +import { GameTouchSpriteRuntime } from "../GameTouchSpriteRuntime"; +import { useHotspotInteractions } from "../hooks/useHotspotInteractions"; +import type { DraggedInventoryPayload } from "../inventory/inventoryRuntimeTypes"; +import { PlacedSceneItems } from "../inventory/PlacedSceneItems"; +import { SceneDropTargets } from "../inventory/SceneDropTargets"; +import { CAMERA_POSITION, CAMERA_ROTATION, WORLD_VIEW_HEIGHT } from "../scene/cameraConstants"; +import { SceneBackgroundPlane } from "../scene/SceneBackgroundPlane"; +import { CameraController, CameraFitHeight } from "../scene/SceneCameraControllers"; +import { SceneHotspots } from "../scene/SceneHotspots"; +import { SceneNpcs, useVisibleNpcs } from "../scene/SceneNpcs"; +import { resolveSpeakingNpcId } from "../scene/visibleNpcs"; +import { SceneTransitions } from "../scene/SceneTransitions"; +import type { CharacterDefinition } from "../sprite/character"; +import type { GameViewportController } from "./useGameViewportController"; + +/** + * Props de editor / depuracion / entrada que el host pasa a `GameTouchSpriteRuntime`. + * Las que controla el viewport (personaje, bocadillo, eventos) no se pueden sobrescribir. + */ +export type GameViewportSpriteRuntimeProps = Partial< + Omit< + ComponentProps, + | "activeCharacter" + | "character" + | "debug" + | "speechText" + | "speechVisible" + | "speechTrigger" + | "onBoundaryHit" + | "onSpeechDismiss" + | "speechPersistent" + | "onSpeechTypingDone" + | "onRuntimeEvent" + > +>; + +export type GameViewportViewProps = { + /** Resultado de `useGameViewportController`. */ + controller: GameViewportController; + /** Definicion del personaje. Por defecto, el personaje incluido. */ + character?: CharacterDefinition; + /** Personajes de los NPCs de la escena por `characterId` (ver `GameSceneNpc`). */ + characters?: Record; + /** Depuracion del sprite y de las zonas de transicion. Por defecto, la del controlador. */ + debug?: boolean; + /** + * Con `"fixed"` (por defecto) se montan los controladores de camara fija; con cualquier + * otro valor (p. ej. `"free"`) no, y el host aporta la suya por `canvasChildren`. + */ + cameraMode?: "fixed" | (string & {}); + /** Props de editor/depuracion/entrada para `GameTouchSpriteRuntime`. */ + spriteRuntimeProps?: GameViewportSpriteRuntimeProps; + /** + * Condicion extra del host para recoger items. Se suma a las genericas + * (inventario cerrado y sin bocadillo visible). Por defecto `true`. + */ + canPickupItems?: boolean; + /** Contenido extra del Canvas fuera de `` (p. ej. una camara libre). */ + canvasChildren?: ReactNode; + /** Contenido extra DENTRO de `` (p. ej. puertas). */ + children?: ReactNode; + /** HTML por encima del canvas y por debajo de la cortina de fundido. */ + overlay?: ReactNode; + /** Se llama una vez cuando los assets del personaje han resuelto. */ + onSceneReady?: () => void; + /** Menu de verbos de los hotspots con varios verbos. Por defecto, `VerbMenu` del paquete. */ + verbMenu?: ComponentType; + /** Clave de i18n de la frase de `hotspot:noAction`. Por defecto, una clave del motor. */ + noActionDialogKey?: string; + /** Lista de opciones de las conversaciones. Por defecto, `DialogueChoices` del paquete. */ + dialogueChoices?: ComponentType; +}; + +/** + * Se monta dentro del Suspense del runtime: cuando llega al DOM significa que + * useLoader ha resuelto todos los assets del personaje. Llama onReady una sola vez. + */ +function SceneReadyReporter({ onReady }: { onReady: () => void }) { + const onReadyRef = useRef(onReady); + useEffect(() => { onReadyRef.current(); }, []); // intentional: run once on mount + return null; +} + +const noop = () => {}; + +/** Vista presentacional del juego: Canvas, escena, personaje, items y cortina de fundido. */ +export function GameViewportView({ + controller, + character, + characters, + debug = controller.debug, + cameraMode = "fixed", + spriteRuntimeProps, + canPickupItems = true, + canvasChildren, + children, + overlay, + onSceneReady = noop, + verbMenu: VerbMenuComponent = VerbMenu, + noActionDialogKey, + dialogueChoices: DialogueChoicesComponent = DialogueChoices, +}: GameViewportViewProps) { + const { + sceneBackground, + sceneInteractions, + playerPosition, + draggedStack, + scenePlacedItems, + isInventoryOpen, + speechText, + speechVisible, + speechTrigger, + speechSpeaker, + speechPersistent, + onSpeechTypingDone, + dialogue, + dialogueChoicesVisible, + fadeOverlayRef, + handleBackgroundReady, + handleRuntimeEvent, + handleTransitionTriggered, + handleBoundaryHit, + hideSpeechBubble, + handleInteractionInspect, + handleInventoryDropHit, + handleInventoryDropMiss, + handleInventoryDropOnPlayer, + handlePickupPlacedItem, + handleItemInteract, + showSpeechBubble, + clearDrag, + } = controller; + + // Hotspots (y NPCs proyectados): click, menu de verbos y suelta de items. + const hotspotUi = useHotspotInteractions({ showSpeechBubble, clearDrag, noActionDialogKey }); + // La suelta sobre un hotspot no debe disparar ademas el "miss" global de las dianas. + const hotspotDropRef = useRef(false); + const handleHotspotDrop = useCallback( + (hotspot: Parameters[0], itemId: string) => { + hotspotDropRef.current = true; + setTimeout(() => { hotspotDropRef.current = false; }, 0); + hotspotUi.dropItem(hotspot, itemId); + }, + [hotspotUi.dropItem], // eslint-disable-line react-hooks/exhaustive-deps + ); + const handleDropMiss = useCallback( + (...args: Parameters) => { + if (hotspotDropRef.current) return; + handleInventoryDropMiss(...args); + }, + [handleInventoryDropMiss], + ); + const draggedPayload: DraggedInventoryPayload | null = draggedStack + ? { stack: draggedStack.stack, fromSlotIndex: draggedStack.fromSlotIndex } + : null; + + // Si habla un NPC visible, el bocadillo (y el gesto de hablar) es suyo y no del jugador. + const visibleNpcs = useVisibleNpcs(); + const speakingNpcId = resolveSpeakingNpcId(visibleNpcs, speechSpeaker, speechVisible); + const speechCharsPerSecond = spriteRuntimeProps?.speechCharsPerSecond ?? 28; + + return ( +
+ useInventoryUiStore.getState().close()} + onCreated={(state) => { + try { + const glCtx = state.gl.getContext(); + console.log("Three: renderer created", { + contextAttributes: glCtx?.getContextAttributes?.(), + version: glCtx?.getParameter?.(glCtx.VERSION), + shadingLanguageVersion: glCtx?.getParameter?.(glCtx.SHADING_LANGUAGE_VERSION), + }); + state.gl.setClearColor(0x0f0f10, 1); + state.gl.clear(); + } catch (err) { + console.error("Three: onCreated error", err); + } + }} + style={{ position: "absolute", inset: 0, width: "100%", height: "100%", zIndex: 1, background: "transparent", display: "block" }} + > + + {cameraMode === "fixed" && } + + + + {cameraMode === "fixed" && } + {canvasChildren} + + + + + + + + + + {children} + + + + + {overlay} + + {hotspotUi.menu && ( + + )} + + {dialogueChoicesVisible && ( + + )} + + {/* Cortina de transición: siempre en DOM, opacidad 0 en reposo. + Se activa/desactiva via ref para evitar el batching de React. */} +
+
+ ); +} diff --git a/packages/engine-renderer-r3f/src/viewport/useGameViewportController.ts b/packages/engine-renderer-r3f/src/viewport/useGameViewportController.ts new file mode 100644 index 0000000..53f897a --- /dev/null +++ b/packages/engine-renderer-r3f/src/viewport/useGameViewportController.ts @@ -0,0 +1,264 @@ +"use client"; + +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { + getGameRuntime, + legacyRuntimeEventToGameEvent, + useDialogStore, + useDialogueStore, + useSceneStore, + type GameScene, + type GameSceneTransition, + type InventoryRuleContext, + type PlacedSceneItem, + type RuntimeEvent, + type RuntimeEventHandler, +} from "@pointclick-engine/engine-core"; + +import { resolveSpeechDismiss, shouldHoldBubble, shouldShowChoices } from "../hooks/dialogueLogic"; +import { useDialogue } from "../hooks/useDialogue"; +import { + attachAudioSystem, + type AttachAudioSystemOpts, + type MinimalRuntime, +} from "../hooks/attachAudioSystem"; +import { + useInventoryRuntime, + type SceneEnterApi, +} from "../hooks/useInventoryRuntime"; +import { + useSceneRuntime, + type SceneProgressStorage, +} from "../hooks/useSceneRuntime"; +import { useTransitionSystem, type CanLeaveScene } from "../hooks/useTransitionSystem"; +import type { GetInitialPlacedItems } from "../inventory/seedScene"; + +const EMPTY_TRANSITIONS: GameSceneTransition[] = []; + +// Runtime nulo: sin runtime el audio no recibe eventos. +const NOOP_RUNTIME: MinimalRuntime = { on: () => () => {} }; + +/** Filtro por defecto: un item colocado pertenece a la escena que dice su `sceneId`. */ +const defaultFilterPlacedItems = (item: PlacedSceneItem, sceneId: string): boolean => + item.sceneId === sceneId; + +/** Audio opcional: sin esta opcion el viewport no suena. */ +export type GameViewportAudioOptions = Omit & { + scenes?: Record; +}; + +export type GameViewportControllerOptions = { + /** Runtime que alimenta el audio. Por defecto, el runtime activo (`getGameRuntime()`). */ + runtime?: MinimalRuntime | null; + /** Escena a sembrar si no hay una guardada. */ + initialSceneId?: string; + /** Persistencia del id de escena. Sin ella no se guarda. */ + storage?: SceneProgressStorage; + /** Resuelve la escena completa por id. Por defecto, el registro del runtime. */ + resolveScene?: (id: string) => GameScene | null; + /** Regla del juego para permitir o bloquear la salida de una escena. */ + canLeaveScene?: CanLeaveScene; + /** Texto de una clave de dialogo. Por defecto, el `getRandomPhrase` del core. */ + getPhrase?: (key: string) => string; + /** Items iniciales de cada escena (ver `useInventoryRuntime`). */ + getInitialPlacedItems?: GetInitialPlacedItems; + /** Se llama al entrar en una escena (p. ej. un dialogo de bienvenida). */ + onSceneEnter?: (sceneId: string, api: SceneEnterApi) => void; + /** Contexto de reglas de items. Por defecto, el registro del runtime activo. */ + itemContext?: InventoryRuleContext; + /** Audio por puerto. Sin esta opcion no hay audio. */ + audio?: GameViewportAudioOptions; + /** Callback legacy del contrato v1; ademas cada evento se reenvia al bus. */ + onRuntimeEvent?: RuntimeEventHandler; + /** Que items colocados se pintan en la escena actual. Por defecto `item.sceneId === sceneId`. */ + filterPlacedItems?: (item: PlacedSceneItem, sceneId: string) => boolean; + /** + * Arranca el guardado automatico de inventario e items colocados. Se llama una vez + * al montar, justo antes de los efectos del inventario; devuelve su limpieza. + */ + startPersistence?: () => void | (() => void); + /** Registra los eventos de runtime en consola. */ + debug?: boolean; +}; + +/** + * Hook sin JSX que ejecuta los hooks genericos del juego y devuelve todo lo que la + * vista (`GameViewportView`) y la UI del host necesitan. El orden de los hooks es + * deliberado: el audio va ANTES de la siembra de escena (los efectos de un mismo + * componente corren en orden de declaracion y el de la escena inicial emite + * `scene:changed`: el audio ya tiene que estar suscrito). + */ +export function useGameViewportController(options: GameViewportControllerOptions = {}) { + const { + runtime, + initialSceneId, + storage, + resolveScene, + canLeaveScene, + getPhrase, + getInitialPlacedItems, + onSceneEnter, + itemContext, + audio, + onRuntimeEvent, + filterPlacedItems = defaultFilterPlacedItems, + startPersistence, + debug = false, + } = options; + + const baseRuntimeEvent = useCallback((event: RuntimeEvent) => { + // Legacy callback (backwards compat) + onRuntimeEvent?.(event); + // Also emit to the bidirectional event bus (Phase 4) + const gameEvent = legacyRuntimeEventToGameEvent(event); + getGameRuntime()?.emit(gameEvent); + if (!debug) return; + console.debug("[runtime-event]", event); + }, [onRuntimeEvent, debug]); + + // IMPORTANTE: antes de useSceneRuntime (ver comentario del hook). + const audioRuntime = runtime ?? getGameRuntime() ?? NOOP_RUNTIME; + useEffect(() => { + if (!audio) return; + return attachAudioSystem({ ...audio, scenes: audio.scenes ?? {}, runtime: audioRuntime }); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [audioRuntime, audio?.port, audio?.settingsStore]); + + const { + sceneId, + sceneBackground, + storeSetScene, + sceneInteractions, + requestRespawn, + playerPosition, + scenePlayerSpawn, + updateInteraction, + resetInteractionsFromSceneConfig, + } = useSceneRuntime({ initialSceneId, storage, resolveScene }); + + // ── Cortina de fundido para transiciones de escena ─────────────────────── + // El div esta siempre en el DOM. Se manipula directamente (sin estado de React) + // para que la cortina caiga de forma sincrona antes de cualquier re-render con + // los datos de la escena nueva (sin fondo). + const fadeOverlayRef = useRef(null); + + const handleBeforeSceneChange = useCallback(() => { + const el = fadeOverlayRef.current; + if (!el) return; + el.style.transition = "none"; + el.style.opacity = "1"; + el.style.pointerEvents = "all"; + }, []); + + const handleBackgroundReady = useCallback(() => { + const el = fadeOverlayRef.current; + if (!el || el.style.opacity !== "1") return; + // Force layout flush so the transition triggers on the next style change. + el.getBoundingClientRect(); + el.style.transition = "opacity 0.45s ease"; + el.style.opacity = "0"; + el.style.pointerEvents = "none"; + }, []); + + const { handleTransitionTriggered, wrapRuntimeEventForTransitions } = useTransitionSystem({ + onBeforeChange: handleBeforeSceneChange, + resolveScene, + canLeaveScene, + }); + + // Cadena: base (callback del host + bus) -> comprobacion de transiciones por item. + const handleRuntimeEvent = useMemo( + () => wrapRuntimeEventForTransitions(baseRuntimeEvent), + [wrapRuntimeEventForTransitions, baseRuntimeEvent], + ); + + // El estado del dialogo vive en el core (tambien escribible via dialog:trigger / dialog:dismiss) + const speechText = useDialogStore((s) => s.text); + const speechVisible = useDialogStore((s) => s.visible); + const speechTrigger = useDialogStore((s) => s.triggerCount); + const speechSpeaker = useDialogStore((s) => s.speaker); + + // Conversaciones con opciones: la linea queda en el bocadillo hasta elegir; las opciones + // salen al terminar de escribirse. Sin conversacion activa nada de esto cambia nada. + const dialogue = useDialogue(); + const lineKey = useDialogueStore((s) => s.lineKey); + const [typedTrigger, setTypedTrigger] = useState(-1); + const dialogueChoicesVisible = shouldShowChoices({ + active: dialogue.active, + choiceCount: dialogue.choices.length, + hasLine: lineKey !== undefined, + typedTrigger, + triggerCount: speechTrigger, + }); + const speechPersistent = shouldHoldBubble(dialogue.active, dialogue.choices.length); + const dialogueRef = useRef(dialogue); + dialogueRef.current = dialogue; + + const sceneTransitions = useSceneStore((s) => s.scene.transitions ?? EMPTY_TRANSITIONS); + + // Guardado automatico del host. Va ANTES del hook del inventario: sus efectos + // (siembra, bienvenida) corren despues. + useEffect(() => startPersistence?.(), []); // eslint-disable-line react-hooks/exhaustive-deps + + const inventory = useInventoryRuntime({ + sceneId, + sceneInteractions, + playerPosition, + onRuntimeEvent: handleRuntimeEvent, + getPhrase, + getInitialPlacedItems, + onSceneEnter, + itemContext, + }); + + // Cierre del bocadillo: con conversacion activa se avanza por `dialogue:advance` (el core + // emite `dialog:dismissed` y pasa al siguiente nodo); si no, se oculta como siempre. + const { hideSpeechBubble: hideBubbleOnly } = inventory; + const handleSpeechDismiss = useCallback(() => { + if (resolveSpeechDismiss(dialogueRef.current.active) === "advance") dialogueRef.current.advance(); + // Sin conversacion se cierra con el comando `dialog:dismiss`, que emite `dialog:dismissed`: + // una accion `say` de un guion espera ese evento y sin el se quedaria colgada. + else if (getGameRuntime()) getGameRuntime()!.executeCommand({ type: "dialog:dismiss" }); + else hideBubbleOnly(); + }, [hideBubbleOnly]); + + // Items colocados que se pintan en la escena actual. + const scenePlacedItems = inventory.placedItems.filter((item) => filterPlacedItems(item, sceneId)); + + return { + debug, + // Escena + sceneId, + sceneBackground, + storeSetScene, + sceneInteractions, + sceneTransitions, + requestRespawn, + playerPosition, + scenePlayerSpawn, + updateInteraction, + resetInteractionsFromSceneConfig, + // Inventario, arrastre, items colocados y bocadillo + ...inventory, + scenePlacedItems, + speechText, + speechVisible, + speechTrigger, + speechSpeaker, + // Cierre del bocadillo (sustituye al de `...inventory`) + hideSpeechBubble: handleSpeechDismiss, + // Conversaciones + dialogue, + dialogueChoicesVisible, + speechPersistent, + onSpeechTypingDone: setTypedTrigger, + // Eventos y transiciones + handleRuntimeEvent, + handleTransitionTriggered, + // Cortina de fundido + fadeOverlayRef, + handleBackgroundReady, + }; +} + +export type GameViewportController = ReturnType;