@jgengine/react 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/dist/chat.d.ts +52 -0
  3. package/dist/chat.js +68 -0
  4. package/dist/chatBubbles.d.ts +15 -0
  5. package/dist/chatBubbles.js +45 -0
  6. package/dist/components.d.ts +1 -0
  7. package/dist/components.js +35 -22
  8. package/dist/display.d.ts +14 -0
  9. package/dist/display.js +45 -0
  10. package/dist/dragLayer.d.ts +6 -1
  11. package/dist/dragLayer.js +64 -31
  12. package/dist/engineStore.d.ts +1 -1
  13. package/dist/engineStore.js +10 -2
  14. package/dist/fogOverlay.d.ts +21 -0
  15. package/dist/fogOverlay.js +34 -0
  16. package/dist/gameIcons.d.ts +12 -0
  17. package/dist/gameIcons.js +282 -0
  18. package/dist/hooks.d.ts +59 -2
  19. package/dist/hooks.js +170 -12
  20. package/dist/hudLayout.d.ts +61 -0
  21. package/dist/hudLayout.js +488 -0
  22. package/dist/hudViewport.d.ts +21 -0
  23. package/dist/hudViewport.js +17 -0
  24. package/dist/identity.d.ts +65 -0
  25. package/dist/identity.js +94 -0
  26. package/dist/index.d.ts +10 -0
  27. package/dist/index.js +10 -0
  28. package/dist/liveBind.d.ts +4 -10
  29. package/dist/liveBind.js +28 -16
  30. package/dist/map.d.ts +27 -7
  31. package/dist/map.js +152 -43
  32. package/dist/preview.d.ts +6 -0
  33. package/dist/preview.js +1 -0
  34. package/dist/selectSnapshot.d.ts +7 -0
  35. package/dist/selectSnapshot.js +16 -0
  36. package/dist/settings.d.ts +75 -0
  37. package/dist/settings.js +61 -0
  38. package/dist/skillCheckPaint.d.ts +4 -0
  39. package/dist/skillCheckPaint.js +28 -0
  40. package/dist/social.d.ts +108 -0
  41. package/dist/social.js +119 -0
  42. package/dist/voice.d.ts +58 -0
  43. package/dist/voice.js +130 -0
  44. package/llms.txt +1633 -0
  45. package/package.json +11 -6
package/llms.txt ADDED
@@ -0,0 +1,1633 @@
1
+ # @jgengine/react
2
+ > React UI layer for JGengine: GameProvider, hooks, and headless primitives over @jgengine/core.
3
+
4
+ Version: 0.9.0
5
+ License: AGPL-3.0-only
6
+ Repository: https://github.com/Noisemaker111/jgengine
7
+ Docs: https://jgengine.com
8
+ Imports use deep paths: `@jgengine/react/<path>`.
9
+
10
+ ## Exported surface
11
+
12
+ ### @jgengine/react/chat
13
+
14
+ - ChannelTabs (function): function ChannelTabs({ channels, active, onSelect, className, tabClassName, activeTabClassName, renderTab, }: { channels?: readonly string[]; active: string; onSelect: (channelId: string) => void; className?: string; tabClassName?: string; activeTabClassName?: string; renderTab?: (channelId: string,…
15
+ - ChatInput (function): function ChatInput({ channelId, className, inputClassName, buttonClassName, placeholder, sendLabel, onSent, onRejected, }: { channelId: string; className?: string; inputClassName?: string; buttonClassName?: string; placeholder?: string; sendLabel?: ReactNode; onSent?: (message: ChatMessage) => void;…
16
+ - ChatLog (function): function ChatLog({ channelId, limit, className, messageClassName, renderMessage, }: { channelId: string; limit?: number; className?: string; messageClassName?: string; renderMessage?: (message: ChatMessage) => ReactNode; }): React.JSX.Element
17
+ - ChatPanel (function): function ChatPanel({ channels, initialChannel, limit, className, tabsClassName, tabClassName, activeTabClassName, logClassName, messageClassName, inputClassName, inputFieldClassName, sendButtonClassName, placeholder, renderMessage, onRejected, }: { channels?: readonly string[]; initialChannel?: stri…
18
+ - chatTransportFromSync (function): function chatTransportFromSync(sync: ChatSync): ChatTransport — Lifts a callback-style ChatSync (e.g. createWsBackend().chatSyncFor(serverId)) into the hook-shaped ChatTransport contract. Create once per sync — outside render or inside useMemo — so subscriptions survive re-renders.
19
+
20
+ ### @jgengine/react/chatBubbles
21
+
22
+ - ChatBubble (interface): interface ChatBubble
23
+ - ChatBubblesOptions (interface): interface ChatBubblesOptions
24
+ - latestChatBubbles (function): function latestChatBubbles(messages: readonly ChatMessage[], nowMs: number, ttlMs: number): ChatBubble[]
25
+ - useChatBubbles (function): function useChatBubbles(options?: ChatBubblesOptions): readonly ChatBubble[]
26
+ - useEntityChatBubble (function): function useEntityChatBubble(instanceId: string, options?: ChatBubblesOptions): ChatBubble | null
27
+
28
+ ### @jgengine/react/components
29
+
30
+ - CaptureOdds (function): function CaptureOdds({ chance, className, fillClassName, }: { chance: number; className?: string; fillClassName?: string; }): React.JSX.Element
31
+ - CurrencyPill (function): function CurrencyPill({ currencyId, className }: { currencyId: string; className?: string }): React.JSX.Element
32
+ - DeathScreen (function): function DeathScreen({ statId = "health", open, className, children, }: { statId?: string; open?: boolean; className?: string; children?: ReactNode; }): React.JSX.Element
33
+ - DialogueBox (function): function DialogueBox({ dialogue, onChoice, rng, className, lineClassName, speakerClassName, choicesClassName, choiceClassName, checkClassName, }: { dialogue: DialogueDef; onChoice?: (choice: DialogueChoice, result: CheckResult | null) => void; rng?: () => number; className?: string; lineClassName?: …
34
+ - DialogueCheck (interface): interface DialogueCheck
35
+ - DialogueChoice (interface): interface DialogueChoice
36
+ - DialogueDef (interface): interface DialogueDef
37
+ - DialogueLine (type): type DialogueLine = { speaker: string; text: string } | { choices: readonly DialogueChoice[] }
38
+ - HealthBar (function): function HealthBar({ instanceId, statId, className, fillClassName, }: { instanceId: string; statId: string; className?: string; fillClassName?: string; }): React.JSX.Element | null
39
+ - KeybindRow (function): function KeybindRow({ action, keys, className, }: { action: string; keys: readonly string[]; className?: string; }): React.JSX.Element
40
+ - LevelUpFlash (function): function LevelUpFlash({ stat, durationMs = 1600, className, children, renderFlash, }: { stat?: string; durationMs?: number; className?: string; children?: ReactNode; renderFlash?: (event: StatLevelUpEvent) => ReactNode; }): React.JSX.Element | null
41
+ - ProximityPrompt (function): function ProximityPrompt({ prompt, className, }: { prompt: ProximityPromptDef; className?: string; }): React.JSX.Element
42
+ - QteTrack (function): function QteTrack({ steps, startedAt, className, stepClassName, activeClassName, doneClassName, }: { steps: readonly QteStep[]; startedAt: number; className?: string; stepClassName?: string; activeClassName?: string; doneClassName?: string; }): React.JSX.Element
43
+ - Screen (function): function Screen({ id, open = true, className, children, }: { id: string; open?: boolean; className?: string; children?: ReactNode; }): React.JSX.Element | null
44
+ - SkillCheckBar (function): function SkillCheckBar({ config, startedAt, className, trackClassName, zoneClassName, markerClassName, renderStatus, }: { config: SkillCheckConfig; startedAt: number; className?: string; trackClassName?: string; zoneClassName?: string; markerClassName?: string; renderStatus?: (result: SkillCheckResu…
45
+ - SlotGrid (function): function SlotGrid({ inventoryId, className, renderSlot, }: { inventoryId: string; className?: string; renderSlot?: (slot: InventorySlot, index: number) => ReactNode; }): React.JSX.Element
46
+ - ToastStack (function): function ToastStack({ action, limit = 4, className, renderToast, }: { action: string; limit?: number; className?: string; renderToast?: (entry: FeedEntry, index: number) => ReactNode; }): React.JSX.Element | null
47
+ - paintQteStepDom (function): function paintQteStepDom(elements: ReadonlyMap<string, HTMLElement>, steps: readonly QteStep[], elapsed: number, activeId: string | null, stepClassName?: string, activeClassName?: string, doneClassName?: string): void
48
+ - paintSkillCheckDom (function): function paintSkillCheckDom(root: HTMLElement, zone: HTMLElement, marker: HTMLElement, config: SkillCheckConfig, result: SkillCheckResult): void
49
+ - resolveDialogueInvoke (function): function resolveDialogueInvoke(choice: DialogueChoice, result: CheckResult | null): { command: string; args?: unknown } | null
50
+
51
+ ### @jgengine/react/display
52
+
53
+ - DisplayProfile (interface): interface DisplayProfile
54
+ - useDisplayProfile (function): function useDisplayProfile(): DisplayProfile
55
+
56
+ ### @jgengine/react/dragLayer
57
+
58
+ - DragGhost (function): function DragGhost<T>({ layer, className, style, children, }: { layer: DragLayer<T>; className?: string; style?: CSSProperties; children?: (payload: DragPayload<T>) => ReactNode; }): React.JSX.Element | null
59
+ - DragLayer (interface): interface DragLayer<T>
60
+ - DragPayload (interface): interface DragPayload<T>
61
+ - DragState (interface): interface DragState<T>
62
+ - DraggableCard (function): function DraggableCard<T>({ id, value, layer, className, children, onRotate, }: { id: string; value: T; layer: DragLayer<T>; className?: string; children?: ReactNode; onRotate?: boolean; }): React.JSX.Element
63
+ - DropInfo (interface): interface DropInfo<T>
64
+ - DropZone (function): function DropZone<T>({ id, layer, className, activeClassName, cellSize, children, }: { id: string; layer: DragLayer<T>; className?: string; activeClassName?: string; cellSize?: number; children?: ReactNode; }): React.JSX.Element
65
+ - useDragLayer (function): function useDragLayer<T>(options?: { onDrop?: (info: DropInfo<T>) => void; }): DragLayer<T>
66
+
67
+ ### @jgengine/react/engineStore
68
+
69
+ - EventfulEngineStore (interface): interface EventfulEngineStore<TEventMap extends object>
70
+ - ReadableEngineStore (interface): interface ReadableEngineStore<TState>
71
+ - useEngineEvent (function): function useEngineEvent<TEventMap extends object, K extends keyof TEventMap>(store: EventfulEngineStore<TEventMap>, eventName: K, handler: (payload: TEventMap[K]) => void): void
72
+ - useEngineState (function): function useEngineState<TState>(store: ReadableEngineStore<TState>): TState
73
+ - useEngineStore (function): function useEngineStore<TState, TSelected>(store: ReadableEngineStore<TState>, selector: (state: TState) => TSelected, isEqual: (previous: TSelected, next: TSelected) => boolean = Object.is): TSelected
74
+
75
+ ### @jgengine/react/fogOverlay
76
+
77
+ - FogCellRect (interface): interface FogCellRect
78
+ - FogPaintSurface (interface): interface FogPaintSurface
79
+ - createFogDataUrl (function): function createFogDataUrl(fog: FogCells, canvasSize: { width: number; height: number }, cellRect: (col: number, row: number) => FogCellRect | null, fill = "rgba(11, 15, 20, 0.82)"): string | null
80
+ - forEachUnrevealedFogCell (function): function forEachUnrevealedFogCell(fog: FogCells, visit: (col: number, row: number) => void): number
81
+ - paintFogOverlay (function): function paintFogOverlay(surface: FogPaintSurface, canvasSize: { width: number; height: number }, fog: FogCells, cellRect: (col: number, row: number) => FogCellRect | null, fill = "rgba(11, 15, 20, 0.82)"): number
82
+
83
+ ### @jgengine/react/gameIcons
84
+
85
+ - GAME_ICON_NAMES (const): const GAME_ICON_NAMES: readonly ["sword", "dagger", "axe", "hammer", "bow", "arrow", "staff", "wand", "spear", "crossbow", "gun", "bomb", "shield", "helmet", "chestplate", "boots", "gauntlet", "ring", "amulet", "cloak", "backpack", "torch", "potionRed", "potionBlue", "scroll", "tome", "meat", "bread…
86
+ - GameIcon (function): function GameIcon({ name, size = 24, color, className, }: { name: GameIconName; size?: number; color?: string; className?: string; }): React.JSX.Element
87
+ - GameIconName (type): type GameIconName = (typeof GAME_ICON_NAMES)[number]
88
+ - iconForAction (function): function iconForAction(action: string): GameIconName | null — Control glyph for a semantic action name (`hardDrop`, `sprint`, `shiftLeft`), or null when no rule matches.
89
+ - iconForItemId (function): function iconForItemId(itemId: string): GameIconName | null
90
+ - isGameIconName (function): function isGameIconName(value: string): value is GameIconName
91
+
92
+ ### @jgengine/react/hooks
93
+
94
+ - AbilitySlotBindingOptions (interface): interface AbilitySlotBindingOptions
95
+ - EventMeterView (interface): interface EventMeterView
96
+ - UseAxisChannelResult (interface): interface UseAxisChannelResult
97
+ - WorldBrowserState (interface): interface WorldBrowserState
98
+ - abilityKitNeedsHeartbeat (function): function abilityKitNeedsHeartbeat(kit: AbilityKit, resourceAvailable?: number): boolean
99
+ - createHeldKeyTracker (function): function createHeldKeyTracker(target: HeldKeyEventTarget): { isDown: (code: string) => boolean; dispose: () => void; }
100
+ - eventMeterNeedsHeartbeat (function): function eventMeterNeedsHeartbeat(meter: EventMeter, previous: EventMeterView | null): boolean
101
+ - localPlayerEntity (function): function localPlayerEntity(ctx: GameContext): SceneEntity | null
102
+ - useAbilitySlot (function): function useAbilitySlot(kit: AbilityKit, slotId: string, resourceAvailable?: number, options?: AbilitySlotBindingOptions): AbilitySlotSnapshot | null
103
+ - useAbilitySlots (function): function useAbilitySlots(kit: AbilityKit, resourceAvailable?: number, options?: AbilitySlotBindingOptions): AbilitySlotSnapshot[]
104
+ - useActivePrompt (function): function useActivePrompt<T extends PositionedPrompt>(prompts?: readonly T[]): T | null
105
+ - useAxisChannel (function): function useAxisChannel(config: AxisChannelConfig): UseAxisChannelResult — Wires useHeldKeys into a fresh AxisChannel, ready for a per-frame `channel.sample(dt, isDown)`. The channel is recreated when `config` identity changes, so pass a stable config (useMemo/module constant at the call site) unless a rebind is intended.
106
+ - useChat (function): function useChat(channelId: string, options?: { limit?: number }): ChatMessage[]
107
+ - useCurrency (function): function useCurrency(currencyId: string): number
108
+ - useEntityStat (function): function useEntityStat(instanceId: string, statId: string): StatValue | null
109
+ - useEventMeter (function): function useEventMeter(meter: EventMeter, options?: AbilitySlotBindingOptions): EventMeterView
110
+ - useFeed (function): function useFeed({ action, limit }: { action: string; limit?: number }): FeedEntry[]
111
+ - useFriendRequests (function): function useFriendRequests(): FriendRequestEntry[]
112
+ - useFriends (function): function useFriends(): FriendEntry[]
113
+ - useGame (function): function useGame(): { commands: GameContext["game"]["commands"]; events: GameEvents }
114
+ - useGameClock (function): function useGameClock(): ClockSnapshot & { controls: SimClock }
115
+ - useGamePhase (function): function useGamePhase(): { phase: GamePhase; setPhase: (phase: GamePhase) => void } — Live run phase + a setter that also gates the shell's touch controls. `menu`/`paused`/`ended` hide the touch dock; `playing` shows it.
116
+ - useGameStore (function): function useGameStore<T>(selector: (ctx: GameContext) => T, isEqual: (previous: T, next: T) => boolean = Object.is): T
117
+ - useHeldKeys (function): function useHeldKeys(): (code: string) => boolean — Held-key predicate backed by window keydown/keyup/blur listeners (blur clears held state so a released-off-window key doesn't stick). SSR-safe: listeners attach in an effect, never at module scope. The returned predicate is stable across renders.
118
+ - useInventory (function): function useInventory(inventoryId: string): readonly InventorySlot[]
119
+ - useLeaderboard (function): function useLeaderboard(stat: string, options: { scope: LeaderboardScope; limit?: number }): { userId: string; value: number }[]
120
+ - useLocalPlayerDead (function): function useLocalPlayerDead(healthStatId = "health"): boolean
121
+ - useNearestWorldItem (function): function useNearestWorldItem(radius: number): WorldItemRecord | null — Nearest ground item within `radius` of the local player — drives a pickup prompt/highlight.
122
+ - useParty (function): function useParty(): PartyMemberEntry[]
123
+ - usePartyInvites (function): function usePartyInvites(): PartyInviteEntry[]
124
+ - usePlayer (function): function usePlayer(): { userId: string; isNew: boolean }
125
+ - usePresence (function): function usePresence(userId: string): PresenceInfo
126
+ - useQuestJournal (function): function useQuestJournal(): QuestInstance[]
127
+ - useRoster (function): function useRoster(userId?: string): readonly RosterEntry[]
128
+ - useSceneEntities (function): function useSceneEntities(): readonly SceneEntity[]
129
+ - useSceneObjects (function): function useSceneObjects(): readonly SceneObject[]
130
+ - useTarget (function): function useTarget(fromInstanceId: string): string | null
131
+ - useWorldBrowser (function): function useWorldBrowser(options: { fetchSessions: () => Promise<readonly SessionListing[]>; filter?: MatchFilter; limit?: number; refreshMs?: number; }): WorldBrowserState — Polls a host-supplied session fetcher (e.g. createWsBackend().browse) and filters through matchmaking's browseSessions. fetchSessions must be identity-stable (wrap in useCallback at the call site) or every render refetches.
132
+ - useWorldInvites (function): function useWorldInvites(): WorldInvite[]
133
+ - useWorldItems (function): function useWorldItems(): readonly WorldItemRecord[]
134
+
135
+ ### @jgengine/react/hudLayout
136
+
137
+ - HudCanvas (function): function HudCanvas({ layout, editChord, compactScale, className, style, children, }: { layout: HudLayoutStore; editChord?: HudEditChord | false; /** Zoom applied to the whole HUD on compact displays. Default 0.85. */ compactScale?: number; className?: string; style?: CSSProperties; children?: ReactN… — Full-viewport HUD surface. Panels declared with `HudPanel` flow into nine anchor regions and stack automatically with a gap — no per-panel pixel offsets, no manual clearance for sibling panels, the touch-control dock (`--jg-hud-dock-clearance`), or device safe areas. On compact displays the whole surface scales down and each panel applies its `compact` behavior.
138
+ - HudCompactMode (type): type HudCompactMode = "keep" | "chip" | "hide" — How a panel behaves on compact (phone-scale) displays. `keep` stays visible at the global compact scale, `chip` collapses to a small tap-to-expand pill, `hide` unmounts entirely.
139
+ - HudEditChord (interface): interface HudEditChord
140
+ - HudPanel (function): function HudPanel({ id, anchor = "top-left", order, compact: compactMode = "keep", chip, interactive, inset, locked, className, style, children, }: { id: string; anchor?: HudAnchor; /** Stack position within the region, ascending outward from the screen edge. Default 0. */ order?: number; /** Behavi… — A HUD block that lives in one of the nine anchor regions. Panels sharing a region stack outward from the screen edge in ascending `order`. On fine pointers panels stay draggable through the edit chord; a dragged panel leaves the flow and keeps its custom placement. On compact displays custom placements are ignored and the `compact` behavior applies.
141
+ - useHudLayout (function): function useHudLayout(options?: { storageKey?: string; snap?: number; locked?: boolean; }): HudLayoutStore
142
+
143
+ ### @jgengine/react/hudViewport
144
+
145
+ - HudViewportContextValue (interface): interface HudViewportContextValue
146
+ - HudViewportProvider (function): function HudViewportProvider({ platforms, config, userScale, children, }: { platforms: readonly HudPlatform[] | undefined; config: HudViewportConfig | undefined; userScale?: number; children?: ReactNode; }): React.JSX.Element — Mounted by the shell around `GameUI` so every `HudCanvas` inside the game picks up the game's `platforms`/`hudFit` declaration and the player's UI scale setting without any game-side wiring.
147
+ - useHudViewport (function): function useHudViewport(): HudViewportContextValue | null
148
+
149
+ ### @jgengine/react/identity
150
+
151
+ - BetterAuthSessionState (interface): interface BetterAuthSessionState
152
+ - BetterAuthUserShape (interface): interface BetterAuthUserShape
153
+ - ClerkUserShape (interface): interface ClerkUserShape
154
+ - ClerkUserState (interface): interface ClerkUserState
155
+ - GameIdentityProvider (function): function GameIdentityProvider({ source, children, }: { source: IdentitySource; children?: ReactNode; }): React.JSX.Element
156
+ - IdentitySource (interface): interface IdentitySource
157
+ - RequireSession (function): function RequireSession({ fallback, loading, children, }: { fallback?: ReactNode; loading?: ReactNode; children?: ReactNode; }): React.JSX.Element
158
+ - SignOutButton (function): function SignOutButton({ className, children, }: { className?: string; children?: ReactNode; }): React.JSX.Element | null
159
+ - UserBadge (function): function UserBadge({ className, avatarClassName, nameClassName, renderBadge, }: { className?: string; avatarClassName?: string; nameClassName?: string; renderBadge?: (session: AuthSession) => ReactNode; }): React.JSX.Element | null
160
+ - betterAuthIdentity (function): function betterAuthIdentity(state: BetterAuthSessionState, options?: { signOut?: () => void }): IdentitySource
161
+ - clerkIdentity (function): function clerkIdentity(state: ClerkUserState, options?: { signOut?: () => void }): IdentitySource
162
+ - guestIdentity (function): function guestIdentity(seed?: string): IdentitySource
163
+ - useAuthedPlayer (function): function useAuthedPlayer(options?: { guestSeed?: string }): PlayerIdentity | null
164
+ - useSession (function): function useSession(): IdentitySource
165
+
166
+ ### @jgengine/react/index
167
+
168
+ - AbilitySlotBindingOptions (interface): interface AbilitySlotBindingOptions
169
+ - AddFriendButton (function): function AddFriendButton({ toUserId, className, children, onRequested, onRejected, }: { toUserId: string; className?: string; children?: ReactNode; onRequested?: (requestId: string) => void; onRejected?: (reason: string) => void; }): React.JSX.Element
170
+ - BetterAuthSessionState (interface): interface BetterAuthSessionState
171
+ - BetterAuthUserShape (interface): interface BetterAuthUserShape
172
+ - CaptureOdds (function): function CaptureOdds({ chance, className, fillClassName, }: { chance: number; className?: string; fillClassName?: string; }): React.JSX.Element
173
+ - ChannelTabs (function): function ChannelTabs({ channels, active, onSelect, className, tabClassName, activeTabClassName, renderTab, }: { channels?: readonly string[]; active: string; onSelect: (channelId: string) => void; className?: string; tabClassName?: string; activeTabClassName?: string; renderTab?: (channelId: string,…
174
+ - ChatBubble (interface): interface ChatBubble
175
+ - ChatBubblesOptions (interface): interface ChatBubblesOptions
176
+ - ChatInput (function): function ChatInput({ channelId, className, inputClassName, buttonClassName, placeholder, sendLabel, onSent, onRejected, }: { channelId: string; className?: string; inputClassName?: string; buttonClassName?: string; placeholder?: string; sendLabel?: ReactNode; onSent?: (message: ChatMessage) => void;…
177
+ - ChatLog (function): function ChatLog({ channelId, limit, className, messageClassName, renderMessage, }: { channelId: string; limit?: number; className?: string; messageClassName?: string; renderMessage?: (message: ChatMessage) => ReactNode; }): React.JSX.Element
178
+ - ChatPanel (function): function ChatPanel({ channels, initialChannel, limit, className, tabsClassName, tabClassName, activeTabClassName, logClassName, messageClassName, inputClassName, inputFieldClassName, sendButtonClassName, placeholder, renderMessage, onRejected, }: { channels?: readonly string[]; initialChannel?: stri…
179
+ - ClerkUserShape (interface): interface ClerkUserShape
180
+ - ClerkUserState (interface): interface ClerkUserState
181
+ - Compass (function): function Compass({ facingYaw, center, markers, width = 340, fov = (Math.PI * 2) / 3, kindStyles = DEFAULT_MARKER_KINDS, className, }: CompassProps): ReactNode — Horizontal compass strip centered on the player's facing direction, with the eight cardinals and optional marker pips (bearing to each `MarkerSet` entry).
182
+ - CompassProps (interface): interface CompassProps
183
+ - CurrencyPill (function): function CurrencyPill({ currencyId, className }: { currencyId: string; className?: string }): React.JSX.Element
184
+ - DeathScreen (function): function DeathScreen({ statId = "health", open, className, children, }: { statId?: string; open?: boolean; className?: string; children?: ReactNode; }): React.JSX.Element
185
+ - DialogueBox (function): function DialogueBox({ dialogue, onChoice, rng, className, lineClassName, speakerClassName, choicesClassName, choiceClassName, checkClassName, }: { dialogue: DialogueDef; onChoice?: (choice: DialogueChoice, result: CheckResult | null) => void; rng?: () => number; className?: string; lineClassName?: …
186
+ - DialogueCheck (interface): interface DialogueCheck
187
+ - DialogueChoice (interface): interface DialogueChoice
188
+ - DialogueDef (interface): interface DialogueDef
189
+ - DialogueLine (type): type DialogueLine = { speaker: string; text: string } | { choices: readonly DialogueChoice[] }
190
+ - DisplayProfile (interface): interface DisplayProfile
191
+ - DragGhost (function): function DragGhost<T>({ layer, className, style, children, }: { layer: DragLayer<T>; className?: string; style?: CSSProperties; children?: (payload: DragPayload<T>) => ReactNode; }): React.JSX.Element | null
192
+ - DragLayer (interface): interface DragLayer<T>
193
+ - DragPayload (interface): interface DragPayload<T>
194
+ - DragState (interface): interface DragState<T>
195
+ - DraggableCard (function): function DraggableCard<T>({ id, value, layer, className, children, onRotate, }: { id: string; value: T; layer: DragLayer<T>; className?: string; children?: ReactNode; onRotate?: boolean; }): React.JSX.Element
196
+ - DropInfo (interface): interface DropInfo<T>
197
+ - DropZone (function): function DropZone<T>({ id, layer, className, activeClassName, cellSize, children, }: { id: string; layer: DragLayer<T>; className?: string; activeClassName?: string; cellSize?: number; children?: ReactNode; }): React.JSX.Element
198
+ - EmoteWheel (function): function EmoteWheel({ emotes, radius, open = true, className, emoteClassName, onPlayed, onRejected, renderEmote, }: { emotes: readonly string[]; radius?: number; open?: boolean; className?: string; emoteClassName?: string; onPlayed?: (emoteId: string) => void; onRejected?: (reason: string) => void; …
199
+ - EventMeterView (interface): interface EventMeterView
200
+ - EventfulEngineStore (interface): interface EventfulEngineStore<TEventMap extends object>
201
+ - FriendRequestsList (function): function FriendRequestsList({ className, rowClassName, acceptClassName, declineClassName, emptyState, renderRequest, }: { className?: string; rowClassName?: string; acceptClassName?: string; declineClassName?: string; emptyState?: ReactNode; renderRequest?: (request: FriendRequestEntry) => ReactNode…
202
+ - FriendRow (function): function FriendRow({ friend, className, dotClassName, children, }: { friend: FriendEntry; className?: string; dotClassName?: string; children?: ReactNode; }): React.JSX.Element
203
+ - FriendsList (function): function FriendsList({ className, rowClassName, dotClassName, emptyState, renderFriend, }: { className?: string; rowClassName?: string; dotClassName?: string; emptyState?: ReactNode; renderFriend?: (friend: FriendEntry) => ReactNode; }): React.JSX.Element
204
+ - GameIdentityProvider (function): function GameIdentityProvider({ source, children, }: { source: IdentitySource; children?: ReactNode; }): React.JSX.Element
205
+ - GamePreviewComponent (type): type GamePreviewComponent = ComponentType<GamePreviewProps>
206
+ - GamePreviewProps (type): type GamePreviewProps = { className?: string; }
207
+ - GamePreviewStates (type): type GamePreviewStates = Record<string, GamePreviewComponent>
208
+ - GameProvider (function): function GameProvider({ context, children }: { context: GameContext; children?: ReactNode }): React.JSX.Element
209
+ - HealthBar (function): function HealthBar({ instanceId, statId, className, fillClassName, }: { instanceId: string; statId: string; className?: string; fillClassName?: string; }): React.JSX.Element | null
210
+ - HudCanvas (function): function HudCanvas({ layout, editChord, compactScale, className, style, children, }: { layout: HudLayoutStore; editChord?: HudEditChord | false; /** Zoom applied to the whole HUD on compact displays. Default 0.85. */ compactScale?: number; className?: string; style?: CSSProperties; children?: ReactN… — Full-viewport HUD surface. Panels declared with `HudPanel` flow into nine anchor regions and stack automatically with a gap — no per-panel pixel offsets, no manual clearance for sibling panels, the touch-control dock (`--jg-hud-dock-clearance`), or device safe areas. On compact displays the whole surface scales down and each panel applies its `compact` behavior.
211
+ - HudCompactMode (type): type HudCompactMode = "keep" | "chip" | "hide" — How a panel behaves on compact (phone-scale) displays. `keep` stays visible at the global compact scale, `chip` collapses to a small tap-to-expand pill, `hide` unmounts entirely.
212
+ - HudEditChord (interface): interface HudEditChord
213
+ - HudPanel (function): function HudPanel({ id, anchor = "top-left", order, compact: compactMode = "keep", chip, interactive, inset, locked, className, style, children, }: { id: string; anchor?: HudAnchor; /** Stack position within the region, ascending outward from the screen edge. Default 0. */ order?: number; /** Behavi… — A HUD block that lives in one of the nine anchor regions. Panels sharing a region stack outward from the screen edge in ascending `order`. On fine pointers panels stay draggable through the edit chord; a dragged panel leaves the flow and keeps its custom placement. On compact displays custom placements are ignored and the `compact` behavior applies.
214
+ - HudViewportContextValue (interface): interface HudViewportContextValue
215
+ - HudViewportProvider (function): function HudViewportProvider({ platforms, config, userScale, children, }: { platforms: readonly HudPlatform[] | undefined; config: HudViewportConfig | undefined; userScale?: number; children?: ReactNode; }): React.JSX.Element — Mounted by the shell around `GameUI` so every `HudCanvas` inside the game picks up the game's `platforms`/`hudFit` declaration and the player's UI scale setting without any game-side wiring.
216
+ - IdentitySource (interface): interface IdentitySource
217
+ - InviteToWorldButton (function): function InviteToWorldButton({ toUserId, target, className, children, onInvited, onRejected, }: { toUserId: string; target: WorldInviteTarget; className?: string; children?: ReactNode; onInvited?: (inviteId: string) => void; onRejected?: (reason: string) => void; }): React.JSX.Element
218
+ - JoinByCode (function): function JoinByCode({ onJoin, className, inputClassName, buttonClassName, placeholder, children, }: { onJoin: (code: string) => void; className?: string; inputClassName?: string; buttonClassName?: string; placeholder?: string; children?: ReactNode; }): React.JSX.Element
219
+ - KeybindRow (function): function KeybindRow({ action, keys, className, }: { action: string; keys: readonly string[]; className?: string; }): React.JSX.Element
220
+ - LeavePartyButton (function): function LeavePartyButton({ className, children, }: { className?: string; children?: ReactNode; }): React.JSX.Element | null
221
+ - LevelUpFlash (function): function LevelUpFlash({ stat, durationMs = 1600, className, children, renderFlash, }: { stat?: string; durationMs?: number; className?: string; children?: ReactNode; renderFlash?: (event: StatLevelUpEvent) => ReactNode; }): React.JSX.Element | null
222
+ - MapBounds (interface): interface MapBounds
223
+ - MicToggle (function): function MicToggle({ voice, className, mutedLabel, unmutedLabel, }: { voice: VoiceState; className?: string; mutedLabel?: ReactNode; unmutedLabel?: ReactNode; }): React.JSX.Element
224
+ - Minimap (function): function Minimap({ markers, center, worldRadius, fog, size = 176, facingYaw = 0, rotate = false, kindStyles = DEFAULT_MARKER_KINDS, background, mapBounds, routes, zones, cellStates, onWorldClick, className, title = "Map", children, }: MinimapProps): ReactNode — Framed circular minimap: optional baked terrain background, reveal-on-event fog overlay, categorized marker icons, and a facing arrow. Reads a core `MarkerSet` / `FogField`; supply your own `kindStyles` palette to reskin.
225
+ - MinimapProps (interface): interface MinimapProps
226
+ - PartyFrame (function): function PartyFrame({ className, rowClassName, dotClassName, emptyState, renderMember, }: { className?: string; rowClassName?: string; dotClassName?: string; emptyState?: ReactNode; renderMember?: (member: PartyMemberEntry) => ReactNode; }): React.JSX.Element
227
+ - PartyInviteToast (function): function PartyInviteToast({ className, acceptClassName, declineClassName, renderInvite, }: { className?: string; acceptClassName?: string; declineClassName?: string; renderInvite?: (invite: PartyInviteEntry) => ReactNode; }): React.JSX.Element | null
228
+ - PartyMemberRow (function): function PartyMemberRow({ member, className, dotClassName, children, }: { member: PartyMemberEntry; className?: string; dotClassName?: string; children?: ReactNode; }): React.JSX.Element
229
+ - PresenceDot (function): function PresenceDot({ userId, className }: { userId: string; className?: string }): React.JSX.Element
230
+ - ProximityPrompt (function): function ProximityPrompt({ prompt, className, }: { prompt: ProximityPromptDef; className?: string; }): React.JSX.Element
231
+ - PushToTalkButton (function): function PushToTalkButton({ voice, className, children, }: { voice: VoiceState; className?: string; children?: ReactNode; }): React.JSX.Element
232
+ - QteTrack (function): function QteTrack({ steps, startedAt, className, stepClassName, activeClassName, doneClassName, }: { steps: readonly QteStep[]; startedAt: number; className?: string; stepClassName?: string; activeClassName?: string; doneClassName?: string; }): React.JSX.Element
233
+ - QuickMatchButton (function): function QuickMatchButton({ listings, onJoin, onNoMatch, filter, className, children, }: { listings: readonly SessionListing[]; onJoin: (listing: SessionListing) => void; onNoMatch?: () => void; filter?: MatchFilter; className?: string; children?: ReactNode; }): React.JSX.Element
234
+ - ReadableEngineStore (interface): interface ReadableEngineStore<TState>
235
+ - RequireSession (function): function RequireSession({ fallback, loading, children, }: { fallback?: ReactNode; loading?: ReactNode; children?: ReactNode; }): React.JSX.Element
236
+ - Screen (function): function Screen({ id, open = true, className, children, }: { id: string; open?: boolean; className?: string; children?: ReactNode; }): React.JSX.Element | null
237
+ - SettingsActionView (interface): interface SettingsActionView — A resolved game-state action — `run` is already bound to the game context and closes the menu.
238
+ - SettingsCategoryView (interface): interface SettingsCategoryView
239
+ - SettingsController (interface): interface SettingsController — The live settings controller — every category/row/keybind/action plus open-state. Render it any way you like or drive the engine menu.
240
+ - SettingsControllerProvider (function): function SettingsControllerProvider({ controller, children, }: { controller: SettingsController; children: ReactNode; }): React.JSX.Element
241
+ - SettingsKeybindRow (interface): interface SettingsKeybindRow
242
+ - SettingsProvider (function): function SettingsProvider({ store, children }: { store: SettingsStore; children: ReactNode }): React.JSX.Element
243
+ - SettingsRow (interface): interface SettingsRow
244
+ - SettingsTrigger (function): function SettingsTrigger({ className, children, label = "Settings", }: { className?: string; children?: ReactNode; label?: string; }): React.JSX.Element | null — Inline settings entry — drop it anywhere in your game's menu or HUD; it opens the themed settings menu. Headless: pass `className` for placement/skin and `children` to replace the default gear glyph. Renders nothing when the game has no settings to show, so it never leaves a dead button behind.
245
+ - SignOutButton (function): function SignOutButton({ className, children, }: { className?: string; children?: ReactNode; }): React.JSX.Element | null
246
+ - SkillCheckBar (function): function SkillCheckBar({ config, startedAt, className, trackClassName, zoneClassName, markerClassName, renderStatus, }: { config: SkillCheckConfig; startedAt: number; className?: string; trackClassName?: string; zoneClassName?: string; markerClassName?: string; renderStatus?: (result: SkillCheckResu…
247
+ - SlotGrid (function): function SlotGrid({ inventoryId, className, renderSlot, }: { inventoryId: string; className?: string; renderSlot?: (slot: InventorySlot, index: number) => ReactNode; }): React.JSX.Element
248
+ - SpeakingIndicator (function): function SpeakingIndicator({ voice, userId, className, threshold = 0.01, children, }: { voice: VoiceState; userId: string; className?: string; threshold?: number; children?: ReactNode; }): React.JSX.Element
249
+ - ToastStack (function): function ToastStack({ action, limit = 4, className, renderToast, }: { action: string; limit?: number; className?: string; renderToast?: (entry: FeedEntry, index: number) => ReactNode; }): React.JSX.Element | null
250
+ - UseAxisChannelResult (interface): interface UseAxisChannelResult
251
+ - UseVoiceOptions (interface): interface UseVoiceOptions
252
+ - UserBadge (function): function UserBadge({ className, avatarClassName, nameClassName, renderBadge, }: { className?: string; avatarClassName?: string; nameClassName?: string; renderBadge?: (session: AuthSession) => ReactNode; }): React.JSX.Element | null
253
+ - VoiceRoster (function): function VoiceRoster({ voice, className, participantClassName, renderParticipant, }: { voice: VoiceState; className?: string; participantClassName?: string; renderParticipant?: (participant: VoiceParticipant, gain: number) => ReactNode; }): React.JSX.Element
254
+ - VoiceState (interface): interface VoiceState
255
+ - WorldBrowser (function): function WorldBrowser({ listings, onJoin, className, rowClassName, joinClassName, emptyState, renderListing, }: { listings: readonly SessionListing[]; onJoin: (listing: SessionListing) => void; className?: string; rowClassName?: string; joinClassName?: string; emptyState?: ReactNode; renderListing?:…
256
+ - WorldBrowserState (interface): interface WorldBrowserState
257
+ - WorldInviteToast (function): function WorldInviteToast({ className, acceptClassName, declineClassName, onAccepted, renderInvite, }: { className?: string; acceptClassName?: string; declineClassName?: string; onAccepted: (target: WorldInviteTarget) => void; renderInvite?: (invite: WorldInvite) => ReactNode; }): React.JSX.Element …
258
+ - WorldMap (function): function WorldMap({ markers, bounds, player, facingYaw = 0, fog, background, width = 520, height, kindStyles = DEFAULT_MARKER_KINDS, routes, zones, cellStates, onWorldClick, className, title = "World Map", onClose, }: WorldMapProps): ReactNode — Full-bounds top-down world map (the "press M" overlay): baked terrain background, reveal-on-event fog, all markers with labels, and the player. Rectangular linear projection over the supplied world `bounds`.
259
+ - WorldMapProps (interface): interface WorldMapProps
260
+ - abilityKitNeedsHeartbeat (function): function abilityKitNeedsHeartbeat(kit: AbilityKit, resourceAvailable?: number): boolean
261
+ - betterAuthIdentity (function): function betterAuthIdentity(state: BetterAuthSessionState, options?: { signOut?: () => void }): IdentitySource
262
+ - chatTransportFromSync (function): function chatTransportFromSync(sync: ChatSync): ChatTransport — Lifts a callback-style ChatSync (e.g. createWsBackend().chatSyncFor(serverId)) into the hook-shaped ChatTransport contract. Create once per sync — outside render or inside useMemo — so subscriptions survive re-renders.
263
+ - clerkIdentity (function): function clerkIdentity(state: ClerkUserState, options?: { signOut?: () => void }): IdentitySource
264
+ - createHeldKeyTracker (function): function createHeldKeyTracker(target: HeldKeyEventTarget): { isDown: (code: string) => boolean; dispose: () => void; }
265
+ - eventMeterNeedsHeartbeat (function): function eventMeterNeedsHeartbeat(meter: EventMeter, previous: EventMeterView | null): boolean
266
+ - guestIdentity (function): function guestIdentity(seed?: string): IdentitySource
267
+ - latestChatBubbles (function): function latestChatBubbles(messages: readonly ChatMessage[], nowMs: number, ttlMs: number): ChatBubble[]
268
+ - localPlayerEntity (function): function localPlayerEntity(ctx: GameContext): SceneEntity | null
269
+ - paintQteStepDom (function): function paintQteStepDom(elements: ReadonlyMap<string, HTMLElement>, steps: readonly QteStep[], elapsed: number, activeId: string | null, stepClassName?: string, activeClassName?: string, doneClassName?: string): void
270
+ - paintSkillCheckDom (function): function paintSkillCheckDom(root: HTMLElement, zone: HTMLElement, marker: HTMLElement, config: SkillCheckConfig, result: SkillCheckResult): void
271
+ - resolveDialogueInvoke (function): function resolveDialogueInvoke(choice: DialogueChoice, result: CheckResult | null): { command: string; args?: unknown } | null
272
+ - useAbilitySlot (function): function useAbilitySlot(kit: AbilityKit, slotId: string, resourceAvailable?: number, options?: AbilitySlotBindingOptions): AbilitySlotSnapshot | null
273
+ - useAbilitySlots (function): function useAbilitySlots(kit: AbilityKit, resourceAvailable?: number, options?: AbilitySlotBindingOptions): AbilitySlotSnapshot[]
274
+ - useActivePrompt (function): function useActivePrompt<T extends PositionedPrompt>(prompts?: readonly T[]): T | null
275
+ - useAuthedPlayer (function): function useAuthedPlayer(options?: { guestSeed?: string }): PlayerIdentity | null
276
+ - useAxisChannel (function): function useAxisChannel(config: AxisChannelConfig): UseAxisChannelResult — Wires useHeldKeys into a fresh AxisChannel, ready for a per-frame `channel.sample(dt, isDown)`. The channel is recreated when `config` identity changes, so pass a stable config (useMemo/module constant at the call site) unless a rebind is intended.
277
+ - useChat (function): function useChat(channelId: string, options?: { limit?: number }): ChatMessage[]
278
+ - useChatBubbles (function): function useChatBubbles(options?: ChatBubblesOptions): readonly ChatBubble[]
279
+ - useCurrency (function): function useCurrency(currencyId: string): number
280
+ - useDisplayProfile (function): function useDisplayProfile(): DisplayProfile
281
+ - useDragLayer (function): function useDragLayer<T>(options?: { onDrop?: (info: DropInfo<T>) => void; }): DragLayer<T>
282
+ - useEngineEvent (function): function useEngineEvent<TEventMap extends object, K extends keyof TEventMap>(store: EventfulEngineStore<TEventMap>, eventName: K, handler: (payload: TEventMap[K]) => void): void
283
+ - useEngineState (function): function useEngineState<TState>(store: ReadableEngineStore<TState>): TState
284
+ - useEngineStore (function): function useEngineStore<TState, TSelected>(store: ReadableEngineStore<TState>, selector: (state: TState) => TSelected, isEqual: (previous: TSelected, next: TSelected) => boolean = Object.is): TSelected
285
+ - useEntityChatBubble (function): function useEntityChatBubble(instanceId: string, options?: ChatBubblesOptions): ChatBubble | null
286
+ - useEntityStat (function): function useEntityStat(instanceId: string, statId: string): StatValue | null
287
+ - useEventMeter (function): function useEventMeter(meter: EventMeter, options?: AbilitySlotBindingOptions): EventMeterView
288
+ - useFeed (function): function useFeed({ action, limit }: { action: string; limit?: number }): FeedEntry[]
289
+ - useFog (function): function useFog(fog: FogField): ReturnType<FogField["cells"]>
290
+ - useFriendRequests (function): function useFriendRequests(): FriendRequestEntry[]
291
+ - useFriends (function): function useFriends(): FriendEntry[]
292
+ - useGame (function): function useGame(): { commands: GameContext["game"]["commands"]; events: GameEvents }
293
+ - useGameClock (function): function useGameClock(): ClockSnapshot & { controls: SimClock }
294
+ - useGameContext (function): function useGameContext(): GameContext
295
+ - useGamePhase (function): function useGamePhase(): { phase: GamePhase; setPhase: (phase: GamePhase) => void } — Live run phase + a setter that also gates the shell's touch controls. `menu`/`paused`/`ended` hide the touch dock; `playing` shows it.
296
+ - useGameStore (function): function useGameStore<T>(selector: (ctx: GameContext) => T, isEqual: (previous: T, next: T) => boolean = Object.is): T
297
+ - useHasSettings (function): function useHasSettings(): boolean — True when the game has any setting or game-action to show — gate your own settings entry on it.
298
+ - useHeldKeys (function): function useHeldKeys(): (code: string) => boolean — Held-key predicate backed by window keydown/keyup/blur listeners (blur clears held state so a released-off-window key doesn't stick). SSR-safe: listeners attach in an effect, never at module scope. The returned predicate is stable across renders.
299
+ - useHudLayout (function): function useHudLayout(options?: { storageKey?: string; snap?: number; locked?: boolean; }): HudLayoutStore
300
+ - useHudViewport (function): function useHudViewport(): HudViewportContextValue | null
301
+ - useInventory (function): function useInventory(inventoryId: string): readonly InventorySlot[]
302
+ - useLeaderboard (function): function useLeaderboard(stat: string, options: { scope: LeaderboardScope; limit?: number }): { userId: string; value: number }[]
303
+ - useLocalPlayerDead (function): function useLocalPlayerDead(healthStatId = "health"): boolean
304
+ - useMarkers (function): function useMarkers(markers: MarkerSet): readonly MapMarker[]
305
+ - useNearestWorldItem (function): function useNearestWorldItem(radius: number): WorldItemRecord | null — Nearest ground item within `radius` of the local player — drives a pickup prompt/highlight.
306
+ - useParty (function): function useParty(): PartyMemberEntry[]
307
+ - usePartyInvites (function): function usePartyInvites(): PartyInviteEntry[]
308
+ - usePlayer (function): function usePlayer(): { userId: string; isNew: boolean }
309
+ - usePresence (function): function usePresence(userId: string): PresenceInfo
310
+ - useQuestJournal (function): function useQuestJournal(): QuestInstance[]
311
+ - useRoster (function): function useRoster(userId?: string): readonly RosterEntry[]
312
+ - useSceneEntities (function): function useSceneEntities(): readonly SceneEntity[]
313
+ - useSceneObjects (function): function useSceneObjects(): readonly SceneObject[]
314
+ - useSession (function): function useSession(): IdentitySource
315
+ - useSetting (function): function useSetting<T extends SettingValue>(id: string, fallback: T): readonly [T, (value: SettingValue) => void] — Read + write one persisted setting; re-renders when the value changes anywhere.
316
+ - useSettings (function): function useSettings(): SettingsController — The engine settings controller for the current game — render your own settings UI from `categories`, or open the built-in menu with `open()`. Null-safe stub when mounted outside the shell.
317
+ - useSettingsStore (function): function useSettingsStore(): SettingsStore — The shared settings store, or a standalone one when no provider is mounted (game code read outside the shell).
318
+ - useTarget (function): function useTarget(fromInstanceId: string): string | null
319
+ - useVoice (function): function useVoice(options?: UseVoiceOptions): VoiceState — Mic capture + push-to-talk + channel roster over the VoiceTransport signaling seam. Transmission gates the captured tracks' `enabled` flag; the media plane that actually moves audio bytes (WebRTC/SFU) stays behind the transport, host-supplied. Call once per voice channel and hand the returned state to the voice components.
320
+ - useWorldBrowser (function): function useWorldBrowser(options: { fetchSessions: () => Promise<readonly SessionListing[]>; filter?: MatchFilter; limit?: number; refreshMs?: number; }): WorldBrowserState — Polls a host-supplied session fetcher (e.g. createWsBackend().browse) and filters through matchmaking's browseSessions. fetchSessions must be identity-stable (wrap in useCallback at the call site) or every render refetches.
321
+ - useWorldInvites (function): function useWorldInvites(): WorldInvite[]
322
+ - useWorldItems (function): function useWorldItems(): readonly WorldItemRecord[]
323
+
324
+ ### @jgengine/react/liveBind
325
+
326
+ - LiveText (function): function LiveText({ get, format, className, style, }: { get: () => number | string; format?: (value: number | string) => string; className?: string; style?: CSSProperties; }): React.JSX.Element
327
+ - frameBindSubscriberCount (function): function frameBindSubscriberCount(): number
328
+ - subscribeFrameBind (function): function subscribeFrameBind(subscriber: FrameSubscriber): () => void
329
+ - useFrameBind (function): function useFrameBind<T, E extends Element = Element>(ref: { current: E | null }, get: () => T, apply: (value: T, element: E) => void): void
330
+
331
+ ### @jgengine/react/map
332
+
333
+ - Compass (function): function Compass({ facingYaw, center, markers, width = 340, fov = (Math.PI * 2) / 3, kindStyles = DEFAULT_MARKER_KINDS, className, }: CompassProps): ReactNode — Horizontal compass strip centered on the player's facing direction, with the eight cardinals and optional marker pips (bearing to each `MarkerSet` entry).
334
+ - CompassProps (interface): interface CompassProps
335
+ - MapBounds (interface): interface MapBounds
336
+ - Minimap (function): function Minimap({ markers, center, worldRadius, fog, size = 176, facingYaw = 0, rotate = false, kindStyles = DEFAULT_MARKER_KINDS, background, mapBounds, routes, zones, cellStates, onWorldClick, className, title = "Map", children, }: MinimapProps): ReactNode — Framed circular minimap: optional baked terrain background, reveal-on-event fog overlay, categorized marker icons, and a facing arrow. Reads a core `MarkerSet` / `FogField`; supply your own `kindStyles` palette to reskin.
337
+ - MinimapProps (interface): interface MinimapProps
338
+ - WorldMap (function): function WorldMap({ markers, bounds, player, facingYaw = 0, fog, background, width = 520, height, kindStyles = DEFAULT_MARKER_KINDS, routes, zones, cellStates, onWorldClick, className, title = "World Map", onClose, }: WorldMapProps): ReactNode — Full-bounds top-down world map (the "press M" overlay): baked terrain background, reveal-on-event fog, all markers with labels, and the player. Rectangular linear projection over the supplied world `bounds`.
339
+ - WorldMapProps (interface): interface WorldMapProps
340
+ - useFog (function): function useFog(fog: FogField): ReturnType<FogField["cells"]>
341
+ - useMarkers (function): function useMarkers(markers: MarkerSet): readonly MapMarker[]
342
+
343
+ ### @jgengine/react/preview
344
+
345
+ - GamePreviewComponent (type): type GamePreviewComponent = ComponentType<GamePreviewProps>
346
+ - GamePreviewProps (type): type GamePreviewProps = { className?: string; }
347
+ - GamePreviewStates (type): type GamePreviewStates = Record<string, GamePreviewComponent>
348
+
349
+ ### @jgengine/react/provider
350
+
351
+ - GameProvider (function): function GameProvider({ context, children }: { context: GameContext; children?: ReactNode }): React.JSX.Element
352
+ - useGameContext (function): function useGameContext(): GameContext
353
+
354
+ ### @jgengine/react/selectSnapshot
355
+
356
+ - SelectCache (type): type SelectCache<TSnapshot, TSelected> = { ready: boolean; snapshot: TSnapshot; value: TSelected; }
357
+ - createSelectCache (function): function createSelectCache<TSnapshot, TSelected>(): SelectCache<TSnapshot, TSelected>
358
+ - readSelectSnapshot (function): function readSelectSnapshot<TSnapshot, TSelected>(cache: SelectCache<TSnapshot, TSelected>, snapshot: TSnapshot, select: (snapshot: TSnapshot) => TSelected, isEqual: (previous: TSelected, next: TSelected) => boolean = Object.is): TSelected
359
+
360
+ ### @jgengine/react/settings
361
+
362
+ - SettingsActionView (interface): interface SettingsActionView — A resolved game-state action — `run` is already bound to the game context and closes the menu.
363
+ - SettingsCategoryView (interface): interface SettingsCategoryView
364
+ - SettingsController (interface): interface SettingsController — The live settings controller — every category/row/keybind/action plus open-state. Render it any way you like or drive the engine menu.
365
+ - SettingsControllerProvider (function): function SettingsControllerProvider({ controller, children, }: { controller: SettingsController; children: ReactNode; }): React.JSX.Element
366
+ - SettingsKeybindRow (interface): interface SettingsKeybindRow
367
+ - SettingsProvider (function): function SettingsProvider({ store, children }: { store: SettingsStore; children: ReactNode }): React.JSX.Element
368
+ - SettingsRow (interface): interface SettingsRow
369
+ - SettingsTrigger (function): function SettingsTrigger({ className, children, label = "Settings", }: { className?: string; children?: ReactNode; label?: string; }): React.JSX.Element | null — Inline settings entry — drop it anywhere in your game's menu or HUD; it opens the themed settings menu. Headless: pass `className` for placement/skin and `children` to replace the default gear glyph. Renders nothing when the game has no settings to show, so it never leaves a dead button behind.
370
+ - useHasSettings (function): function useHasSettings(): boolean — True when the game has any setting or game-action to show — gate your own settings entry on it.
371
+ - useSetting (function): function useSetting<T extends SettingValue>(id: string, fallback: T): readonly [T, (value: SettingValue) => void] — Read + write one persisted setting; re-renders when the value changes anywhere.
372
+ - useSettings (function): function useSettings(): SettingsController — The engine settings controller for the current game — render your own settings UI from `categories`, or open the built-in menu with `open()`. Null-safe stub when mounted outside the shell.
373
+ - useSettingsStore (function): function useSettingsStore(): SettingsStore — The shared settings store, or a standalone one when no provider is mounted (game code read outside the shell).
374
+
375
+ ### @jgengine/react/skillCheckPaint
376
+
377
+ - paintQteStepDom (function): function paintQteStepDom(elements: ReadonlyMap<string, HTMLElement>, steps: readonly QteStep[], elapsed: number, activeId: string | null, stepClassName?: string, activeClassName?: string, doneClassName?: string): void
378
+ - paintSkillCheckDom (function): function paintSkillCheckDom(root: HTMLElement, zone: HTMLElement, marker: HTMLElement, config: SkillCheckConfig, result: SkillCheckResult): void
379
+
380
+ ### @jgengine/react/social
381
+
382
+ - AddFriendButton (function): function AddFriendButton({ toUserId, className, children, onRequested, onRejected, }: { toUserId: string; className?: string; children?: ReactNode; onRequested?: (requestId: string) => void; onRejected?: (reason: string) => void; }): React.JSX.Element
383
+ - EmoteWheel (function): function EmoteWheel({ emotes, radius, open = true, className, emoteClassName, onPlayed, onRejected, renderEmote, }: { emotes: readonly string[]; radius?: number; open?: boolean; className?: string; emoteClassName?: string; onPlayed?: (emoteId: string) => void; onRejected?: (reason: string) => void; …
384
+ - FriendRequestsList (function): function FriendRequestsList({ className, rowClassName, acceptClassName, declineClassName, emptyState, renderRequest, }: { className?: string; rowClassName?: string; acceptClassName?: string; declineClassName?: string; emptyState?: ReactNode; renderRequest?: (request: FriendRequestEntry) => ReactNode…
385
+ - FriendRow (function): function FriendRow({ friend, className, dotClassName, children, }: { friend: FriendEntry; className?: string; dotClassName?: string; children?: ReactNode; }): React.JSX.Element
386
+ - FriendsList (function): function FriendsList({ className, rowClassName, dotClassName, emptyState, renderFriend, }: { className?: string; rowClassName?: string; dotClassName?: string; emptyState?: ReactNode; renderFriend?: (friend: FriendEntry) => ReactNode; }): React.JSX.Element
387
+ - InviteToWorldButton (function): function InviteToWorldButton({ toUserId, target, className, children, onInvited, onRejected, }: { toUserId: string; target: WorldInviteTarget; className?: string; children?: ReactNode; onInvited?: (inviteId: string) => void; onRejected?: (reason: string) => void; }): React.JSX.Element
388
+ - JoinByCode (function): function JoinByCode({ onJoin, className, inputClassName, buttonClassName, placeholder, children, }: { onJoin: (code: string) => void; className?: string; inputClassName?: string; buttonClassName?: string; placeholder?: string; children?: ReactNode; }): React.JSX.Element
389
+ - LeavePartyButton (function): function LeavePartyButton({ className, children, }: { className?: string; children?: ReactNode; }): React.JSX.Element | null
390
+ - PartyFrame (function): function PartyFrame({ className, rowClassName, dotClassName, emptyState, renderMember, }: { className?: string; rowClassName?: string; dotClassName?: string; emptyState?: ReactNode; renderMember?: (member: PartyMemberEntry) => ReactNode; }): React.JSX.Element
391
+ - PartyInviteToast (function): function PartyInviteToast({ className, acceptClassName, declineClassName, renderInvite, }: { className?: string; acceptClassName?: string; declineClassName?: string; renderInvite?: (invite: PartyInviteEntry) => ReactNode; }): React.JSX.Element | null
392
+ - PartyMemberRow (function): function PartyMemberRow({ member, className, dotClassName, children, }: { member: PartyMemberEntry; className?: string; dotClassName?: string; children?: ReactNode; }): React.JSX.Element
393
+ - PresenceDot (function): function PresenceDot({ userId, className }: { userId: string; className?: string }): React.JSX.Element
394
+ - QuickMatchButton (function): function QuickMatchButton({ listings, onJoin, onNoMatch, filter, className, children, }: { listings: readonly SessionListing[]; onJoin: (listing: SessionListing) => void; onNoMatch?: () => void; filter?: MatchFilter; className?: string; children?: ReactNode; }): React.JSX.Element
395
+ - WorldBrowser (function): function WorldBrowser({ listings, onJoin, className, rowClassName, joinClassName, emptyState, renderListing, }: { listings: readonly SessionListing[]; onJoin: (listing: SessionListing) => void; className?: string; rowClassName?: string; joinClassName?: string; emptyState?: ReactNode; renderListing?:…
396
+ - WorldInviteToast (function): function WorldInviteToast({ className, acceptClassName, declineClassName, onAccepted, renderInvite, }: { className?: string; acceptClassName?: string; declineClassName?: string; onAccepted: (target: WorldInviteTarget) => void; renderInvite?: (invite: WorldInvite) => ReactNode; }): React.JSX.Element …
397
+
398
+ ### @jgengine/react/voice
399
+
400
+ - MicToggle (function): function MicToggle({ voice, className, mutedLabel, unmutedLabel, }: { voice: VoiceState; className?: string; mutedLabel?: ReactNode; unmutedLabel?: ReactNode; }): React.JSX.Element
401
+ - PushToTalkButton (function): function PushToTalkButton({ voice, className, children, }: { voice: VoiceState; className?: string; children?: ReactNode; }): React.JSX.Element
402
+ - SpeakingIndicator (function): function SpeakingIndicator({ voice, userId, className, threshold = 0.01, children, }: { voice: VoiceState; userId: string; className?: string; threshold?: number; children?: ReactNode; }): React.JSX.Element
403
+ - UseVoiceOptions (interface): interface UseVoiceOptions
404
+ - VoiceRoster (function): function VoiceRoster({ voice, className, participantClassName, renderParticipant, }: { voice: VoiceState; className?: string; participantClassName?: string; renderParticipant?: (participant: VoiceParticipant, gain: number) => ReactNode; }): React.JSX.Element
405
+ - VoiceState (interface): interface VoiceState
406
+ - useVoice (function): function useVoice(options?: UseVoiceOptions): VoiceState — Mic capture + push-to-talk + channel roster over the VoiceTransport signaling seam. Transmission gates the captured tracks' `enabled` flag; the media plane that actually moves audio bytes (WebRTC/SFU) stays behind the transport, host-supplied. Call once per voice channel and hand the returned state to the voice components.
407
+
408
+ ## Guides
409
+
410
+ # JGengine
411
+
412
+ JGengine is a pure-TypeScript game-engine SDK for games built by AI coding agents. Its skills teach the agent how to use the SDK. When a user says “make X with JGengine” or “make X with jgengine.com,” treat that as sufficient intake. If the skills are not installed, run `npx jgengine skills`; then use this skill and build on the SDK. Do not make the user discover or name skills.
413
+
414
+ ## Intake
415
+
416
+ State the reading as a short numbered list that is easy to correct, then proceed unless the user changes it. Prefer concrete values and actions over prose:
417
+
418
+ 1. **POV:** first-person
419
+ 2. **World:** custom 3D wasteland with three settlements
420
+ 3. **Core loop:** get quests by talking to people → defeat enemies → return to redeem quests
421
+ 4. **Interaction:** collect ground items by walking over them; interact with people and doors at close range
422
+ 5. **Combat:** ranged weapons, damage, death, loot
423
+ 6. **Progression:** inventory, currency, quest rewards, upgrades
424
+ 7. **Players:** single-player, or name the multiplayer topology and synchronized systems
425
+ 8. **UI:** visible controls, objective tracker, health, inventory feedback
426
+ 9. **Art direction:** one aesthetic, palette, asset family, and UI voice
427
+ 10. **Done looks like:** one observable end-to-end play scenario
428
+
429
+ Keep this compact—roughly one line per item. It is a build map, not a large specification or an approval gate. Infer conventional details from the named game or genre. Ask only when two plausible readings would fundamentally change the game.
430
+
431
+ ## Route selectively
432
+
433
+ This skill is the foundation for every task (packages, project shape, defineGame, context, catalogs). After intake, also read only the domain skills the work needs:
434
+
435
+ | Need | Read |
436
+ | --- | --- |
437
+ | Terrain, scenes, camera, movement, physics, maps, sensors | `jgengine-world` |
438
+ | Seeded generation, terrain/environment generation, grids, buildings, simulation | `jgengine-procedural` |
439
+ | Damage, effects, weapons, targeting, projectiles, loot, death | `jgengine-combat` |
440
+ | Items, quests, dialogue, economy, crafting, objectives, turns, social systems | `jgengine-gameplay` |
441
+ | Networking adapters, authority, rooms/topology, persistence/backend seams | `jgengine-multiplayer` |
442
+ | React HUD, shell affordances, controls, feedback, accessibility | `jgengine-ui` |
443
+ | Models, sprites, textures, audio, catalogs, attribution | `jgengine-assets` |
444
+ | Proof and screenshots | `jgengine-verify` after implementation |
445
+
446
+ Do not read every domain by default. Build through documented engine surfaces; do not infer APIs from gallery games. Inspect engine source only when a documented surface appears wrong or a missing primitive blocks the work.
447
+
448
+ ## Build behavior
449
+
450
+ Scaffold with `npx jgengine create game-name --name "Game Name"` when needed. Build the requested game continuously from the intake, keeping systems end-to-end rather than leaving registered-but-unusable pieces. Use real assets and visible feedback early. Verify at completion with `jgengine-verify`.
451
+
452
+ Cartridge-shaped games (declarative config, engine-owned loop): see [reference-cartridge.md](https://github.com/Noisemaker111/jgengine/blob/main/.claude/skills/jgengine/reference-cartridge.md).
453
+
454
+ ---
455
+
456
+ The engine ships **verbs and primitives**; your game ships **nouns** (catalogs) and thin handlers. This skill is that foundation plus intake. Use domain skills only when needed; use `jgengine-verify` afterward. UI guidance lives in [`../jgengine-ui/reference.md`](https://github.com/Noisemaker111/jgengine/blob/main/.claude/skills/jgengine-ui/reference.md); assets live in `jgengine-assets`.
457
+
458
+ Load detailed references only for the selected domain: [`jgengine-combat`](https://github.com/Noisemaker111/jgengine/blob/main/.claude/skills/jgengine-combat/reference.md), [`jgengine-world`](https://github.com/Noisemaker111/jgengine/blob/main/.claude/skills/jgengine-world/reference.md), [`jgengine-multiplayer`](https://github.com/Noisemaker111/jgengine/blob/main/.claude/skills/jgengine-multiplayer/reference.md), and [`jgengine-ui`](https://github.com/Noisemaker111/jgengine/blob/main/.claude/skills/jgengine-ui/reference.md). Each domain skill explains when its reference is needed.
459
+
460
+ ## Packages
461
+
462
+ All published on npm, source at [github.com/Noisemaker111/jgengine](https://github.com/Noisemaker111/jgengine) (AGPL-3.0):
463
+
464
+ | Package | Role | May import |
465
+ |---------|------|------------|
466
+ | `@jgengine/core` | Everything below: defineGame, GameContext, scene, combat, game systems, movement, input, world features, runtime/transport contracts | nothing platform-specific — no React, Convex, three.js, browser |
467
+ | `@jgengine/react` | `GameProvider`, hooks, headless UI primitives | react + core |
468
+ | `@jgengine/shell` | `GamePlayerShell` — R3F canvas, camera rig library (orbit, first-person, top-down/iso, RTS, over-the-shoulder, lock-on, chase, cinematic + shake channel), input tracking, HUD mounting, `GameUiPreview`, demo game; you supply a `GameRegistry` | react + three + core |
469
+ | `@jgengine/ws` | Browser-safe `GameBackend` over a pluggable string-pipe transport (WebSocket/socket.io/WebRTC/loopback), protocol codec, HTTP reads, browser-safe authoritative host + router (`host`/`hostRouter`), and P2P (`peer`) | core |
470
+ | `@jgengine/node` | Node process bindings over `@jgengine/ws`'s host/router: `ws`-package server, socket.io server attach, file persistence (re-exports `createGameHost`/`memoryPersistence` unchanged) | node + ws + core |
471
+ | `@jgengine/sql` | `HostPersistence` on Postgres (structural pool, no hard `pg` dep) | core |
472
+ | `@jgengine/convex` | The Convex **adapter** behind the `GameBackend` seam | react + convex + core |
473
+
474
+ Import by deep path: `@jgengine/core/<domain>/<file>` (e.g. `@jgengine/core/runtime/gameContext`).
475
+
476
+ ## Hit a snag? File an issue
477
+
478
+ Any hiccup with JGengine — a doc that's wrong, a missing primitive, a rough edge, or a feature/improvement idea — file it fast at [github.com/Noisemaker111/jgengine/issues](https://github.com/Noisemaker111/jgengine/issues). A 30-second issue (what you were building, the glue it forced, the API you wanted) is worth more than a silent workaround — that's the fastest way gaps and doc errors get closed. Don't reverse-engineer around a broken doc in silence; report it.
479
+
480
+ ## Upgrading? Read the changelog
481
+
482
+ All eight packages version in lockstep. When you bump (e.g. `0.6` → `0.7`) to pick up new capabilities, read [`CHANGELOG.md`](https://github.com/Noisemaker111/jgengine/blob/main/CHANGELOG.md) — each release leads with a **Migrate** block listing the concrete steps to move a game onto the new APIs. It ships inside every package too (`node_modules/@jgengine/core/CHANGELOG.md`), and as typed values: `import { VERSION, CHANGELOG } from "@jgengine/core/meta/changelog"` to diff your installed version against the latest programmatically.
483
+
484
+ ## Concept → Type Reference
485
+
486
+ Exact import paths and export names — **do not invent paths**; every row below resolves to a real file under `packages/core/src`. Import the deep path form `@jgengine/core/<path>`.
487
+
488
+ | Concept | Import path (`@jgengine/core/…`) | Export(s) |
489
+ |---------|----------------------------------|-----------|
490
+ | Game boot | `game/defineGame` | `defineGame`, `GameDefinition`, `GameLoop`, `InventoryDeclaration`, `PhysicsConfig`, `GameServerConfig`, `TimeConfig` |
491
+ | Simulation clock | `time/simClock` | `createSimClock`, `SimClock`, `TimeConfig`, `ClockSnapshot`, `CalendarTime` |
492
+ | Runner contract | `game/playableGame` | `PlayableGame`, `GameCameraConfig`, `CameraRigKind`, `CameraProjection`, `SideScrollCameraConfig`, `TopDownCameraConfig`, `RtsCameraConfig`, `ShoulderCameraConfig`, `LockOnCameraConfig`, `ChaseCameraConfig`, `ObserverCameraConfig`, `CameraShakeConfig`, `CinematicCameraConfig`, `CameraKeyframe`, `EntitySpriteConfig` |
493
+ | Runtime ctx | `runtime/gameContext` | `createGameContext`, `GameContext`, `GameContextContent`, `GameContextItemEntry`, `GameContextEntityEntry`, `GameContextObjectEntry`, `CatalogEntityRole` |
494
+ | Behaviour lifecycle | `behaviour/behaviour` | `Behaviour` (`onAwake`→`onEnable`→`onStart`→`onUpdate(dt)`→`onDisable`→`onDestroy`), `BehaviourModule`, `createBehaviourWorld`, `BehaviourWorld`, `JGEngineRegister`, `RegisterField`, `BehaviourModules` — Unity-style lifecycle over an id-keyed node tree (`setActive` cascade, lazy update dispatch); key nodes by entity instance ids. Games augment `JGEngineRegister` via `declare module "@jgengine/core/behaviour/behaviour"` for typed `world.modules`. Three.js binding: `Object3DBehaviour`, `attachObject3D`, `useBehaviourWorld` from `@jgengine/shell/behaviour` |
495
+ | Reactive keyed store | `store/observableKeyedStore` | `createObservableKeyedStore`, `ObservableKeyedStore` — backs `ctx.game.store` |
496
+ | Scene instance role | `scene/entityStore` | `EntityRole`, `SceneEntity`, `SpawnOptions`, `EntityPose` |
497
+ | Object spatial queries | `scene/objectQuery` | `raycastObjects`, `raycastObjectsAll`, `ObjectRaycastInput`, `ObjectRaycastHit` — backs `ctx.scene.object.raycast`/`raycastAll` |
498
+ | Runtime paint layer | `scene/paintLayer` | `createPaintLayer`, `PaintLayer`, `PaintStroke` — backs `ctx.scene.entity.paint` |
499
+ | Possession | `scene/possession` | `createPossession`, `Possession`, `PossessionDeps`, `PossessionSwappedEvent` |
500
+ | Form / shapeshift | `scene/form` | `createForms`, `Forms`, `FormDef`, `FormsDeps`, `FormChangedEvent` |
501
+ | Multiplayer adapters | `runtime/adapter` | `offline`, `ws`, `convex`, `socketIo`, `p2p`, `lan`, `fly`, `servers`, `MultiplayerTopology`, `ServersPoolConfig` |
502
+ | Loot | `game/lootTable` | `lootTable`, `LootTableDef`, `LootEntry`, `Drop` |
503
+ | Dropped-item entity | `game/worldItem` | `WORLD_ITEM_ENTITY_NAME`, `WorldItemRecord`, `WorldItemSpawnInput`, `createWorldItemStore`, `resolveDeathDrops`, `scatterOffset`, `scatterPosition`, `selectNearestWorldItem`, `resolveWorldItemPresentation`, `RarityStyle`, `WorldItemPresentation`, `DEFAULT_RARITY`, `DEFAULT_PICKUP_RADIUS`, `DEFAULT_SCATTER` |
504
+ | Loot filter | `game/lootFilter` | `lootFilter`, `evaluateLootFilter`, `LootFilterRule`, `LootFilterCondition`, `LootFilterItem`, `LootFilterOverride` |
505
+ | Loadout | `game/loadout` | `LoadoutDef`, `LoadoutItemEntry`, `Loadouts` |
506
+ | Cosmetic loadout | `game/cosmetics` | `createCosmetics`, `Cosmetics`, `CosmeticLoadoutDef` |
507
+ | Quest | `game/quest` | `QuestDef`, `QuestRewards`, `QuestObjective`, `QuestJournal` |
508
+ | World features | `world/features` | `WorldFeature`, `biomes`, `voxel`, `plots`, `tilemap`, `flat`, `environment`, `terrain`, `rain`, `snow`, `grass`, `ocean`, `building` |
509
+ | Voxel field | `world/voxelField` | `createVoxelField`, `VoxelField`, `VoxelCell`, `VoxelHit`, `VoxelBounds`, `VoxelFieldSummary`, `VoxelFace`, `VOXEL_FACES`, `VOXEL_FACE_NORMALS` — a chunked block lattice, distinct from the `voxel()` `WorldFeature` descriptor |
510
+ | Terrain field | `world/terrain` | `TerrainField`, `noiseField`, `resolveTerrainField`, `rollingField`, `fractalNoise`, `valueNoise`, `withNormal`, `arenaField`, `flatField`, `resolveGroundStep`, `snapToGround`, `snapEntityToGround`, `resolveTerrainPalette`, `TERRAIN_MATERIAL_PALETTES` |
511
+ | Seeded RNG | `random/rng` | `seededRng`, `seededStreams` |
512
+ | Seed share link | `random/seedLink` | `withSeedParam`, `seedFromUrl`, `seedFromSearch`, `dailySeed`, `DEFAULT_SEED_PARAM` — encode/decode a world seed to/from a shareable URL query param; `dailySeed` is the UTC daily-run seed |
513
+ | Name generator | `random/nameGen` | `createNameGenerator`, `pickFrom`, `fillTemplate`, `NameGenerator`, `NameGeneratorOptions`, `SyllableBank` |
514
+ | Regions | `world/regions` | `createRegionField`, `isRegionField`, `RegionDef`, `RegionField`, `RegionSample` |
515
+ | Wind field | `world/wind` | `windField`, `WindField`, `WindFieldConfig`, `WindVector` |
516
+ | Water surface | `world/water` | `waterSurface`, `waterSurfaceFromDescriptor`, `synthesizeWaves`, `WaterSurface`, `GerstnerWave` |
517
+ | Scatter | `world/scatter` | `scatter`, `scatterAabb`, `ScatterConfig`, `ScatterPoint` |
518
+ | Content scatter | `world/scatterItems` | `scatterItems`, `pickWeighted`, `ScatterLayer`, `ScatterInstance` |
519
+ | Building generator | `world/buildings` | `generateBuilding`, `generateBuildingDistrict`, `createBuildingGrid`, `GeneratedBuilding` |
520
+ | Building index | `world/buildingIndex` | `buildingIndex`, `BuildingIndex`, `BuildingHit` |
521
+ | Scene summary | `world/environmentSummary` | `summarizeEnvironment`, `resolveStructureBuildings`, `EnvironmentSummary` |
522
+ | Map markers | `world/markers` | `createMarkerSet`, `MarkerSet`, `MapMarker`, `MarkerInput`, `MarkerKindStyle`, `DEFAULT_MARKER_KINDS`, `markerKindStyle` |
523
+ | Fog of war | `world/fog` | `createFogField`, `FogField`, `FogConfig`, `FogBounds`, `FogCells` |
524
+ | Minimap math | `world/minimap` | `projectToMinimap`, `clampToMinimapEdge`, `compassBearing`, `headingToBearing`, `bearingToCardinal`, `relativeBearing`, `MinimapView` |
525
+ | Ping | `game/ping` | `createPingSystem`, `classifyPing`, `PingSystem`, `PingPayload`, `PingCategory`, `PingCategoryDef`, `DEFAULT_PING_CATEGORIES`, `PING_FEED_ACTION` |
526
+ | Proximity prompt | `interaction/proximityPrompt` | `proximityPrompt`, `ProximityPrompt`, `ProximityPromptDisplay`, `keybind`, `gauge`, `label`, `command` |
527
+ | Skill-check minigame | `interaction/skillCheck` | `evaluateSkillCheck`, `skillCheckMarkerPosition`, `skillCheckZoneAt`, `SkillCheckConfig`, `SkillCheckZone`, `SkillCheckResult` |
528
+ | QTE sequencer | `interaction/qte` | `evaluateQteSequence`, `pendingQteStep`, `qteProgress`, `QteStep`, `QteInputEvent`, `QteOutcome` |
529
+ | Item use | `item/use` | `createItemUse`, `ItemUseHandler`, `ItemUseInput`, `ItemUseResult`, `ItemUseRejection` |
530
+ | Durability | `item/durability` | `createDurability`, `wear`, `repairQuote`, `isDisabled`, `createDurabilityTracker`, `DurabilitySpec`, `DurabilityState`, `RepairSpec`, `RepairQuote` |
531
+ | Affix roller | `item/affix` | `createAffixRoller`, `seededRng`, `AffixRoller`, `RollerConfig`, `AffixPool`, `AffixDef`, `RarityTier`, `ItemBaseDef`, `RolledItem`, `RolledAffix` |
532
+ | Modular item | `item/modularItem` | `createModularItem`, `install`, `computeEffectiveStats`, `missingRequiredSlots`, `ModularItemDef`, `MountSlotDef`, `PartDef`, `InstalledPart` |
533
+ | Storage tier | `inventory/storageTier` | `partitionOnDeath`, `createDeliveryQueue`, `insureLost`, `resolveConsolation`, `tierOf`, `StorageTier`, `ContainerSnapshot`, `DeathPartition`, `DeliveryQueue`, `InsurancePolicy`, `ConsolationPolicy` |
534
+ | Contested channel | `session/contestedChannel` | `createContestedChannel`, `ContestedChannel`, `ContestedChannelConfig`, `ContestedEvent`, `ContestedPhase`, `ContestedSnapshot` |
535
+ | Round state | `session/roundState` | `createRoundState`, `lossBonusFor`, `RoundState`, `RoundConfig`, `RoundPhase`, `RoundTeam`, `RoundEvent`, `RoundEconomy`, `RoundSnapshot`, `LossBonusRule` |
536
+ | Shrinking ring | `session/ring` | `createRing`, `ringSampleAt`, `Ring`, `RingConfig`, `RingPhase`, `RingSample`, `RingHit`, `RingPoint` |
537
+ | Extraction session | `session/extraction` | `createRaidSession`, `RaidSession`, `RaidSessionConfig`, `ExtractPoint`, `ExtractionResult`, `DeathResult`, `RaidStatus` |
538
+ | Role assignment | `session/roles` | `assignRoles`, `RoleSpec` |
539
+ | Downed / revive | `combat/downed` | `createDownedState`, `DownedState`, `DownedConfig`, `DownedPhase`, `DownedEntry`, `DownedEvent` |
540
+ | Persistence scopes | `runtime/persistenceScope` | `partitionScopes`, `resetRun`, `mergeScopes`, `clearRunFields`, `applyRunReset`, `planScenarioReset`, `ScopeSchema`, `ScenarioReset`, `PersistenceScope` |
541
+ | Inventory | `inventory/inventoryModel` | `InventoryLayout`, `InventorySet`, `ItemTraits` |
542
+ | Progression | `game/progression` | `curve`, `evalCurve`, `leveling`, `Curve`, `LevelingTrack`, `LevelProgress` |
543
+ | Talent tree | `game/talents` | `createTalentTree`, `TalentTree`, `TalentTreeConfig`, `TalentNodeDef`, `TalentRequirement`, `TalentAllocateResult`, `ResolvedTalents`, `TalentSnapshot` — point spends gated by prereqs + points-in-branch, resolved once into a cached flat `StatModifierSet` + ability grants |
544
+ | Inventory slots | `inventory/slotModel` | `createSlots`, `placeAt`, `removeAt`, `moveSlot`, `firstEmpty`, `compactSlots`, `Slot`, `SlotGrid` |
545
+ | Shaped inventory | `inventory/shapedGrid` | `createShapedGrid`, `placeShaped`, `moveShaped`, `removeShaped`, `canPlace`, `rotateFootprint`, `occupiedCells`, `gridAdjacencyQuery`, `cellFromPoint`, `ShapedGrid`, `Footprint`, `Placement`, `Rotation` |
546
+ | Card piles | `cards/cardPile` | `createCardPile`, `createCardPileState`, `draw`, `moveCards`, `shuffleZone`, `pileRng`, `CardPile`, `CardPileState`, `CardPileConfig` |
547
+ | Modifier pipeline | `cards/modifierPipeline` | `createModifierPipeline`, `runPipeline`, `Modifier`, `TraceStep`, `PipelineResult` |
548
+ | Lane board | `board/laneBoard` | `createLaneBoard`, `laneAggregate`, `laneOutcome`, `boardTotals`, `lanesWon`, `LaneBoard`, `LaneRule`, `LaneBoardConfig` |
549
+ | Timeline board | `board/timelineBoard` | `createTimelineBoard`, `tickTimeline`, `TimelineBoard`, `TimelineSlot`, `TimelineFire` |
550
+ | World geometry | `world/geometry` | `footprintAabb`, `aabbOverlap`, `snapToGrid`, `resolveMove`, `Aabb`, `Footprint` |
551
+ | Placement | `world/placement` | `validatePlacement`, `footprintObstacle`, `PlacementRules`, `PlacementResult` |
552
+ | Placement ghost | `world/placementController` | `createPlacementController`, `PlacementController`, `PlacementPreview`, `PlacementCommit`, `SnapMode`, `quarterTurnsToRotationY` |
553
+ | Connector sockets | `world/connectors` | `snapToNearest`, `socketsCompatible`, `worldSockets`, `socketWorldPosition`, `ConnectorSocket`, `ConnectorPieceDef`, `PlacedPiece`, `SnapResult` |
554
+ | Structural support | `world/support` | `solveSupport`, `toDebrisBodies`, `SupportPiece`, `SupportLink`, `SupportResult` |
555
+ | Wall/roof authoring | `world/walls` | `createWallDrawTool`, `footprintFromWalls`, `autoRoof`, `wallSegments`, `createSurfacePaint`, `WallDrawTool`, `RoofPlan`, `EnclosedFootprint` |
556
+ | Placed structures | `world/placedStructureStore` | `createPlacedStructureStore`, `PlacedStructure`, `PlacedStructureStore`, `PlacedStructureSnapshot` |
557
+ | Terraform | `world/terraform` | `createEditableTerrain`, `createTerraformBrush`, `brushWeight`, `EditableTerrain`, `TerraformBrush`, `TerraformEdit`, `TerraformMode` |
558
+ | Build permissions | `world/buildPermissions` | `createPlotPermissions`, `createContributionPool`, `PlotPermissions`, `ContributionPool`, `BuildRole`, `ContributionGoal` |
559
+ | Interiors | `world/interiors` | `createInteriors`, `Interior`, `Exterior`, `SpaceRef` |
560
+ | Game clock | `time/gameClock` | `getScaledElapsedMs`, `computeGameDay`, `SECONDS_PER_GAME_DAY` |
561
+ | Idle / offline catch-up | `time/idleProgress` | `idleWindow`, `linearCatchUp`, `exponentialCatchUp`, `steppedCatchUp`, `IdleWindow`, `IdleWindowConfig`, `SteppedCatchUpResult` — elapsed-real-time production/growth/decay for a game reopened after being closed |
562
+ | Scene behaviors | `scene/behaviors` | `wander`, `patrol`, `promptable`, `talkable`, `player` |
563
+ | Capture check | `scene/captureCheck` | `captureChance`, `rollCapture`, `CaptureCheckInput` |
564
+ | Owned roster | `scene/roster` | `createRoster`, `Roster`, `RosterEntry`, `RosterCaptureOptions` |
565
+ | Economy wallet | `economy/wallet` | `createEmptyWallet`, `balance`, `grant`, `charge`, `canAfford`, `chargeAll` |
566
+ | Tech tree | `economy/techTree` | `createTechTree`, `TechTree`, `TechNodeDef`, `canUnlockTech`, `availableTech`, `unlockedRecipes`, `grantTech`, `techPrerequisitesMet` |
567
+ | Recipe graph | `crafting/recipe` | `createRecipeGraph`, `RecipeGraph`, `RecipeDef`, `RecipeItem`, `canCraft`, `craft`, `missingInputs`, `stationSatisfied`, `craftSeconds` |
568
+ | Production building | `crafting/production` | `productionBuilding`, `ProductionBuildingDef`, `createProductionState`, `tickProduction`, `feedProduction`, `drainOutput`, `advanceTransport`, `resolvePowerGrid` |
569
+ | Crop tile / farming | `crafting/crop` | `createCropField`, `CropField`, `CropDef`, `CropTileState`, `tillTile`, `plantCrop`, `waterTile`, `advanceCropDay`, `harvestCrop`, `applyToolToTiles`, `squarePattern`, `diamondPattern`, `createDayTicker` |
570
+ | Skill-check roll | `stats/rollCheck` | `rollCheck`, `CheckInput`, `CheckResult`, `CheckAdvantage` |
571
+ | Input bindings (full) | `input/actionBindings` | `hotbarSlotBindings`, `actionLabel`, `bindingLabel`, `resolveActionCommand`, `bindingMatches`, `createActionStateTracker` |
572
+ | Touch controls | `input/touchScheme` | `deriveTouchScheme`, `touchCode`, `touchActionLabel`, `withTouchCodes`, `TouchControlsConfig`, `TouchGestureBindings`, `TouchDragBinding`, `TouchButtonSpec`, `TouchScheme`, `TouchJoystick`, `TouchButton` |
573
+ | Pointer hit | `input/pointer` | `PointerHit`, `PointerButton`, `aimToPoint`, `moveTargetFromHit`, `groundOf`, `PointerVec3` |
574
+ | Navmesh + A* | `nav/navGrid` | `createNavGrid`, `findPath`, `smoothPath`, `NavGrid`, `NavGridConfig`, `NavPoint`, `FindPathOptions` |
575
+ | Path follow | `nav/pathFollow` | `createPathFollow`, `advancePathFollow`, `pathFromNav`, `PathFollowConfig`, `PathFollowState`, `Waypoint` |
576
+ | Nav-grid movement constraint | `nav/navConstrain` | `constrainToNavGrid`, `NavConstrainProposed`, `NavConstrainEntity`, `NavConstrainOptions` — a standalone walkable-pass-through + wall-slide helper; adapt its `(proposed, entity)` shape to `PlayerMovementConfig.beforeCommit`'s `(frame) => [x,y,z]` with a small closure |
577
+ | Selection set | `scene/selection` | `createSelectionSet`, `SelectionSet`, `screenRect`, `selectWithinRect`, `rectContainsPoint`, `isMarquee`, `ScreenRect` |
578
+ | Context menu | `interaction/contextMenu` | `contextVerb`, `buildContextMenu`, `contextVerbInput`, `ContextVerb`, `ContextMenu` |
579
+ | Shared / group wallet | `economy/sharedWallet` | `createWalletBook`, `WalletBook`, `WalletScope`, `userScope`, `groupScope`, `balanceIn`, `grantTo`, `chargeFrom`, `contributionOf`, `contributorsOf` |
580
+ | Analog axis input | `input/axisInput` | `AxisInput`, `AxisChannel`, `AxisBindingMap`, `DRIVE_AXIS_BINDINGS`, `clampAxis`, `rampToward`, `NEUTRAL_AXIS` |
581
+ | Raw control polling | `runtime/inputSnapshot` | `createInputSnapshot`, `InputSnapshot` — backs `ctx.input` |
582
+ | Physics world | `physics/physicsWorld` | `PhysicsWorld`, `PhysicsWorldConfig`, `PhysicsBounds`, `PhysicsStats`, `AddBodyOptions` (`{ shape: "box", halfExtents }` \| `{ shape: "sphere", radius }`), `JointOptions`, `JointKind`, `CollisionEvent` |
583
+ | Ballistic collision sweep | `physics/ballisticSweep` | `createBallisticSweep`, `BallisticSweep`, `BallisticSweepHit`, `BallisticSweepOptions` |
584
+ | Tweening / easing | `anim/easing` | `Easing`, `lerp`, `clamp01`, `smoothstep`, `easeInQuad`, `easeOutQuad`, `easeInOutQuad`, `easeInCubic`, `easeOutCubic`, `easeInOutCubic`, `easeOutBack`, `easeOutElastic`, `tween`, `timedProgress` |
585
+ | Async data source | `data/dataSource` | `createDataSource`, `DataSource`, `DataSourceState`, `DataSourceStatus`, `DataSourceOptions`, `DataSourceClock`, `RefreshOptions` |
586
+ | JSON fetch | `data/fetchJson` | `fetchJson`, `FetchJsonOptions`, `FetchImpl`, `HttpStatusError`, `JsonParseError` |
587
+ | JSON data source | `data/jsonDataSource` | `createJsonDataSource`, `JsonDataSourceOptions` |
588
+ | Dev proxy routing | `data/devProxy` | `proxiedUrl`, `parseDevProxyTable`, `DevProxyTable`, `ProxiedUrlOptions`, `DEFAULT_DEV_PROXY_PREFIX` |
589
+ | Grid-cell world rendering | `world/gridInstances` | `resolveGridInstances`, `GridInstanceTransform` |
590
+ | Swarm LOD scheduler | `world/lod` | `createLodScheduler`, `LodScheduler`, `LodSchedulerConfig`, `LodBand` — distance→band index for render detail, `step(id, distance, dt)` throttles per-entity updates by band interval (staggered, accumulates skipped time); pairs with `@jgengine/shell/world/SpriteBatch` for 1000+ entity swarms |
591
+ | Turn loop | `turn/turnLoop` | `createTurnLoop`, `TurnLoop`, `TurnLoopConfig`, `TurnState`, `PoolConfig`, `PoolState`, `TurnLoopSnapshot` |
592
+ | Declared-action intent board | `turn/intent` | `createIntentBoard`, `IntentBoard`, `DeclaredIntent` — `declare(participantId, intent)`, `peek`, `all`, `consume`, `clear` |
593
+ | Commit modes | `turn/commit` | `createCommitController`, `CommitController`, `CommitMode`, `CommitOutcome`, `SubmittedAction` |
594
+ | Intent board | `turn/intent` | `createIntentBoard`, `IntentBoard`, `DeclaredIntent` |
595
+ | Tactical grid | `tactics/tacticalGrid` | `createTacticalGrid`, `TacticalGrid`, `TacticalGridConfig`, `Tile`, `ReachableTile`, `PushResult`, `PushCollision` |
596
+ | Predictive query | `tactics/predictiveQuery` | `predictAreaEffect`, `predictArcEffect`, `predictTiles`, `PredictiveDeps`, `PredictedTarget` |
597
+ | Sim snapshot | `tactics/snapshot` | `createSnapshotStore`, `SnapshotStore`, `SnapshotSlice`, `Snapshot`, `deepClone` |
598
+ | Surfaces | `tactics/surface` | `createSurfaceLayer`, `SurfaceLayer`, `SurfaceLayerConfig`, `SurfaceKindDef`, `SurfaceReaction`, `SurfaceEvent` |
599
+ | Area targeting | `combat/effects` | `resolveAreaTargets`, `AreaTarget`, `AreaTargetInput` (shared AoE targeting behind `effect` + the predictive query) |
600
+ | Environment field | `world/envField` | `createEnvironmentField`, `EnvironmentField`, `EnvironmentSample`, `EnvironmentFieldConfig`, `OccluderRect`, `HeatSource` |
601
+ | Weather + fire | `world/weather` | `resolveWeather`, `WeatherState`, `WeatherModifier`, `WeatherModifierTable`, `ResolvedWeather`, `createFireGrid`, `FireGrid`, `FireCell`, `FireGridConfig` |
602
+ | Realm composition | `world/realm` | `composeRealm`, `RealmCard`, `RealmBase`, `ComposedRealm`, `RealmEnvironmentParams`, `SpawnTableOverride` |
603
+ | Decay meters | `survival/decayMeter` | `createDecayMeterSet`, `DecayMeterSet`, `DecayMeterConfig`, `MeterThreshold`, `DecayMeterState` |
604
+ | Status moodles | `survival/moodle` | `createMoodleStack`, `stackMoodles`, `MoodleStack`, `Moodle`, `MoodleSeverity`, `TimedMoodleInput` |
605
+ | Multi-region health | `survival/regionHealth` | `createMultiRegionHealth`, `MultiRegionHealth`, `HealthRegionConfig`, `AilmentConfig`, `RegionHealthState`, `AilmentInstance` |
606
+ | Audio contract | `audio/audioFalloff` | `computeFalloffGain`, `resolveEmitterGain`, `distance3`, `AudioFalloffConfig`, `FalloffCurve`, `SoundDef`, `AudioBusDef`, `AudioBusId` |
607
+ | Beat clock | `time/beatClock` | `createBeatClock`, `createBeatInputBuffer`, `nextBeatTime`, `BeatClock`, `BeatClockConfig`, `BeatSnapshot`, `BeatInputBuffer`, `BufferedAction` |
608
+ | Spawn director | `ai/spawnDirector` | `createSpawnDirectorState`, `advanceSpawnDirector`, `advanceWave`, `raiseAlert`, `pickSpawnPoint`, `SpawnDirectorConfig`, `WaveManifest`, `SpawnEntry`, `SpawnRequest`, `DirectorContext` |
609
+ | Threat table | `ai/threat` | `createThreatTable`, `ThreatTable`, `ThreatTableConfig`, `ThreatEntry`, `HighestThreatOptions` |
610
+ | Group-assist aggro | `ai/groupAssist` | `createAssistNetwork`, `AssistNetwork`, `AssistNetworkConfig`, `AssistMember` — propagates one member's threat gains to same-group members (optional radius + `distanceBetween` gating) so a single pull rallies the group |
611
+ | Job board | `ai/jobBoard` | `createJobBoard`, `JobBoard`, `JobDef`, `Job`, `JobPhase`, `WorkerState`, `JobReport`, `JobTickContext` |
612
+ | Crowd flow | `ai/crowd` | `computeFlowField`, `createCrowdField`, `selectPoi`, `FlowField`, `FlowFieldOptions`, `CrowdField`, `Poi`, `SelectPoiOptions` |
613
+ | Factions & reputation | `faction/factions`, `faction/reputation` | `createFactionGraph`, `createFactionRoster`, `FactionRelation`, `FactionDef`, `FactionGraph`, `FactionRoster`, `createReputationLedger`, `DEFAULT_REPUTATION_TIERS`, `tierForStanding`, `effectiveRelation`, `ReputationTier`, `ReputationLedger` |
614
+ | Physics actors | `physics/ragdoll`, `physics/carryable`, `physics/forceVolume`, `physics/spatialGrid` | `createRagdoll`, `Ragdoll`, `Carryable`, `carrySpeedMultiplier`, `ForceVolume`, `PlatformCarry`, `SpatialGrid` |
615
+ | Traversal (grapple/glide) | `physics/traversal` | `Grapple`, `GrappleConfig`, `Glide`, `GlideConfig` |
616
+ | Structural destruction | `physics/structure` | `StructureGraph`, `StructureNodeSpec`, `StructureEdgeSpec`, `StructureMaterial`, `StructureMaterialTable`, `CollapseEvent`, `DebrisConfig` |
617
+ | Destructible terrain | `world/carve` | `VoxelVolume`, `VoxelMaterial`, `VoxelMaterialTable`, `CarvableField`, `carvableTerrain`, `CarveOp`, `DepositOp`, `CraterOp`, `MoundOp`, `EMPTY_VOXEL` |
618
+ | Vehicle body | `physics/vehicleBody` | `createVehicleBody`, `VehicleBody`, `VehicleBodyConfig`, `WheelSpec`, `GripCurve`, `sampleGripCurve`, `DEFAULT_GRIP_CURVE` |
619
+ | Buoyant boat | `physics/buoyancy` | `createBuoyantBody`, `BuoyantBody`, `BuoyantBodyConfig` |
620
+ | Crash damage | `physics/damageZones` | `createDamageModel`, `DamageModel`, `DamageZoneDef`, `DamageTransition` |
621
+ | Mounts / rideables | `scene/mount` | `createMountController`, `MountController`, `MountKit`, `MountSeat`, `RideableConfig` |
622
+ | Shared-vehicle stations | `scene/stationClaim` | `createStationClaim`, `StationClaim`, `Station`, `SharedVehicleConfig`, `ClaimResult` |
623
+ | Lag compensation | `multiplayer/lagCompensation` | `createPositionHistory`, `PositionHistory`, `rewindTimestamp`, `resolveHitscan`, `raySphereDistance`, `HitscanRay`, `HitscanTarget` |
624
+ | Simultaneous commit | `multiplayer/simultaneousCommit` | `createCommitRound`, `CommitRound`, `SealedCommit`, `resolveCommits` |
625
+ | Combat-snapshot replay | `multiplayer/combatSnapshot` | `serializeBoard`, `cloneSnapshot`, `replayCombat`, `BoardSnapshot`, `SnapshotUnit`, `CombatRules`, `ReplayResult` |
626
+ | Session matchmaking | `multiplayer/matchmaking` | `browseSessions`, `findByJoinCode`, `quickMatch`, `matchesFilter`, `normalizeJoinCode`, `generateJoinCode`, `SessionListing`, `MatchFilter` |
627
+ | Auth identity | `multiplayer/identity` | `AuthSession`, `PlayerIdentity`, `sessionPlayer`, `resolveGuestSession` |
628
+ | Text chat | `game/chat`, `multiplayer/chatContract` | `createChat`, `Chat`, `ChatMessage`, `ChatChannelDef`, `whisperChannelId`, `createChatRateLimiter`, `ChatTransport`, `ChatSync`, `createLocalChatTransport` |
629
+ | Chat filter | `game/chatFilter` | `createChatFilter`, `normalizeChatText`, `ChatFilter`, `ChatFilterConfig`, `ChatFilterResult` — mask/reject blocked words (leet-normalized token match); wire via `ChatDeps.filter` (word lists are game data, the engine ships the mechanism) |
630
+ | Voice seam | `multiplayer/voiceContract` | `VoiceTransport`, `VoiceParticipant`, `VoiceRoute`, `createLocalVoiceTransport`, `createPushToTalk`, `PushToTalkMode` |
631
+ | Race state | `game/race` | `raceTrack`, `RaceTrack`, `createRaceState`, `RaceState`, `RaceEvent`, `RaceWinCondition`, `firstPastPost`, `topK`, `lastStanding`, `everyoneFinishes` |
632
+ | Reveal query | `sensor/revealQuery` | `createRevealQuery`, `RevealQuery`, `RevealQueryOptions`, `RevealHit` |
633
+ | Hidden-state probe | `sensor/hiddenStateProbe` | `probeHiddenState`, `probeHiddenStateAll`, `HiddenStateSource`, `HiddenStateValue`, `SensorProbeOptions`, `SensorReading` |
634
+ | View-frustum sensor | `sensor/frustumSensor` | `createFrustumSensor`, `projectToView`, `framingScore`, `FrustumCamera`, `FrustumTarget`, `FrustumProjection`, `FrustumSample`, `FrustumSensor`, `FramingConfig` |
635
+ | Recording buffer | `sensor/recordingBuffer` | `createRecordingBuffer`, `RecordingBuffer`, `RecordingFrame`, `RecordingBufferOptions` |
636
+ | Concealment scoring | `sensor/concealment` | `colorDistance`, `concealmentScore`, `createConcealmentSensor`, `ColorHex`, `ConcealmentTarget`, `ConcealmentSample`, `ConcealmentSensor` |
637
+ | Freeze violation monitor | `sensor/freezeMonitor` | `createFreezeMonitor`, `FreezeMonitor`, `FreezeSubject`, `FreezeViolation` |
638
+ | Animation SM | `combat/animationState` | `createAnimationState`, `AnimationState`, `AnimationClip`, `FramePhase`, `FrameRange`, `phasesAtFrame`, `activeRangeAtFrame`, `frameAtMs` |
639
+ | Accumulator meter | `stats/accumulatorMeter` | `createAccumulatorMeter`, `AccumulatorMeter`, `AccumulatorMeterConfig`, `MeterTier`, `MeterAddResult`, `tierAt` |
640
+ | Stagger / buildup | `combat/breakMeters` | `createStaggerMeter`, `createBuildupMeter`, `StaggerMeter`, `BuildupMeter`, `BuildupProc` |
641
+ | Attack tags | `combat/attackTags` | `attackMeta`, `AttackTag`, `AttackMeta`, `hasTag`, `isBlockable`, `isParryable`, `isDodgeable`, `counters` |
642
+ | Defensive window | `combat/defensiveWindow` | `createDefensiveWindow`, `resolveDefense`, `DefensiveWindowConfig`, `DefenseKind`, `DefenseOutcome`, `windowActiveAt`, `iframeActiveAt` |
643
+ | Combo string | `combat/comboString` | `createComboRunner`, `advanceCombo`, `ComboString`, `ComboStep`, `AdvanceComboResult` |
644
+ | Hit reaction | `combat/hitReaction` | `resolveHitReaction`, `HitReaction`, `HitReactionConfig`, `CameraShake`, `applyImpulse` |
645
+ | Telegraph | `combat/telegraph` | `pointInTelegraph`, `telegraphProgress`, `telegraphFired`, `telegraphTurnProgress`, `telegraphFiredAtTurn`, `telegraphTurnsRemaining`, `TelegraphShape`, `TelegraphConfig` |
646
+ | Dash / dodge | `movement/dash` | `createDashState`, `DashState`, `DashConfig`, `DashBurst`, `iframeActive`, `dashOffset` |
647
+ | Ability kit | `combat/abilityKit` | `createAbilityKit`, `AbilityKit`, `AbilitySlotConfig`, `AbilitySlotSnapshot`, `AbilitySlotState`, `AbilityCastType`, `AbilityCastResult`, `AbilitySlotRetune` |
648
+ | Resource pool | `combat/resourcePool` | `createResourcePool`, `ResourcePool`, `ResourcePoolConfig` — current/max with per-second regen/decay and spend/gain; `pool.current()` is the ability kit's `resourceAvailable` |
649
+ | Combo points | `combat/comboPoints` | `createComboPoints`, `ComboPoints`, `ComboPointsConfig` — discrete points accrued on action, expiring after a timeout from the last gain, spent in bulk |
650
+ | Event meter | `stats/eventMeter` | `createEventMeter`, `EventMeter`, `EventMeterConfig`, `EventMeterFeedResult` |
651
+ | Auto-target policy | `scene/autoTarget` | `selectAutoTarget`, `createAutoTargeter`, `AutoTargetPolicy`, `AutoTargeter`, `AutoTargetDeps` |
652
+ | Resistance matrix | `combat/resistance` | `resolveResistance`, `resistanceScale`, `ResistanceMatrix`, `ResistVerdict`, `ResistanceResult` |
653
+ | Run draft | `game/runDraft` | `createRunDraft`, `createRunModifierStack`, `RunDraft`, `RunModifierStack`, `RunModifierOffer` |
654
+ | Uniform-cell grid | `puzzle/cellGrid` | `CellGrid`, `CellRun`, `createCellGrid`, `cellAt`, `inGridBounds`, `withCell`, `withCells`, `fullRows`, `clearRows`, `collapseColumns`, `findRuns` |
655
+ | Falling piece | `puzzle/fallingPiece` | `FallingPiece`, `ShapeTable`, `LockDelayState`, `pieceCells`, `pieceCollides`, `mergePiece`, `dropDistance`, `gravityInterval`, `levelForLines`, `lineScore`, `createLockDelay`, `stepLockDelay` |
656
+ | Falling tile grid | `tactics/fallingGrid` | `createFallingGrid`, `FallingGrid`, `FallingGridConfig`, `FallingGridCell`, `FallingGridSnapshot`, `LockState`, `gravityIntervalMs`, `GravityIntervalConfig` — a generic tile-drop grid (any `TCell` payload), distinct from `puzzle/cellGrid`+`puzzle/fallingPiece`'s row-clear/shape-table pair |
657
+ | Spawn/respawn points | `game/spawnPoints` | `createSpawnPoints`, `SpawnPoints`, `SpawnPointPose`, `RespawnTarget` |
658
+ | Level sequence | `game/levelSequence` | `createLevelSequence`, `LevelSequence`, `LevelSequenceConfig`, `LevelDescriptor`, `CurrentLevel`, `LevelSequenceStatus`, `LevelSequenceProgress` |
659
+ | Devtools overlay + tunables | `devtools/devtools` | `devtools`, `createDevtools`, `tunable`, `snapshotDevtools`, `instrumentLatency`, `Tunable`, `TunableOptions`, `TunableAccessor`, `DevtoolsControl`, `DiscoveredEntry`, `DevtoolsOverrides`, `DevtoolsSnapshot` |
660
+ | Tunable auto-discovery | `devtools/transformTunables` | `transformTunableExports`, `tunableModuleTable`, `tunableDiscoveryPlugin`, `TunableTransformResult` |
661
+
662
+ ## Getting started (new project)
663
+
664
+ Fastest path — the `jgengine` CLI scaffolds the entire canonical shape below (harness, skeleton, stub game, verify test, AGENTS.md) as a booting game:
665
+
666
+ ```sh
667
+ npx jgengine create my-game # then: cd my-game && bun dev
668
+ npx jgengine doctor # later, if the setup drifts (version skew, unstyled HUD, shape strays)
669
+ ```
670
+
671
+ Manual equivalent:
672
+
673
+ ```sh
674
+ bun add @jgengine/core @jgengine/react @jgengine/shell react react-dom three three-stdlib @react-three/fiber @react-three/drei
675
+ bun add -d @tailwindcss/vite tailwindcss # HUD styling (Vite + Tailwind v4)
676
+ ```
677
+
678
+ A single game's standalone entry mounts `GameHost` (`@jgengine/shell/GameHost`) over the `game` your `game.config.ts` exports. The full standalone harness is four small files plus a script — this is exactly the shape every `Games/*` game ships, so `bun dev` plays it on its own with no host app:
679
+
680
+ ```html
681
+ <!-- index.html -->
682
+ <!doctype html>
683
+ <html lang="en">
684
+ <head>
685
+ <meta charset="UTF-8" />
686
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
687
+ <title>My Game</title>
688
+ </head>
689
+ <body>
690
+ <div id="root"></div>
691
+ <script type="module" src="/src/main.tsx"></script>
692
+ </body>
693
+ </html>
694
+ ```
695
+
696
+ ```ts
697
+ // vite.config.ts — monorepo-aware: the alias branch only fires when this folder
698
+ // sits inside the engine repo checkout; copied anywhere else, @jgengine/* resolves
699
+ // from npm dist and the alias list is empty
700
+ import { existsSync } from "node:fs";
701
+ import { fileURLToPath } from "node:url";
702
+ import tailwindcss from "@tailwindcss/vite";
703
+ import react from "@vitejs/plugin-react";
704
+ import { defineConfig } from "vite";
705
+
706
+ const engineSrc = (pkg: string) => fileURLToPath(new URL(`../../packages/${pkg}/src`, import.meta.url));
707
+
708
+ export default defineConfig({
709
+ plugins: [react(), tailwindcss()],
710
+ resolve: {
711
+ alias: existsSync(engineSrc("core"))
712
+ ? [
713
+ { find: /^@jgengine\/core\/(.*)$/, replacement: `${engineSrc("core")}/$1` },
714
+ { find: /^@jgengine\/react\/(.*)$/, replacement: `${engineSrc("react")}/$1` },
715
+ { find: /^@jgengine\/ws\/(.*)$/, replacement: `${engineSrc("ws")}/$1` },
716
+ { find: /^@jgengine\/shell\/(.*)$/, replacement: `${engineSrc("shell")}/$1` },
717
+ { find: /^@jgengine\/assets$/, replacement: `${engineSrc("assets")}/index.ts` },
718
+ { find: /^@jgengine\/assets\/(.*)$/, replacement: `${engineSrc("assets")}/$1` },
719
+ ]
720
+ : [],
721
+ },
722
+ });
723
+ ```
724
+
725
+ ```css
726
+ /* src/index.css */
727
+ @import "tailwindcss";
728
+ @source "../node_modules/@jgengine/react/dist";
729
+ @source "../node_modules/@jgengine/shell/dist";
730
+ ```
731
+
732
+ Inside the engine repo the two `@source` lines point at `../../../packages/react/src` and `../../../packages/shell/src` instead (see any `Games/*/src/index.css`) — same file, different `@source` targets depending on where dist lives.
733
+
734
+ ```tsx
735
+ // main.tsx
736
+ import "./index.css";
737
+
738
+ import { createRoot } from "react-dom/client";
739
+ import { GameHost } from "@jgengine/shell/GameHost";
740
+ import { game } from "./game.config";
741
+
742
+ const root = document.getElementById("root");
743
+ if (root === null) throw new Error("main: missing #root mount element");
744
+ createRoot(root).render(<GameHost playable={game} />);
745
+ ```
746
+
747
+ Add `"dev": "vite"` to `package.json`'s `scripts` — `bun dev` then launches the game standalone.
748
+
749
+ `GameHost` resolves multiplayer itself from `game.multiplayer` (falling back to offline when the adapter can't resolve, with a console warning) — pass `multiplayer` (a prebuilt `ShellMultiplayer | null`, used as-is with no resolution attempted) or `resolveMultiplayer` (`(args) => ShellMultiplayer | null`, tried before the built-in resolver, falling back to it on `null`) only when the host app needs to supply its own session, e.g. trying several transports in sequence.
750
+
751
+ A multi-game host (a launcher, a dev registry) wires `GamePlayer` over a `GameRegistry`:
752
+
753
+ ```tsx
754
+ import { GamePlayer } from "@jgengine/shell/GamePlayer";
755
+ import type { GameRegistry } from "@jgengine/shell/registry";
756
+
757
+ const games: GameRegistry = {
758
+ "my-game": () => import("./my-game").then((m) => m.game),
759
+ };
760
+
761
+ function App() {
762
+ return <GamePlayer gameId="my-game" registry={games} loading={<p>Loading…</p>} />;
763
+ }
764
+ ```
765
+
766
+ `GamePlayer({ gameId, registry, fallbackGameId?, loading?, multiplayer? })` (`@jgengine/shell/GamePlayer`) is `GamePlayerShell` plus the lazy-load glue: it looks up `gameId` in `registry`, awaits the loader, renders `loading` (default `null`) until it resolves, then mounts `GamePlayerShell playable={...} multiplayer={...}`; switching `gameId` re-triggers the load, and an in-flight load is discarded if the id changes again first. `resolveGameLoader(registry, gameId, fallbackGameId?)` (`@jgengine/shell/registry`) is the underlying lookup — `registry[gameId] ?? registry[fallbackGameId]` — for hosts that want the fallback behavior without the component.
767
+
768
+ HUD styling is Tailwind v4 via the `index.css` above — without its `@source` lines the HUD renders unstyled. Then build the game itself under `src/` per the layout below — `src/game.config.ts` is the single entry, defined with `defineGame` from `@jgengine/shell/defineGame`.
769
+
770
+ ## Scope
771
+
772
+ This file documents engine primitives and conventions only — never game domain. Example ids (`iron_block`, `mob_grunt`, `shop_town`) are placeholders, not content to copy.
773
+
774
+ | Engine owns | Your game owns |
775
+ |-------------|----------------|
776
+ | Weighted loot RNG, trade validation, loadout application, quest journal state, social graph, stat clamp math, effect absorption, projectile geometry, death resolution, event bus, feeds, leaderboards, input capture, pose hitboxes | Catalog entries and ids, effect id names, XP curves, shop/item/quest/loadout definitions, use-handlers, AI logic, UI content |
777
+
778
+ **Rules:**
779
+
780
+ 1. **Catalog-first** — shape and behavior of every id lives in game-owned catalog files. Runtime calls pass ids, positions, instance keys.
781
+ 2. **Three buckets** — inventory items, scene objects, scene entities. Never merge them.
782
+ 3. **Dumb place/spawn** — no behaviors on `place()`/`spawn()`; the catalog owns them.
783
+ 4. **Commands for verbs** — input maps to actions, actions to commands/handlers; no raw keys in game logic.
784
+ 5. **Primitives over glue** — a loop several games need (loot roll, shop buy, kit seeding) belongs in the engine, not copy-pasted per game.
785
+ 6. **No speculative config** — `defineGame` fields exist only with a live engine consumer.
786
+ 7. **This file stays domain-free.**
787
+
788
+ ## The three buckets
789
+
790
+ | Bucket | What | API |
791
+ |--------|------|-----|
792
+ | **Inventory** | Stackable ids in containers | `ctx.player.inventory.put / take / move / has / count` |
793
+ | **Scene object** | Static world content | `ctx.scene.object.place / remove / move / rotate / list` |
794
+ | **Scene entity** | Movers driven per tick | `ctx.scene.entity.spawn / despawn / setPose / effect / …` |
795
+
796
+ A voxel block is an object. A rack is an object with a slot inventory. A GPU is an inventory item inside it. A player, mob, or car is an entity. A dropped-item lying on the ground is also an entity — `ctx.scene.worldItem` (position + item ref + rarity, spawned under `game/worldItem`'s `WORLD_ITEM_ENTITY_NAME`) — never a fourth bucket and never merged into inventory or object.
797
+
798
+ ## Game repo layout
799
+
800
+ Every game is one shape, enforced by `check-game-shape` (part of `check-types`): the top of `src/` holds only the skeleton, and every game-specific module, UI component, and test lives under `src/game/`. Dense files — one `catalog.ts` per domain, never one file per entry.
801
+
802
+ ```
803
+ src/
804
+ game.config.ts single entry — export const game = defineGame({...}) from "@jgengine/shell/defineGame"
805
+ index.tsx barrel — export { game } from "./game.config" (+ any UI-preview scenario re-export)
806
+ main.tsx standalone host — mounts <GameHost playable={game}/> from "@jgengine/shell/GameHost"
807
+ loop.ts onInit, onNewPlayer, onTick
808
+ world.ts WorldFeature + PhysicsConfig (only for games that have one)
809
+ game/
810
+ keybinds.ts ActionCodesMap — named actions + hotbarSlotBindings(n)
811
+ inventories.ts inventory declarations
812
+ assets.ts Render catalog
813
+ content.ts itemById / entityById lookups over all catalogs
814
+ loadouts.ts Loadout ids → items/economy/unlocks per inventory
815
+ world/ zones.ts, setup.ts (place/spawn from onInit)
816
+ items/ <domain>/catalog.ts + use-handlers.ts
817
+ objects/ catalog.ts (+ loot tables beside their domain)
818
+ entities/ players/ enemies/ npcs/ — catalog.ts per role (never actors/)
819
+ quests/catalog.ts when using game.quest
820
+ progression/ curves.ts — game-owned XP curve numbers fed to game/progression
821
+ ui/GameUI.tsx ALL layout/positioning
822
+ ui/components/ content-only pieces GameUI places
823
+ ```
824
+
825
+ ## `defineGame` — the single authoring entry
826
+
827
+ `@jgengine/shell/defineGame` is the game-authoring entry: one call in `game.config.ts` takes both engine fields (`name`, `assets`, `world`, `physics`, `inventories`, `input`, `server`, `save`, `time`, `feed`, `multiplayer`) and presentation fields (`content`, `loop`, `GameUI`, `camera`, `environment`, `WorldOverlay`, `renderEntity`, `renderObject`, `entitySprites`, `entityModels`, `objectModels`, `hotbarSelection`, `prompts`, `pointer`, `touch`, `worldHealthBars`, `audio`, `entitySounds`, `objectSounds`, `worldItem`, `shadows`, `collision`, `movement`, `devtools`) and returns a ready `PlayableGame` — no separate object to assemble. It is a thin wrapper over the core `defineGame` primitive (below) plus the `PlayableGame` runner assembly; see `packages/shell/src/defineGame.tsx` for the exact accepted fields. Never game tuning (walk speeds, damage, prompts — those live in catalogs).
828
+
829
+ **Smart defaults** — omit any of these and the call still resolves: `multiplayer` → `offline()`; `assets` → an empty asset catalog; `loop` hooks (`onInit`/`onNewPlayer`/`onTick`) → no-ops; `content` → `{}`; `GameUI` → an empty component; `camera` → third-person orbit; `feed` → 20-entry ring buffers per action; a `world` of kind `environment()` auto-renders as the backdrop with no `environment` component supplied — a non-`environment()` world (`flat()`, `voxel()`, …) still needs the game to hand it one.
830
+
831
+ ```ts
832
+ // game.config.ts — imports only, nothing inline
833
+ import { defineGame } from "@jgengine/shell/defineGame";
834
+ import { assets } from "./game/assets";
835
+ import { content } from "./game/content";
836
+ import { GameUI } from "./game/ui/GameUI";
837
+ import { inventories } from "./game/inventories";
838
+ import { keybinds } from "./game/keybinds";
839
+ import { loop } from "./loop";
840
+ import { physics, world } from "./world";
841
+
842
+ export const game = defineGame({
843
+ name: "My Game",
844
+ assets,
845
+ world,
846
+ physics,
847
+ inventories,
848
+ input: keybinds,
849
+ server: "persistent", // or { mode: "ffa", scoreLimit: 30 } — rules live in game code
850
+ save: { auto: "5m", scope: "player+chunks" }, // or "none"
851
+ multiplayer: offline(), // or ws({ topology, url? }) / fly({ app }) / convex({ topology }) / socketIo({ topology, url? }) / p2p({ room? }) / lan({ port?, path? }) / servers({ …, adapter }) — defaults to offline()
852
+ content,
853
+ loop, // Partial<GameLoop<GameContext>> — missing hooks default to no-ops
854
+ GameUI,
855
+ camera: { perspective: "third" }, // optional — this is the default
856
+ });
857
+ ```
858
+
859
+ ```ts
860
+ // game/keybinds.ts — named actions + generated hotbar slots; one key, one action
861
+ import { hotbarSlotBindings, type ActionCodesMap } from "@jgengine/core/input/actionBindings";
862
+
863
+ export const keybinds: ActionCodesMap = {
864
+ moveForward: ["KeyW"], moveBack: ["KeyS"], moveLeft: ["KeyA"], moveRight: ["KeyD"],
865
+ jump: ["Space"], sprint: ["ShiftLeft"],
866
+ interact: ["KeyE"],
867
+ crouch: { hold: ["KeyC"], toggle: ["KeyZ"] },
868
+ aim: { hold: ["mouse2"], toggle: ["KeyV"] },
869
+ tabTarget: ["Tab"], clearTarget: ["Escape"],
870
+ ...hotbarSlotBindings(9), // hotbarSlot1..9 → Digit1..9 (a 10th slot gets Digit0)
871
+ };
872
+ ```
873
+
874
+ ```ts
875
+ // game/inventories.ts
876
+ import type { InventoryDeclaration } from "@jgengine/core/game/defineGame";
877
+ export const inventories: Record<string, InventoryDeclaration> = {
878
+ hotbar: { slots: 9, hud: "hotbar" },
879
+ backpack: { slots: 28, traits: itemTraits },
880
+ equipment: { slots: 4, accepts: ["weapon", "armor"], applyModifiers: true },
881
+ };
882
+
883
+ // world.ts — top of src/, not under game/
884
+ import type { PhysicsConfig } from "@jgengine/core/game/defineGame";
885
+ import { biomes, type WorldFeature } from "@jgengine/core/world/features";
886
+ export const world: WorldFeature = biomes({ map: "world/biomes", zones: "world/zones" });
887
+ export const physics: PhysicsConfig = { gravity: -32 };
888
+ ```
889
+
890
+ - `PhysicsConfig.gravity`/`jumpVelocity` tune the shell's built-in walk controller's fall/jump feel (defaults ~`-24`/`7.1`) — the only two levers on gravity and jump height; everything else about movement (speed, poses) stays catalog `movement` fields.
891
+ - Input bindings are string arrays (hold semantics) or `{ hold, toggle, repeatMs? }` for the same verb. `repeatMs` turns a held action into an auto-repeat fire (build-mode place-on-drag, rapid-fire without a separate `wasPressed`/interval combo in game code) — the shell refires the command every `repeatMs` while the binding stays down, on top of its normal press-edge fire.
892
+ - **Keybind → command convention.** The shell fires a command for any bound action that isn't reserved: pressing an action runs a command of the **same name** if one is defined, else a `ui.<action>` fallback (so `openBackpack` → `ui.openBackpack`). Just declare the binding and a matching command — no per-game `keydown` listener. Reserved actions the shell consumes natively and never routes to a command: `moveForward/moveBack/moveLeft/moveRight`, `turnLeft/turnRight`, `sprint`, `jump`, `tabTarget`, `clearTarget`, `useAbility`, `interact`, and any `hotbarSlotN`/`slotN`. `tabTarget`/`clearTarget` run `target.cycle`/`target.clear` (native `cycleTarget`/`setTarget` fallback).
893
+ - **`interact`** is special: pressing it resolves the active proximity prompt from the `prompts` field of `defineGame({...})` and runs that prompt's `invoke` command. A prompt with `invoke: null` is display-only and does nothing on the key.
894
+ - UI keybind badges derive from `keybinds` via `actionLabel(keybinds, "openBackpack")` — `bindingLabel` maps codes to short labels (`Digit1`→`1`, `KeyB`→`B`, `mouse0`→`LMB`, `Escape`→`Esc`). Never hardcode label strings; they drift the moment a binding changes.
895
+ - `server.mode` is a string your loop/commands interpret — the engine ships no gamemode presets.
896
+ - Never in defineGame: player tuning, catalog helpers (`defineItems` etc.), game nouns, behaviors, prompts, or inline binding/inventory/world blobs. The one exception is `physics.gravity`/`physics.jumpVelocity` — global controller tuning, not a catalog value (see "Controller kinematics" below).
897
+ - `assets` may be omitted for a game with no models (a HUD-only card/board game, say) — `defineGame` injects an empty catalog, so `GameDefinition.assets` is always present downstream with no per-caller `?.` checks.
898
+ - `devtools` defaults to `true` — every game gets the F2-toggled debug overlay (Perf/Tune/Logs/Net/Keys) for free, and every top-level `export const` number/boolean/color and every exported flat table of them under `src/` is auto-discovered into the Tune tab with zero game code; set `false` to disable the toggle entirely. See "Devtools — F2 overlay and tunables" below.
899
+
900
+ ### `@jgengine/core/game/defineGame` — the underlying primitive
901
+
902
+ The low-level engine boot call the shell `defineGame` composes internally: engine fields only (`name`, `assets`, `world`, `physics`, `inventories`, `input`, `server`, `save`, `time`, `feed`, `multiplayer`, `loop`) — no `content`/`GameUI`/`camera`/render fields, those are the shell layer's job.
903
+
904
+ ```ts
905
+ import { defineGame as defineEngineGame } from "@jgengine/core/game/defineGame";
906
+ import { offline } from "@jgengine/core/runtime/adapter";
907
+
908
+ const game = defineEngineGame({
909
+ name: "My Game",
910
+ assets, world, physics, inventories,
911
+ input: keybinds,
912
+ server: "persistent",
913
+ save: { auto: "5m", scope: "player+chunks" },
914
+ multiplayer: offline(),
915
+ loop, // GameLoop<GameContext>
916
+ });
917
+ ```
918
+
919
+ Reach for this directly only outside a React host — a headless server, a non-shell runner; a browser game authors through `@jgengine/shell/defineGame` above, which calls this and returns the `PlayableGame` a runner needs.
920
+
921
+ ## `PlayableGame` — how a game plugs into a runner
922
+
923
+ The type `@jgengine/shell/defineGame` returns and every runner (`GameHost`, `GamePlayerShell`) consumes. A game never builds this object by hand — `defineGame({...})` assembles it from the merged config. Source type at `@jgengine/core/game/playableGame`:
924
+
925
+ ```ts
926
+ export type PlayableGame<TUi = unknown> = {
927
+ game: GameDefinition;
928
+ content: GameContextContent; // { itemById?, entityById?, objectById? }
929
+ loop: Required<GameLoop<GameContext>>; // onInit, onNewPlayer, onTick
930
+ GameUI: TUi; // React component in web runners
931
+ prompts?: (ctx: GameContext) => readonly PositionedPrompt[]; // interact-key + HUD source
932
+ };
933
+ ```
934
+
935
+ `prompts` is the **single source** of positioned proximity prompts: the shell reads it to fire the `interact` key, and the HUD should read the same list through `useActivePrompt(playable.prompts?.(ctx))` rather than building its own — one list, no drift. A prompt is only actionable if its `invoke` is non-null.
936
+
937
+ Optional render/world fields the shell also reads: `entitySprites` / `entityModels` (billboards / GLBs keyed by entity kind), `objectModels` (GLBs keyed by object catalog id), `renderObject` (per-object visual override — return your own mesh for a placed object and the shell still positions it; falls back to `objectModels` → colored box), `WorldOverlay` (canvas-layer VFX), `environment` (canvas-layer scenery — ground/sky/structures; when set, replaces the default ground plane + debug grid + rock field), `camera`, `shadows` (cast/receive shadows across the R3F canvas; default true), and `worldHealthBars` (`boolean | { statId?, roles? }` — `roles` restricts bars to entities whose catalog `role` is in the given `CatalogEntityRole` list, e.g. skip friendly NPCs). A model value is a catalog id (`string`, resolved via `game.assets`) or an inline `ModelConfig { url, scale?, y?, anchor?, dims?, material?, animation? }` (`material` overrides color/metalness/roughness/emissive/emissiveIntensity on the cloned mesh, leaving shared GLTF caches untouched; `animation?: { clip?, loop?, timeScale?, paused?, time? }` plays a GLTF clip — `clip` defaults to the first clip, `loop` defaults true — and `paused: true` + `time: <seconds>` holds the rig on one fixed frame, a pose library for inventory previews or held cutscene poses). Catalog-resolved models carry measured `dims` (`catalog.resolve(id).dims = { footprint:{w,d}, center:{x,z}, minY }`); with the default `anchor: "center"` the shell centers the footprint on the placement point and ground-snaps `minY` to it, so corner-pivot kit models place correctly with no per-game pivot math. Applies through both `entityModels` and `objectModels`.
938
+
939
+ `renderEntity?: (entity: SceneEntity) => ReactNode` and `renderObject?: (object: SceneObject) => ReactNode` hand you the mesh for one entity/object while the shell still positions it and keeps it tagged for picking/selection; return null/undefined to fall through to model → sprite/box. `objectStyles?: Record<catalogId, { color?, opacity?, hidden? }>` styles the default colored-box object render — `color` overrides the hash color, `opacity < 1` sets transparent, `hidden` skips the mesh but keeps the picking tag.
940
+
941
+ **Presentation mode.** `PlayableGame.presentation`: `"3d"` (default) mounts the canvas, camera rig, and pointer; `"hud"` mounts none of that — the game is `GameUI` plus the command/input loop, for board/card/menu games that need no 3D camera at all.
942
+
943
+ **Auto environment.** When `world` is an `environment()` descriptor and `PlayableGame.environment` is unset, the shell renders that descriptor as the backdrop automatically — no manual `environment` wiring needed for the common case. Set `environment` explicitly only to override that default (a custom canvas component always wins). The same auto-render convention covers grid-cell worlds (`biomes`/`voxel`/`plots`/`tilemap`) — see "World features" below.
944
+
945
+ **Lighting and backdrop.** `PlayableGame.lighting` (`LightingConfig`, `@jgengine/core/game/playableGame`) replaces the shell's hardcoded ambient/directional default when present, regardless of world kind: `ambient?: { color?, intensity? }`, `directional?: { color?, intensity?, position, castShadow? }[]`, `hemisphere?: { skyColor?, groundColor?, intensity? }`. `PlayableGame.backdrop` (`BackdropConfig`) is a generic background/sky/fog for **any** world kind, including a custom `environment` component: `background?: string` (CSS color), `sky?: SkyEnvironmentConfig` (same descriptor `environment()`'s `sky` field takes), `fog?: { color?, near?, far?, density? }` (`density` set switches to exponential `FogExp2` and `near`/`far` are ignored). Both are optional and additive to whatever the world/`environment` renderer already draws.
946
+
947
+ **Visibility & streaming (automatic).** Every 3D game gets camera frustum + distance culling for free — the shell's `CullingProvider` reads the live camera each frame, runs the engine `createVisibilitySystem` (`@jgengine/core/visibility/visibilitySystem`) over the scene's entities and placed objects, and toggles `group.visible` so off-screen objects are never submitted to the renderer (never unmounted — gameplay and simulation are untouched). Defaults are conservative (a preload margin larger than the view, hysteresis, `Infinity` default render distance) so existing games only benefit. Tune or opt out via `PlayableGame.visibility` (`VisibilityConfig`, `@jgengine/core/visibility/config`): `enabled: false` disables it; `culling`/`streaming` patch the global `CullingSettings`/`StreamingSettings` (`@jgengine/core/visibility/settings`); `scene` sets scene-wide overrides; `entities`/`objects` override by kind name / catalog id (`alwaysVisible`, `maxRenderDistance`, custom `bounds`, `pinned`, `cullingDisabled`, …). The engine layer also ships `@jgengine/core/visibility/spatialIndex` (the 3D hash the culler queries instead of scanning every object), `@jgengine/core/visibility/assetStreaming` (dedup/budget/grace-period asset loading), and `@jgengine/core/visibility/simulationCulling` (opt-in, off by default — throttles low-priority off-screen updates, never protected entities). Full reference: `packages/core/src/visibility/README.md`.
948
+
949
+ **Player movement tuning** — the `movement` field (`PlayerMovementConfig`) tunes the shell's local-player walk controller beyond `physics.gravity`/`jumpVelocity`: `mode` (`"free"` camera-relative default, `"axis"` locks travel to one world `axis`, `"grid"` snaps each committed step to `cellSize` centers), `collideObjects` (collide against placed scene objects as unit-box AABBs even without `collision.voxel`), and `beforeCommit(frame)` — an escape hatch called each frame with `{ entityId, current, next, dt }` that can return a replacement `[x, y, z]` to constrain or redirect the step (rails, bounds, custom collision) before it commits and before `onTick` runs.
950
+
951
+ The runner boots `createGameContext({ definition, content, player: { userId, isNew } })`, calls `loop.onInit(ctx)` then `loop.onNewPlayer(ctx)`, and drives `loop.onTick(ctx, dt)` per frame. **Convention: `onNewPlayer` spawns the player entity with `id === ctx.player.userId`** — bounded stats, targeting, and kill attribution key off that.
952
+
953
+ ### Object spatial queries, entity patching, and surface sampling
954
+
955
+ ```ts
956
+ ctx.scene.object.at(x, y, z) // cell lookup, cell size 1, most-recent wins
957
+ ctx.scene.object.inBox(min, max) // inclusive AABB query
958
+ ctx.scene.object.raycast({ origin, direction, maxDistance, halfExtents?, filter? }) // → nearest hit or null
959
+ ctx.scene.object.raycastAll({ origin, direction, maxDistance, halfExtents?, filter? }) // → hits, nearest-first
960
+ ctx.scene.entity.update(id, patch) // name/position/rotations/role/movement/behaviors/meta; false for unknown id
961
+ ```
962
+
963
+ Placed objects are unit boxes (half-extents `[0.5, 0.5, 0.5]`) centered on position, matching the shell's default render, so `raycast`/`raycastAll` (`scene/objectQuery`) match what a player sees. `entity.update` notifies subscribers and bumps `ctx.version()` the same as `spawn`/`despawn`/`setPose` — it's the general-purpose patch the more specific methods (`setPose`, `form.shapeshift`, `possession.possess`) build on.
964
+
965
+ `ctx.scene.object.place(catalogId, x, y, z, { instanceId?, parentSpace?, rotation?, visual? })` takes an optional `visual: ObjectVisual` (`@jgengine/core/scene/objectStore`) — `{ scale?: number | [x,y,z], color?, opacity? }` — a per-instance render override independent of the catalog entry; `ctx.scene.object.setVisual(instanceId, visual | undefined)` changes it after placement (`undefined` clears back to the catalog default). Distinct from `objectStyles` on `PlayableGame` (styles a catalog id for every instance); `visual`/`setVisual` targets one placed instance (a damaged crate, a dyed banner, a resized prop).
966
+
967
+ `pointerService.worldHitCenter()` (shell) casts from the viewport center regardless of cursor presence (pointer-lock aim) — combine with `pointer.worldHit()` (cursor-driven) to support both mouse-look and free-cursor games from the same probe. `PointerHit` also carries an optional `uv?: { u, v }` on UV-mapped mesh hits (absent for the ground fallback), `material?: { color, metalness?, roughness? } | null` sampled off the hit mesh's `MeshStandardMaterial` (`null`/unset for non-standard materials, e.g. the ground plane) — combine `uv` + `material` for paint tools, decals, and material-aware interaction — and `instanceId?: number`, the hit index when the intersected mesh is a `THREE.InstancedMesh` (grid-world cells, `InstancedBodies` debris, any instanced render), absent otherwise.
968
+
969
+ **Runtime paint layer** (`ctx.scene.entity.paint`, backed by `scene/paintLayer`) — a `PaintLayer` keyed by instance id (entity or object): `paint(instanceId, { u, v, radius, color })`, `strokes(instanceId)`, `clear(instanceId?)`, `version(instanceId)` (bumps per paint/clear), `subscribe(listener)`. The shell auto-renders painted instances through a lazily-created 512×512 canvas texture kept in sync — no per-game render wiring. Clearing refills with the material's base color; the original texture pixels are not restored.
970
+
971
+ ### Audio — positional emitters, listener falloff, buses
972
+ Catalog-first, no per-game audio glue. The `audio` field of `defineGame({...})` — `{ sounds: Record<string, SoundDef>, buses?: Record<string, AudioBusDef> }` — declares the sound catalog (`SoundDef = { id, url, bus, gain?, loop?, positional?, falloff? }`) and mix buses (`music`/`sfx`/`ambient`/…, `AudioBusDef = { id, gain? }`) — both types from `@jgengine/core/audio/audioFalloff`. `entitySounds?: Record<string, string>` maps an entity **kind name** (same convention as `entitySprites`/`entityModels`) to a sound id: while a matching entity exists, the shell keeps a looping positional emitter on it, repositioned every frame. `objectSounds?: Record<string, string>` does the same keyed by placed-object catalog id. The pure distance→gain math (`computeFalloffGain(distance, config)`, curves `"linear" | "inverse" | "none"`) lives in core so it is unit-tested without a browser; `@jgengine/shell` (`shell/audio/audioEngine`, `shell/audio/AudioComponents`) is the only package that touches Web Audio — it owns an `AudioContext`, mounts `AudioListener` on the camera every frame, and `EntityAudioEmitters`/`ObjectAudioEmitters` drive per-instance emitter gain from the core falloff function. `GamePlayerShell` wires all of this automatically from `playable.audio`/`entitySounds`/`objectSounds` — a game never touches `AudioContext` directly.
973
+ ### Camera rigs (`camera` field of `defineGame({...})`)
974
+ The shell ships a **rig library**; a game picks and tunes one through `camera` config, never by writing camera positions from `onTick`. Select with `camera.rig` (or the `perspective: "third" | "first"` shorthand) — or by config block alone (#207.8): supplying `camera.<rig>` selects that rig with no redundant `rig` field, checked in the table's order; an explicit `rig` wins when several blocks are present:
975
+ | `rig` | For | Key config (`camera.<rig>`) |
976
+ |-------|-----|------------------------------|
977
+ | `orbit` (default) | Third-person chase | `initialDistance`, `targetHeight`, `min/maxPolarAngle`, drag/zoom |
978
+ | `first` | FPS mouse-look | `firstPerson: { eyeHeight, sensitivity, maxPitch, reticle, viewmodel }` |
979
+ | `topDown` | ARPG iso / top-down (Diablo IV, Hades II) | `topDown: { height, pitch, yaw, followSmoothing, zoom }` — decoupled follow; `pitch` is camera elevation (PI/2 = straight down, near 0 = grazing and boom-distance blows up past `frustum.far`) |
980
+ | `rts` | Free-pan / edge-scroll (The Sims, Manor Lords) | `rts: { panSpeed, edgeScroll, rotateSpeed, bounds, start, pan }` — `pan: false` turns it into a static backdrop camera: no WASD/arrow pan, no edge-scroll, no Q/E rotate, no wheel zoom, still re-centers on `followEntityId` if one resolves |
981
+ | `shoulder` | Over-the-shoulder (Helldivers 2, Remnant II) | `shoulder: { shoulderOffset, distance, ads, side }` — ADS + shoulder-swap (V) |
982
+ | `lockOn` | Souls-like strafe (Elden Ring) | `lockOn: { targetEntityId?, distance, framingBias, yawSmoothing }` — yaw binds to player→target; WASD becomes strafe |
983
+ | `chase` | Vehicle chase (Forza, Rocket League) | `chase: { distance, springDamping, fov: { base, max, speedForMax }, shakePerSpeed, view: "chase"|"cockpit"|"hood"|"rear" }` |
984
+ | `sideScroll` | Fixed lateral follow — 2.5D platformer/beat-'em-up | `sideScroll: { distance, height, lookHeight, axis: "x"\|"z", followSmoothing, fov }` — reads no player input, follows like the other follow rigs (defaults to the local player) |
985
+ | `observer` | Detached spectator/photo/kill-cam (#120) | `observer: { bind: { kind: "entity", entityId } \| { kind: "point", position }, distance, height, orbitSpeed }` — reads no player input, auto-orbits the bound subject |
986
+ | `inspection` | Model-viewer / data-viz orbit (#207.7) | `inspection: { anchor: "target"\|"cursor"\|"center", target, initialDistance, initialPosition, min/maxDistance, min/maxPolarAngle, pan, rotateSpeed, zoomSpeed, dampingFactor }` — left-drag orbit, middle/right-drag pan (pan defaults on for this rig only), scroll zoom toward the anchor (`cursor` = zoom-to-cursor); orbits a fixed `target`, never reads player/entity state |
987
+ | `none` | No camera rig mounted | HUD-only presentations or a game that manages its own camera; see `presentation: "hud"` below |
988
+ **Frustum:** `camera.frustum: { fov?, near?, far? }` overrides the canvas camera; `far` defaults to 300, so any world whose content spans more than a few hundred units must raise it or distant settlements/terrain silently clip out of view. **Every rig accepts `followEntityId: null`** so avatar-less games (city-builders, card games, auto-battlers) still mount a camera. Leave `followEntityId` unset and the shell defaults it to `ctx.player.possession.active(userId)` every frame, so a possession swap (party control-swap, BG3-style) or a form's mesh/camera-relevant change re-targets the camera automatically — set it explicitly only to override that default. **Shake / trauma (#28):** every rig reads a shake channel; feed it from anywhere with `import { cameraShake } from "@jgengine/shell/camera"` — `cameraShake(amplitude, decayPerSecond?)` (amplitude 0..1) — or from React via `useCameraShake()`. Tune with `camera.shake: { maxOffset, maxRoll, decayPerSecond, exponent, frequency }`. **Cinematic (#29):** set `camera.cinematic: { keyframes: [{ position, lookAt, fov?, duration?, ease? }], loop? }` to play a scripted path over the active rig, and `camera.transitionSeconds` cross-fades the camera when the rig changes so mode swaps don't hard-cut. The pure rig math (shake decay, spring-arm, speed→FOV, offset/strafe, keyframe lerp) is exported from `@jgengine/shell/camera` for testing.
989
+
990
+ ## `GameContext` — the ctx surface
991
+
992
+ `createGameContext` (in `@jgengine/core/runtime/gameContext`) wires every system:
993
+
994
+ ```
995
+ ctx.scene.object place, remove, move, rotate, get, list, subscribe,
996
+ at, inBox, raycast, raycastAll, catalog
997
+ ctx.scene.entity spawn, despawn, setPose, update, get, list,
998
+ stats.{get,set,delta}, setTarget, getTarget, cycleTarget,
999
+ canReceive, preview, effect, paint,
1000
+ willHitProjectile, fireProjectile, settleProjectile,
1001
+ distance, inRadius, hasLineOfSight, queryArc, moveToward,
1002
+ spawnPoseOf, resetToSpawn, resetAllToSpawn,
1003
+ form.{register,get,active,abilities,shapeshift,revert}
1004
+ ctx.game commands, events, feed, loot, trade, quest, social, chat,
1005
+ unlocks, economy, leaderboard, roster, store, cards, turn
1006
+ ctx.game.social friends, party, presence, emotes.play, worldInvites
1007
+ ctx.game.store set, delete, get, has, subscribe, mapSnapshot, arraySnapshot — game-defined
1008
+ keyed reactive store slot (any value type); mutations bump ctx.version()
1009
+ ctx.game.cards pile(id, config?) — lazily creates (config required on first call) or returns
1010
+ the existing notify-wrapped CardPile for id
1011
+ ctx.game.turn loop(id, config?) — lazily creates (config required on first call) or returns
1012
+ the existing notify-wrapped TurnLoop for id
1013
+ ctx.player userId, isNew, inventory, stats (modifiers), loadout,
1014
+ applyLoadout, movement (pose/aim), motion (impulse/setVerticalVelocity/setY/takePending),
1015
+ possession, cosmetics
1016
+ ctx.player.motion impulse(vy), setVerticalVelocity(vy), setY(y), takePending() — game-code
1017
+ seam into the shell's vertical-motion integrator; drained once per frame
1018
+ before gravity, so a jump pad or grapple release calls this from
1019
+ onTick/commands instead of touching y directly
1020
+ ctx.item use, weapon
1021
+ ctx.input publish(held), isDown(action), held() — per-frame held-action snapshot, polled from onTick
1022
+ ctx.world ground (TerrainField), groundHeightAt(x, z) — the canonical
1023
+ sampler for the game's declared world; environment worlds
1024
+ resolve their terrain field, every other world kind is 0.
1025
+ Use it for every spawn/placement/waypoint y — never
1026
+ hand-roll a noise sampler or hardcode y = 0 on relief
1027
+ ctx.camera follow(entityId | null), followedEntityId(), setCinematic(config), cinematic(),
1028
+ subscribe — runtime camera-follow/cinematic override; the shell reads
1029
+ followedEntityId() each frame, falling back to the static
1030
+ playable.camera.followEntityId when it returns undefined
1031
+ ctx.time advance, now, calendar, snapshot; pause, play, toggle,
1032
+ setSpeed, cycleSpeed; after, every, at (game-time timers)
1033
+ ctx.subscribe / ctx.version change signal — UI layers bind via useSyncExternalStore
1034
+ ```
1035
+
1036
+ `content.itemById(id)` supplies `{ use?, weapon?, trade? }`; `content.entityById(id)` supplies `{ stats?, receive?, onDeath?, movement?, role? }`; `content.objectById(id)` supplies `GameContextObjectEntry` `{ proximityPrompt?, breakable?, slotInventory? }`. Build all three from your catalogs in `content.ts`. A placed object resolves its catalog entry via `ctx.scene.object.catalog(instanceId)`; `ctx.scene.object.at(x, y, z, tolerance?)` finds placed objects near a point (grid interaction, click resolution beyond the pointer service). `ctx.scene.entity.update(id, patch)` writes a shallow patch onto a spawned entity's mutable fields (e.g. `movement.walkSpeed`) without a full respawn — `scene/movementSpeed`'s `applyStatDrivenSpeed(deps, id, { baseSpeed, multiplierStat?, flatBonusStat? })` is the catalog-driven helper that recomputes and writes `movement.walkSpeed` from a stat-modifier pair each time a buff changes.
1037
+
1038
+ ### Two tiers: `ctx` runtime vs pure factories
1039
+
1040
+ The `ctx` surface above is the **stateful runtime** — it's what game code uses. Every subsystem it wires is *also* exported as a **pure factory** that `createGameContext` composes internally: `createTradeSystem`, `createDeathSystem`, `createEffectSystem`, `createProjectileSystem`, `createSpatialApi`, `createEntityStatsApi`, `createEntityStore`, `createObjectStore`, `createStats`, `createLoadouts`, `createLootRegistry`, `createQuestJournal`, `createSocial`, `createSlots`, `createInteriors` (plus stateless helpers beside each — `canAffordCosts`/`resolveBuy` in `game/trade`, `getStatValue`/`applyPoolDelta` in `scene/entityStats`, and so on). **Build a game through `ctx`, not these** — reach for the factories only for unit tests of pure game math, headless servers, or a custom runtime. Import the domain deep path (`@jgengine/core/combat/death`, `@jgengine/core/game/trade`, `@jgengine/core/stats/statModifiers`, …) and read the `.d.ts`; each is a real export in the published package.
1041
+
1042
+ `createSpatialApi`'s optional `grid: { cellSize }` opts `inRadius`/`queryArc` into a lazily-built x/z broadphase index over `candidates()` instead of a linear scan — worth it once candidate counts run into the hundreds+. The index is reused across calls until `invalidate()` is called, so call it after any position change (move, spawn, despawn); a candidate outside the index at query time still resolves exactly (never silently skipped), only a *moved* one can be missed until invalidated.
1043
+
1044
+ ## `loop` — lifecycle
1045
+
1046
+ ```ts
1047
+ export function onInit(ctx: GameContext) {
1048
+ ctx.item.use.register(itemUseHandlers);
1049
+ ctx.player.loadout.register(loadouts);
1050
+ for (const table of lootTables) ctx.game.loot.register(table);
1051
+ ctx.game.quest.register(quests);
1052
+ ctx.game.quest.bind("entity.died");
1053
+ ctx.game.feed.bind("entity.died");
1054
+ ctx.game.events.on("entity.died", (evt) => onEntityDied(ctx, evt));
1055
+ setupWorld(ctx);
1056
+ }
1057
+
1058
+ export function onNewPlayer(ctx: GameContext) {
1059
+ ctx.scene.entity.spawn("player_default", { id: ctx.player.userId, position: spawnPoint });
1060
+ if (ctx.player.isNew) ctx.player.applyLoadout(ctx.player.userId, "starterKit");
1061
+ }
1062
+
1063
+ export function onTick(ctx: GameContext, dt: number) {
1064
+ // AI, regen, respawn timers — dt is GAME time (see ctx.time). Never death detection (see entity.died)
1065
+ }
1066
+ ```
1067
+
1068
+ `onInit` runs once per boot; register everything there. Loot tables register through `ctx.game.loot.register` — `lootTable()` is a pure validating factory, there is no global side-effect registry.
1069
+
1070
+ ## `ctx.time` — the simulation clock
1071
+
1072
+ `onTick`'s `dt` is **game time, not real time**: the shell scales each frame's real delta by `definition.time.scale` (real→game seconds at 1×) and the live speed multiplier, so writing decay/regen/AI as `rate * dt` makes it obey pause and fast-forward for free — never read wall-clock in a tick. Configure via `defineGame({ time: { scale?, speeds?, dayLength?, start?, startPaused?, daysPerYear?, seasons? } })` (all optional; default is real-time 1:1 with speeds `[1,2,3,4]`, 365-day years).
1073
+
1074
+ - **Continuous** work scales through `dt`. **Scheduled** work uses game-time timers: `ctx.time.after(sec, cb)`, `ctx.time.every(sec, cb)`, `ctx.time.at(gameSec, cb)` — measured in game-seconds, so 4× fires them 4× sooner and pause freezes them. Each returns a cancel handle.
1075
+ - **Controls** (drive from a HUD or a command): `pause()`, `play()`, `toggle()`, `setSpeed(mult)` (0 pauses), `cycleSpeed()`. Read state with `ctx.time.snapshot()` / `ctx.time.calendar()` (`{ day, hour, minute, second, dayFraction, year, dayOfYear, yearFraction, season? }`), or in React with `useGameClock()` → snapshot + `controls`. Speeding to 4× or pausing affects **everything** on the tick — no per-system wiring.
1076
+ - **Calendar year/season** rides the same day counter, no separate clock: `year`/`dayOfYear` fall out of `day` divided by `TimeConfig.daysPerYear` (default 365), `yearFraction` is progress through the current year (0..1). Setting `TimeConfig.seasons: string[]` (e.g. `["spring","summer","fall","winter"]`) slices the year into equal named segments and populates `calendar().season`; omit `seasons` and the field is absent — a living-world sim names its own season boundaries this way instead of a hand-rolled `dayOfYear % ...` module.
1077
+
1078
+ ### Beat clock — BPM signal + input quantization
1079
+
1080
+ `@jgengine/core/time/beatClock` is a separate, purpose-built signal from `simClock` — a BPM tick generator for rhythm games (Hi-Fi Rush–style quantized combat), not a day/pause clock. `createBeatClock({ bpm, beatsPerBar? }, onBeat?)` returns a `BeatClock`: call `advance(gameDt)` from `onTick` with the same **game-time** `dt` (never wall-clock) — it fires `onBeat(beatIndex)` once per newly crossed integer beat and returns a `BeatSnapshot` (`beat`, `beatIndex`, `bar`, `beatInBar`, `phase`). `createBeatInputBuffer<T>(beatDurationSec)` is the auto-correct input buffer: `buffer(action, nowSec)` quantizes an off-beat press to fire on the next beat tick (or immediately if pressed exactly on one); `advance(nowSec)` drains and returns every action whose beat has arrived. `nextBeatTime(nowSec, beatDurationSec)` is the underlying pure quantization function. Feed a music track's actual BPM in; the buffer is what makes an early/late input still land on-beat.
1081
+
1082
+ ## Content catalogs
1083
+ ## `ctx.game.store` — reactive game state
1084
+
1085
+ ```ts
1086
+ ctx.game.store.set("health", 100) // any key, any value type
1087
+ ctx.game.store.get("health") // T | undefined
1088
+ ctx.game.store.has("health")
1089
+ ctx.game.store.delete("health")
1090
+ ctx.game.store.subscribe(listener) // change-signal fires on set/delete
1091
+ ctx.game.store.mapSnapshot() / arraySnapshot()
1092
+ ```
1093
+
1094
+ A reactive per-game keyed store (`ObservableKeyedStore<unknown>`) attached to `GameContext` — reach for it instead of a module-level singleton store for ad-hoc reactive game state (turn trackers, deck UIs, anything that doesn't already have a `ctx` surface). `set`/`delete` bump `ctx.version()` and notify `ctx.subscribe` listeners; `get`/`has` are plain reads. Unlike a per-slot handle, there is no `define`/seed step — a key simply doesn't exist until the first `set`.
1095
+
1096
+ ## `ctx.game.cards` / `ctx.game.turn` — lazily-created piles and turn loops
1097
+
1098
+ `ctx.game.cards.pile(id, config?)` and `ctx.game.turn.loop(id, config?)` lazily create (config required on first call) or return the existing notify-wrapped `CardPile`/`TurnLoop` for `id` — call with just the id after the first `onInit` seed to fetch the same instance; every mutating method is wrapped so it bumps `ctx.version()`/notifies `ctx.subscribe` automatically, same as every other `ctx` surface. This replaces manually constructing `createCardPile`/`createTurnLoop` and wiring notification yourself.
1099
+
1100
+ ## Movement, pose, input
1101
+ ## External data — `data/dataSource` and the dev proxy
1102
+
1103
+ Renderer-free async-state primitives (`@jgengine/core/data`) for a game that reads a live external source (a leaderboard API, a session browser, remote config) — distinct from `ctx.game.store`/multiplayer, which are for the game's own authoritative state.
1104
+
1105
+ - **`createDataSource(load, options?)`** (`data/dataSource`) → `DataSource<T>` wraps one `load(signal)` async call as `{ status: "idle"|"loading"|"ready"|"error", data, error }`. `getState()` reads the current snapshot, `subscribe(listener)` fires on every change, `refresh({ force? })` re-runs `load` (de-duplicates a call already in flight unless `force`; aborts the prior call first when forced), `startPolling(intervalMs?)`/`stopPolling()` run `refresh` on an interval (`intervalMs` falls back to the one passed at construction; throws if neither is given), `dispose()` tears down polling and in-flight requests for good. Pass `options.clock` (`{ setInterval, clearInterval }`) to swap the timer source in tests.
1106
+ - **`fetchJson<T>(url, options?)`** (`data/fetchJson`) — `fetch` + JSON-parse in one call; throws `HttpStatusError` (`status`, `statusText`, `url`) on a non-OK response and `JsonParseError` (`url`, `cause`) on unparsable JSON, so a `DataSource`'s `error` is always one of these two typed shapes, never a bare `Error`. `options.fetchImpl` swaps the fetch implementation for tests/SSR.
1107
+ - **`createJsonDataSource<T>(url, options?)`** (`data/jsonDataSource`) — sugar combining the two above: a `DataSource<T>` whose `load` calls `fetchJson(url, options)`.
1108
+ - **Dev proxy (`data/devProxy`)** — same-origin routing for external APIs during `bun dev` so browser CORS never blocks a game's `fetchJson` call against a third-party host. `parseDevProxyTable(raw)` parses a `VITE_JGENGINE_DEV_PROXY` env value (a JSON object of `{ routeName: "https://api.example.com" }`) into a `DevProxyTable`; `proxiedUrl(target, { dev?, table?, prefix? })` rewrites a `target` URL whose prefix matches a table entry into `/proxy/<routeName>/<rest>` (default prefix `/proxy`) when `dev` is true (defaults to `import.meta.env.DEV`) — else returns `target` unchanged, so the same call hits the real host in production. `apps/dev`'s `vite.config.ts` reads the same env var and wires a matching Vite server `proxy` entry per route (`changeOrigin: true`, strips the `/proxy/<routeName>` prefix) — set `VITE_JGENGINE_DEV_PROXY` once and both sides (the URL rewrite and the actual proxy route) agree.
1109
+
1110
+ ## Multiplayer and the backend seam
1111
+ ## Genre cheat sheet
1112
+
1113
+ - **Voxel/crafting**: objects for blocks/machines, `voxel()`, `object.break`/`object.placeFromInventory`.
1114
+ - **Tycoon/lab**: objects + `slotInventory`, `plots()`, configure via prompt → command.
1115
+ - **Shooter**: `fireProjectile`/`settleProjectile`; grenades settle → `effect({ at, radius })`; `movement.poses`/`aim` + zoom modifier; `servers({ … })` + game-owned `server.mode`; loadout classes from commands.
1116
+ - **MMO/RPG**: bounded stats + `leveling()` over a game XP curve; `tabTarget` → `cycleTarget`; handlers read `getTarget`; quests bound to `entity.died`/`inventory.added`; social party + `partyShare`; `server: "persistent"`.
1117
+ - **All combat games**: react to `entity.died` (feed/leaderboard/score) — never poll HP.
1118
+
1119
+ ## Anti-patterns
1120
+
1121
+ | Wrong | Right |
1122
+ |-------|-------|
1123
+ | Player tuning in `defineGame` | Entity catalog `movement` + stats |
1124
+ | `behaviors: […]` on place/spawn | Catalog entry |
1125
+ | Engine `weapon.fire` / `consumable.use` / `combat.*` | `item.use` + catalog `use` → game handler |
1126
+ | `ItemUseInput.to` for targets | `getTarget(from)` in handlers |
1127
+ | `effect({ to })` for gunshots | `fireProjectile` + `settleProjectile` |
1128
+ | Polling HP in `onTick` for kills | `entity.died` event |
1129
+ | `combat.lootTable` / `loot.enemy` | `onDeath` on the entity that died |
1130
+ | Hand-rolled `Math.random()` loot in commands | `lootTable()` + `ctx.game.loot.roll` |
1131
+ | Hand-rolled `xpForLevel`/`levelFromXp` | `game/progression` `curve()` + `leveling()` |
1132
+ | Hardcoded shop arrays | `item.trade.shops` + `tradableAt` |
1133
+ | Kit seeding via scattered `put`/`grant` | `applyLoadout` |
1134
+ | Per-user quest state hand-rolled | `game.quest.register` + binds |
1135
+ | `useKillFeed` / per-domain feed hooks | `useFeed({ action })` |
1136
+ | Raw keys in game logic | `defineGame` input actions |
1137
+ | Positioning inside `ui/components/` or on primitives (`CurrencyPill className="absolute …"`) | Screen wrappers in `GameUI.tsx` only |
1138
+ | Game UI classes without `@source` in host CSS | `@source` entries for your game dirs + `node_modules/@jgengine/{shell,react}` |
1139
+ | One file per catalog entry / per brand | Dense `<domain>/catalog.ts` |
1140
+ | Convex mutations called from game code | `commands.run` through the `GameBackend` transport |
1141
+ | Half a system: quest without tracker, cooldown without sweep, keybind never shown, stub "coming soon" modal | Finish the system end to end — or cut it whole (see `jgengine`) |
1142
+ | Game-side workaround for a missing engine primitive | File the gap at github.com/Noisemaker111/jgengine/issues (or PR the primitive) and cut or scope the dependent system honestly |
1143
+ | Game nouns in this skill | Engine primitives + placeholder ids only |
1144
+
1145
+ ## New-game definition of done
1146
+
1147
+ This is a gate, not a suggestion — every box, in one pass (workflow: **`jgengine`** skill). "Compiles and the hooks are wired" is not done; a declared system with no UI, no feedback, or no way to exercise it is not done — finish the system or cut it whole.
1148
+
1149
+ - [ ] `game.config.ts` (`defineGame` from `@jgengine/shell/defineGame`) + `index.tsx` (barrel) + `main.tsx` (standalone host) + `loop.ts` + `game/content.ts`
1150
+ - [ ] Catalogs: `game/entities/<role>/catalog.ts`, `game/items/<domain>/catalog.ts`, `game/objects/catalog.ts`; loot tables beside their domain
1151
+ - [ ] Entity `stats` + `receive` orders aligned on the same stat ids; `role` set (drives targeting + camera)
1152
+ - [ ] `game/items/use-handlers.ts` registered in `onInit`; handlers read `getTarget`/`aim`, never a target input
1153
+ - [ ] `game/loadouts.ts` + `applyLoadout` in `onNewPlayer` (gated on `isNew`)
1154
+ - [ ] `game/quests/catalog.ts` + binds; if using xp/level, a game-owned curve fed to `game/progression` (`curve`/`leveling`) — **with their HUD/tracker, or cut**
1155
+ - [ ] `onInit`: register handlers/loadouts/loot/quests, event listeners, feed binds, leaderboard tracks; `setupWorld`
1156
+ - [ ] Player spawns with `id === ctx.player.userId`
1157
+ - [ ] `game/ui/GameUI.tsx` owns layout; components use `@jgengine/react` hooks
1158
+ - [ ] UI passes the **quality bar** above (contrast, scale, framing, genre fit) — not just hook wiring
1159
+ - [ ] Camera tuned via `camera` in `defineGame({...})` — defaults untouched means the feel was never checked
1160
+ - [ ] For an `environment()` world: a `<game>.world.test.ts` asserts `summarizeEnvironment(world)` (`@jgengine/core/world/environmentSummary`) is non-empty with the expected counts — the browserless scene-correctness gate
1161
+ - [ ] HUD screenshotted over a staged `GameUiPreview` scenario and **judged by looking at the image** against the UI quality bar in [`../jgengine-ui/reference.md`](https://github.com/Noisemaker111/jgengine/blob/main/.claude/skills/jgengine-ui/reference.md) — the final human glance, not the verification loop
1162
+ - [ ] Co-located bun tests for pure game math (curves, cooldowns, spawn logic)
1163
+ - [ ] Multiplayer via adapter config only; no direct backend calls
1164
+
1165
+ ## Quick reference
1166
+
1167
+ ```
1168
+ defineGame (shell) engine fields (assets, world, physics, inventories, input, server, save, time, feed, multiplayer)
1169
+ + presentation fields (content, loop, GameUI, camera, environment, shadows, movement, devtools, …) in one call — smart defaults fill the rest
1170
+ defineGame (core) the underlying engine-only primitive: assets, world, physics, inventories, input, server, save, time, feed, multiplayer, loop
1171
+ PlayableGame { game, content, loop, GameUI, camera, … } — the runner contract `defineGame` (shell) returns
1172
+ GameContext ctx.scene / ctx.game / ctx.player / ctx.item / ctx.camera / ctx.input + subscribe/version
1173
+ scene.object place, remove, move, rotate, at, setVisual (per-instance ObjectVisual: scale/color/opacity override)
1174
+ scene.entity spawn (anchor/offset), despawn, setPose, update; stats; targeting; effects;
1175
+
1176
+ # jgengine-ui
1177
+
1178
+ Use this skill for the **visual and interaction design of the game interface**: title screens, HUDs, menus, prompts, maps, inventories, dialogue, touch controls, transitions, pause/results states, accessibility, and screenshot critique.
1179
+
1180
+ Do not use this skill as a React, routing, state-management, or hooks reference. The main `jgengine` skill owns routing and points to the engine APIs. When implementation needs `@jgengine/react` hooks or shell APIs, follow the links in the main skill and the compact API appendix in [reference.md](reference.md); keep this skill focused on what the player sees and feels.
1181
+
1182
+ ## Required outcome
1183
+
1184
+ A JGengine game must read as a self-contained game, not a responsive website with a canvas inside it.
1185
+
1186
+ Before shipping UI:
1187
+
1188
+ 1. Give the game a concise UI art direction.
1189
+ 2. Compose explicit desktop/mobile game layouts instead of document flow.
1190
+ 3. Keep persistent HUD information sparse and hierarchical.
1191
+ 4. Adapt touch controls to the genre and reserve their screen zones.
1192
+ 5. Implement authored focus, pressed, selected, disabled, success, failure, and warning states.
1193
+ 6. Add purposeful motion and feedback.
1194
+ 7. Capture screenshots and revise what actually renders.
1195
+
1196
+ ## Ownership boundary
1197
+
1198
+ The main `jgengine` skill owns intake, engine architecture, API routing, hooks, commands, state, and verification routing. This skill owns presentation quality.
1199
+
1200
+ Read [reference.md](reference.md) when building or reviewing a game interface. It contains the implementation quality bar, layout rules, art-direction template, touch-control requirements, acceptance criteria, and the compact existing React API surface.
1201
+
1202
+ ## Non-negotiable defaults
1203
+
1204
+ - Active play owns the viewport; no marketing header, page title bar, document scrolling, or website container.
1205
+ - Screen placement belongs in the game's `ui/GameUI.tsx` composition layer.
1206
+ - Persistent gameplay information is frameless unless a physical/diegetic frame is part of the game's art direction.
1207
+ - Instructions are contextual and temporary, not permanent keyboard grids.
1208
+ - Mobile controls share input mechanics but not one universal visual skin.
1209
+ - Themes change geometry, composition, typography roles, icons, motion, materials, sound, and density—not only colors.
1210
+ - Ordinary rounded cards, pill buttons, generic dark modals, and dashboard grids are fallback failures, not defaults.
1211
+
1212
+ ## Preview states ship with the UI
1213
+
1214
+ Every game ships `src/preview.tsx`: a static default frame (default export, used by the website card) plus a `states` named export (`GamePreviewStates` from `@jgengine/react/preview`) keying named UI states — `stage_1`, `game_over`, `boss_intro` — to components. Build state entries from the game's **real UI components** with fixture snapshots (canned props/state), not redrawn lookalikes; that turns every key into a capturable render test. Capture any state instantly with `bun run shoot <game> --preview <stateKey>` — no sim, no three.js, no hang risk — and use it as the screenshot-critique loop for HUD/menu/overlay work before any full-shell `--mode ui`/`play` glance.
1215
+
1216
+ ## Rejection test
1217
+
1218
+ Reject and revise the UI when it could be mistaken for a SaaS dashboard, landing page, admin panel, documentation page, or generic emulator overlay.
1219
+
1220
+ # JGengine UI — game presentation reference
1221
+
1222
+ This reference defines the required visual and interaction quality for JGengine games. The main `jgengine` skill owns engine architecture, hooks, input commands, and routing. This document owns what the interface looks like, how it is composed, how it responds, and how it is verified.
1223
+
1224
+ ## The rule
1225
+
1226
+ A game must visually own its viewport. It must not resemble a dashboard, landing page, documentation page, or ordinary responsive web app.
1227
+
1228
+ HTML and React are valid implementation tools. Website visual grammar is not the default.
1229
+
1230
+ ## 1. Start with a concise UI art direction
1231
+
1232
+ Before implementing screens, write this short block:
1233
+
1234
+ ```md
1235
+ UI ART DIRECTION
1236
+
1237
+ Player fantasy:
1238
+ Emotional tone:
1239
+ Shape language:
1240
+ Material language:
1241
+ Typography roles: display / body / numerical / labels
1242
+ Motion language:
1243
+ Icon language:
1244
+ Sound language:
1245
+ Information hierarchy:
1246
+ Forbidden patterns:
1247
+ ```
1248
+
1249
+ Keep it practical. It should directly influence layout, silhouettes, controls, timing, and materials.
1250
+
1251
+ Example forbidden patterns:
1252
+
1253
+ - generic rounded dashboard cards
1254
+ - pill buttons
1255
+ - long centered paragraphs during play
1256
+ - ordinary two-column form layouts
1257
+ - persistent keyboard-instruction grids
1258
+ - multiple equally weighted bordered panels
1259
+ - generic translucent mobile circles
1260
+ - large website-style modals
1261
+ - document-flow wrapping used as HUD layout
1262
+
1263
+ A theme is not complete when only colors and fonts change. It must also affect composition, geometry, spacing rhythm, borders, icons, animation, sound, information density, terminology, button construction, and touch controls.
1264
+
1265
+ ## 2. Screen inventory and hierarchy
1266
+
1267
+ Identify the screens the game actually needs:
1268
+
1269
+ - boot/loading
1270
+ - title or attract screen
1271
+ - mode selection
1272
+ - onboarding/tutorial
1273
+ - gameplay HUD
1274
+ - pause
1275
+ - settings
1276
+ - map/inventory/dialogue where relevant
1277
+ - victory/results
1278
+ - failure/retry
1279
+
1280
+ For each screen, define:
1281
+
1282
+ - the player’s primary question
1283
+ - the primary action
1284
+ - the most important information
1285
+ - what can be hidden
1286
+ - what belongs in-world instead of in the HUD
1287
+
1288
+ ### HUD tiers
1289
+
1290
+ **Tier 1 — immediate action and survival**
1291
+ Health, timer, current target, ammo, danger, capture state.
1292
+
1293
+ **Tier 2 — short-term decisions**
1294
+ Objective progress, route progress, cooldowns, combo, pursuit distance.
1295
+
1296
+ **Tier 3 — reference information**
1297
+ Full map, inventory, controls, schedule, mission details, lore.
1298
+
1299
+ Tier 1 is immediately readable. Tier 2 is quieter. Tier 3 is usually hidden until requested.
1300
+
1301
+ Do not style every datum as an equally important bordered box.
1302
+
1303
+ ## 3. Full-viewport game composition
1304
+
1305
+ The active game should behave like an application mode:
1306
+
1307
+ - own the full viewport
1308
+ - avoid document scrolling
1309
+ - avoid site navigation and marketing chrome during play
1310
+ - respect safe-area insets
1311
+ - keep exit/settings/fullscreen controls minimal
1312
+ - separate world, HUD, controls, screens, and system overlays
1313
+
1314
+ Recommended layer contract:
1315
+
1316
+ ```tsx
1317
+ <GamePlayer>
1318
+ <WorldLayer />
1319
+ <HudLayer />
1320
+ <ControlLayer />
1321
+ <ScreenLayer />
1322
+ <SystemLayer />
1323
+ </GamePlayer>
1324
+ ```
1325
+
1326
+ - `WorldLayer`: game renderer
1327
+ - `HudLayer`: non-blocking gameplay information
1328
+ - `ControlLayer`: touch/input surfaces
1329
+ - `ScreenLayer`: title, pause, settings, tutorial, victory, failure, transitions
1330
+ - `SystemLayer`: exit, fullscreen, engine settings, devtools
1331
+
1332
+ Do not place unrelated interface pieces into one ordinary DOM flow.
1333
+
1334
+ ## 4. Explicit game layout modes
1335
+
1336
+ Do not rely on generic responsive wrapping. Compose explicit modes such as:
1337
+
1338
+ - desktop-wide
1339
+ - desktop-compact
1340
+ - mobile-landscape
1341
+ - mobile-portrait
1342
+
1343
+ A mobile layout is not a shrunken desktop HUD.
1344
+
1345
+ On mobile:
1346
+
1347
+ - reserve thumb-control zones
1348
+ - keep critical HUD out of those zones
1349
+ - hide keyboard legends
1350
+ - reduce persistent information
1351
+ - move Tier 3 information behind contextual panels
1352
+ - respect browser and device safe areas
1353
+ - support portrait only when intentionally designed
1354
+ - otherwise show a polished rotate-device state
1355
+
1356
+ All viewport anchoring should live in the game’s top-level UI composition file. Child components own their internal layout, not their screen position.
1357
+
1358
+ ### Design-resolution fit (`platforms` + `hudFit`)
1359
+
1360
+ Design-resolution fit is on by default for every game: each `HudCanvas` auto-scales from `hudFit.designSize` (default 1600×900) down to the live viewport, clamped by `hudFit.minScale`/`maxScale` (default 0.4–1), so the authored layout shrinks instead of overflowing a phone. No declaration needed. `hudFit.mobile` overrides the fit on compact displays only — tune the phone presentation there instead of hand-rolling media queries. The player's Graphics → UI scale setting multiplies the computed scale on every platform. Declaring `platforms: ["web"]` (without `"mobile"`) opts a desktop-only game out; its compact displays keep the legacy fixed 0.85 zoom.
1361
+
1362
+ **Overflow is an error, not a style note.** `HudCanvas` measures every `HudPanel` against the viewport at runtime; offenders land in a `data-hud-overflow` attribute (and a console warning), and `bun run shoot <game> --device mobile` (or `both`) exits non-zero naming the escaping panels. A game is not mobile-done while shoot reports HUD OVERFLOW.
1363
+
1364
+ ## 5. Change the visual grammar
1365
+
1366
+ Avoid making every element the same rounded translucent rectangle.
1367
+
1368
+ Use genre-appropriate structures:
1369
+
1370
+ - clipped corners
1371
+ - irregular silhouettes
1372
+ - image-backed frames
1373
+ - mechanical plates
1374
+ - radial interfaces
1375
+ - ribbons and tabs
1376
+ - gauges and meters
1377
+ - emblems and decorative corners
1378
+ - notches and edge anchors
1379
+ - diegetic objects
1380
+ - world-space prompts
1381
+ - asymmetrical compositions
1382
+ - masks, textures, layered borders, and strong focal elements
1383
+
1384
+ Practical rule: no more than roughly 20% of a normal gameplay screen should resemble an ordinary web card or modal.
1385
+
1386
+ Every persistent panel must justify why it exists, remains visible, has that shape, and occupies that position.
1387
+
1388
+ ## 6. Game UI primitives
1389
+
1390
+ Prefer small headless or lightly styled primitives over a giant universal design system. Useful concepts include:
1391
+
1392
+ - `HudAnchor`
1393
+ - `StatReadout`
1394
+ - `Meter`
1395
+ - `ObjectiveTracker`
1396
+ - `ActionPrompt`
1397
+ - `Reticle`
1398
+ - `MinimapFrame`
1399
+ - `DialoguePlate`
1400
+ - `Countdown`
1401
+ - `BossBar`
1402
+ - `ItemPickup`
1403
+ - `DamageIndicator`
1404
+ - `PauseScreen`
1405
+ - `ResultsScreen`
1406
+ - `VirtualControlZone`
1407
+ - `ScreenTransition`
1408
+
1409
+ A primitive should expose game-oriented choices such as shape, material, urgency, placement, hierarchy, entry motion, icon treatment, compactness, and diegetic-versus-overlay presentation.
1410
+
1411
+ Do not create a primitive whose only value is wrapping a `div` with border radius.
1412
+
1413
+ ## 7. Complete interaction states
1414
+
1415
+ Every interactive element needs intentional states:
1416
+
1417
+ - rest
1418
+ - hover where applicable
1419
+ - keyboard/controller focus
1420
+ - pressed
1421
+ - selected
1422
+ - disabled
1423
+ - success
1424
+ - failure
1425
+ - warning
1426
+
1427
+ Do not communicate all states with background-color changes alone. Use appropriate combinations of:
1428
+
1429
+ - scale compression
1430
+ - position shift
1431
+ - edge or glow response
1432
+ - mask movement
1433
+ - icon movement
1434
+ - text response
1435
+ - brief particles
1436
+ - sound
1437
+ - haptics when supported
1438
+ - controlled shake only when appropriate
1439
+
1440
+ Focus must look authored while remaining accessible. Menus should support keyboard/controller-style focus navigation when practical.
1441
+
1442
+ ## Settings menu
1443
+
1444
+ **Settings menu (themed, four layouts, no forced chrome).** The engine builds the whole menu for free — Sound (master + per-bus volume), Graphics (quality/dpr + shadows), Gameplay (FOV slider, default 40–120), Controls (per-action key rebinding, inline click-to-rebind, persisted) — from the game's `audio.buses` and `input` map. What it does **not** do is bolt a fixed gear onto every game: **there is no auto trigger.** You place the entry yourself so it lives *inline with your game's own UI*, never a stray corner overlay. Drop `<SettingsTrigger className=…>` (from `@jgengine/react`) anywhere in your HUD or menu — headless button, `className` for skin/placement, optional `children` to replace the default gear glyph, renders nothing when there's nothing to show. Or call `useSettings().open()` from your own control. Tune the menu via `defineGame({ settings })` (`GameSettingsConfig` from `@jgengine/core/settings/settingsModel`):
1445
+
1446
+ - `variant: "panel" | "sheet" | "sidebar" | "fullscreen"` — the layout + skin (default `panel`; `sheet` is the mobile bottom-sheet). All four are fixed-size (no shrink-to-content jitter) and read the game's `--jg-*` theme tokens, falling back to a neutral dark skin.
1447
+ - `actions: SettingsActionDef[]` — game-state actions (Restart, Quit to menu, …). They become the **first "Game" tab, shown before anything else** — the home for buttons that used to float over the HUD. Each: `{ id, label, kind?: "default"|"danger", description?, run(ctx) }`; the menu closes right after `run`.
1448
+ - `hideBindings: string[]` — input actions to drop from the rebindable Controls list. A game-state key like `restart` belongs in `actions`, not the rebind grid — hide it here so it stops showing up as a "rebindable" control.
1449
+ - `surface: "quick"` — additionally mount compact on-screen volume/graphics buttons. Omit for none. `settings: false` — off entirely.
1450
+ - `extra: GameSettingDef[]` — append rows to any category, built-in *or a brand-new one* named by `category` (any string). Each row: `{ id, label, category, kind: "slider"|"toggle"|"select", default, min?, max?, step?, options?, onChange?(value, ctx) }`.
1451
+ - `categories: SettingCategoryDef[]` — declare custom category tabs, or relabel/reorder built-ins (`{ id, label, order? }`).
1452
+ - `hide: SettingCategory[]` — drop built-in categories.
1453
+
1454
+ **Game-state controls go in `actions`, never a floating button.** Restart/quit/new-game buttons stapled to the bottom of the HUD are the anti-pattern — declare them as `actions` (first Game tab) and place a `<SettingsTrigger>` inline. A contextual button on a win/lose *results* card is fine; a persistent game-state button pinned over live play is not.
1455
+
1456
+ **Present it any way you want.** `useSettings()` (`@jgengine/react`) returns the live controller — `{ categories, actions, variant, surface, isOpen, open, close, setOpen }` — so a game can drive its own pause-menu button, or render `categories`/`actions` (rows carry `value`/`set`/bounds, keybinds carry `rebind`/`reset`) entirely inside its own HUD. `useHasSettings()` gates a custom entry; `useSetting(id, fallback)` reads/writes one value. Set a slider's `min`/`max` explicitly — an omitted range collapses the thumb to 0/1.
1457
+
1458
+ ## 8. Motion and game feel
1459
+
1460
+ Add purposeful motion for:
1461
+
1462
+ - screen entry and exit
1463
+ - confirm and cancel
1464
+ - warnings
1465
+ - score increases
1466
+ - objective updates
1467
+ - damage
1468
+ - victory and failure
1469
+ - countdowns
1470
+ - pause
1471
+ - item pickup
1472
+
1473
+ Motion should be brief, readable, interruptible when necessary, coordinated, consistent with the game’s art direction, and respectful of reduced-motion settings.
1474
+
1475
+ Do not animate everything constantly. Motion communicates hierarchy, cause and effect, urgency, and state changes.
1476
+
1477
+ ## 9. Mobile controls are genre-authored
1478
+
1479
+ Shared input mechanics may remain shared. Their visual treatment and arrangement must match the game.
1480
+
1481
+ Examples:
1482
+
1483
+ **Driving**
1484
+ Steering region or wheel, accelerator, brake, handbrake, optional camera/map control.
1485
+
1486
+ **Stealth**
1487
+ Movement zone, sneak/crouch hold, contextual interaction, temporary map/schedule control.
1488
+
1489
+ **Shooter**
1490
+ Movement zone, aim region, fire/action cluster, weapon or ability controls.
1491
+
1492
+ **Puzzle/arcade**
1493
+ Direct drag, tap, swipe, paddle region, or discrete directions. Do not add a joystick without a gameplay reason.
1494
+
1495
+ Requirements:
1496
+
1497
+ - never cover critical HUD information
1498
+ - use the game’s shape and material language
1499
+ - fade training labels after learning
1500
+ - consider thumb reach
1501
+ - preserve accessible target sizes
1502
+ - visually respond to activation
1503
+ - support optional scaling where appropriate
1504
+
1505
+ Do not use one generic translucent controller across all games.
1506
+
1507
+ ## 10. Progressive instruction
1508
+
1509
+ Do not leave large control grids visible during gameplay.
1510
+
1511
+ Prefer:
1512
+
1513
+ - contextual prompts
1514
+ - brief onboarding
1515
+ - first-use hints
1516
+ - a controls screen
1517
+ - pause-menu reference
1518
+ - icons attached to actions
1519
+ - progressive disclosure
1520
+
1521
+ Desktop keyboard legends must not appear on touch devices. Prompts should appear near the relevant action, object, or HUD region and clear when no longer useful.
1522
+
1523
+ ## 11. Reference directions for flagship games
1524
+
1525
+ ### Clockwork Heist
1526
+
1527
+ Use gentleman-thief mechanical field-kit language: watch geometry, midnight enamel, aged brass, ivory paper, engraved labels, mechanical shutters, and an authored schedule timeline. The timer should feel like a clock. The schedule should be an on-demand pocket-watch or dossier panel. Touch controls should use brass/enamel construction. Restart belongs in pause, not permanently over the world.
1528
+
1529
+ ### Canyon Chase
1530
+
1531
+ Use desert pursuit language: battered dashboard, analog instruments, radio display, route strip, warning lamps, and road-sign typography. Target gap should read as a pursuit gauge. Border progress should resemble an odometer, route strip, or mile marker. Driving controls should feel like steering, throttle, brake, and handbrake—not generic circles.
1532
+
1533
+ ### Brick Breaker
1534
+
1535
+ Use arcade-cabinet language: bezel framing, CRT/vector treatment, arcade numerical readouts, attract mode, launch feedback, and brief level overlays that clear before play. Pause and results should feel like cabinet states, not web dialogs.
1536
+
1537
+ These games must remain structurally distinct, not recolors of one component set.
1538
+
1539
+ ## 12. Accessibility and performance
1540
+
1541
+ Maintain:
1542
+
1543
+ - sufficient contrast
1544
+ - readable text size
1545
+ - keyboard navigation
1546
+ - controller navigation where available
1547
+ - reduced-motion support
1548
+ - visible authored focus
1549
+ - touch target sizing
1550
+ - semantic labels where practical
1551
+ - responsive scaling
1552
+ - reasonable DOM and animation performance
1553
+
1554
+ Use blur, masks, textures, filters, and full-screen effects carefully, especially on mobile.
1555
+
1556
+ ## 13. Screenshot verification is mandatory
1557
+
1558
+ Capture and inspect meaningful states:
1559
+
1560
+ - desktop title screen
1561
+ - desktop gameplay
1562
+ - mobile landscape
1563
+ - mobile portrait where supported
1564
+ - pause
1565
+ - victory or failure
1566
+ - an interaction prompt
1567
+ - touch controls in active use
1568
+
1569
+ Inspect for:
1570
+
1571
+ - overlap and clipping
1572
+ - weak contrast
1573
+ - unreadable scale
1574
+ - excessive cards
1575
+ - website-like composition
1576
+ - broken safe areas
1577
+ - conflicting hierarchy
1578
+ - browser chrome interference
1579
+ - poor thumb reach
1580
+ - keyboard instructions on touch devices
1581
+ - inconsistent art direction
1582
+
1583
+ Revise after inspection. Typechecking is not visual proof.
1584
+
1585
+ ## 14. Rejection criteria
1586
+
1587
+ Require revision when any of these are true:
1588
+
1589
+ - normal site navigation remains visible during active gameplay
1590
+ - the player must scroll the page to use the game
1591
+ - the game is presented inside a normal content card
1592
+ - essential HUD is covered by touch controls
1593
+ - controls overlap each other
1594
+ - keyboard instructions appear on touch devices
1595
+ - large instruction panels remain visible during gameplay
1596
+ - more than three ordinary card-like panels are persistently visible
1597
+ - the main action looks like a standard website button
1598
+ - pause resembles a generic website modal
1599
+ - victory/failure is only text plus restart
1600
+ - restart is permanently visible without a gameplay reason
1601
+ - menu elements lack pressed, focused, selected, or disabled states
1602
+ - UI changes have no transition or feedback
1603
+ - generic virtual controls are used without genre adaptation
1604
+ - the theme only changes colors and fonts
1605
+ - unrelated UI elements have equal visual weight
1606
+ - mobile portrait technically fits but is not intentionally composed
1607
+ - important UI sits beneath safe areas
1608
+ - ordinary document flow determines the HUD layout
1609
+ - generic default styling is used because no art direction was written
1610
+
1611
+ ## 15. Compact implementation API appendix
1612
+
1613
+ Use the main `jgengine` skill for the authoritative engine API routing. The React package exposes `GameProvider`, hooks, and headless primitives from `@jgengine/react` and its documented subpaths. Common hooks include player/game state, entities, stats, inventory, quests, prompts, clocks, markers, fog, and engine stores. The shell provides `GamePlayerShell`, input integration, devtools, and `GameUiPreview`.
1614
+
1615
+ Use these APIs to bind state; do not let API wiring dictate visual composition. Keybind labels should derive from the game’s binding table, and UI actions should dispatch through game commands rather than existing only as click handlers.
1616
+
1617
+ Headless components are not finished design. They are behavior and accessibility seams that the game must art-direct.
1618
+
1619
+ ## Definition of done
1620
+
1621
+ UI work is complete only when:
1622
+
1623
+ - the game owns the viewport
1624
+ - site chrome is absent during active play
1625
+ - no document scrolling is required
1626
+ - HUD and control layers have clear responsibilities
1627
+ - mobile controls do not cover critical content
1628
+ - touch controls match the genre and game identity
1629
+ - title, pause, and results screens feel authored
1630
+ - interaction states and transitions are present
1631
+ - screenshots have been reviewed and revised
1632
+ - the implementation remains accessible and performant
1633
+ - future generated UI is explicitly prevented from falling back to generic website-card styling