@jgengine/github 0.1.0 → 0.2.0-next.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.
- package/CHANGELOG.md +582 -2
- package/package.json +1 -1
- package/skills/ce-handoff/SKILL.md +149 -0
- package/skills/jgengine/SKILL.md +38 -802
- package/skills/jgengine/api.md +213 -84
- package/skills/jgengine/capabilities.md +124 -2
- package/skills/jgengine/recipes/minimal-game.md +91 -0
- package/skills/jgengine/reference-cartridge.md +0 -72
- package/skills/jgengine/reference-orphans.md +0 -9
- package/skills/jgengine/reference-systems.md +0 -60
package/skills/jgengine/SKILL.md
CHANGED
|
@@ -1,823 +1,59 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: jgengine
|
|
3
|
-
description:
|
|
3
|
+
description: Route game work to the smallest useful JGengine guidance set.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
|
-
# JGengine
|
|
6
|
+
# JGengine intake and router
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
Read the JGengine README for package truth, commands, layering, and license — the repo-root [`README.md`](../../../README.md) in the monorepo, or [jgengine.com](https://jgengine.com) from a scaffolded consumer project (where the relative link does not resolve). This skill decides what to load; it is not an engine manual.
|
|
9
9
|
|
|
10
|
-
##
|
|
10
|
+
## 1. Establish the target
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
Treat the pitch as a unique composition of needs, not a genre to fill in — never reach for a genre kit, preset, archetype, or class template ("default sports car", "default RPG", "default FPS") in the SDK or skills (see [AGENTS.md](../../../AGENTS.md)). Use `game-design` to turn the pitch into a testable player promise, verbs, loops, progression, failure, and completion scenario. Use `level-design` when play depends on authored spaces, routes, encounters, exploration, or spatial pacing. Capture only decisions that change architecture:
|
|
13
13
|
|
|
14
|
-
-
|
|
15
|
-
-
|
|
16
|
-
-
|
|
14
|
+
- player point of view and controls
|
|
15
|
+
- world shape and authored content
|
|
16
|
+
- core loop, interaction, combat, and progression
|
|
17
|
+
- solo, local, hosted, or persistent multiplayer
|
|
18
|
+
- HUD/menu states and **custom** UI art direction (compose shipped building blocks + HudTheme; no unskinned stock face)
|
|
19
|
+
- one observable completion scenario
|
|
17
20
|
|
|
18
|
-
|
|
21
|
+
For a new in-repo game, scaffold with `bun run new:game "<id-or-title>"` (thin script alias for `jgengine create`, auto-detects the in-repo variant). Outside this monorepo, start with `npx jgengine create`; never copy `Games/*`.
|
|
19
22
|
|
|
20
|
-
|
|
23
|
+
For an existing game asked to pick up a new engine release ("jgengine published a new version, grab it"), run `npx jgengine upgrade` in the project first: it diffs installed `@jgengine/*` versions against the latest release and prints every Migrate step and Adopt-worthy addition in between (`--json` for structured output). Bump, migrate oldest-first, then work the Adopt lists instead of reconstructing the changelog by hand.
|
|
21
24
|
|
|
22
|
-
|
|
23
|
-
2. **World:** custom 3D wasteland with three settlements
|
|
24
|
-
3. **Core loop:** get quests by talking to people → defeat enemies → return to redeem quests
|
|
25
|
-
4. **Interaction:** collect ground items by walking over them; interact with people and doors at close range
|
|
26
|
-
5. **Combat:** ranged weapons, damage, death, loot
|
|
27
|
-
6. **Progression:** inventory, currency, quest rewards, upgrades
|
|
28
|
-
7. **Players:** single-player, or name the topology, synchronized systems, and authority — presence-only (`wsPresence()`/`convexPresence()`, each client ticks its own world) or host-authoritative shared sim (`authority: "server"` + a host, see `examples/HOSTED.md`)
|
|
29
|
-
8. **UI:** visible controls, objective tracker, health, inventory feedback
|
|
30
|
-
9. **Art direction:** one aesthetic, palette, asset family, and UI voice
|
|
31
|
-
10. **Done looks like:** one observable end-to-end play scenario
|
|
25
|
+
## 2. Select domains
|
|
32
26
|
|
|
33
|
-
|
|
27
|
+
Load only rows the target needs. Do not preload every domain.
|
|
34
28
|
|
|
35
|
-
|
|
29
|
+
| Need | Skill | Owner |
|
|
30
|
+
| --- | --- | --- |
|
|
31
|
+
| player promise, pillars, verbs, loops, economy, progression, balance | `game-design` | experience and rule intent |
|
|
32
|
+
| metrics, topology, encounters, navigation, spatial pacing | `level-design` | playable space intent |
|
|
33
|
+
| scene placement, terrain painting, paths, asset authoring | `jgengine-editor` | editor document and authoring tools |
|
|
34
|
+
| runtime world, movement, input, interaction, AI, navigation, audio | `jgengine-world` | spatial simulation and world runtime |
|
|
35
|
+
| game state, systems, inventory, crafting, quests, economy, turns | `jgengine-gameplay` | non-combat rules and state |
|
|
36
|
+
| targeting, stats, damage, effects, abilities, projectiles, loot | `jgengine-combat` | combat resolution |
|
|
37
|
+
| HUD, menus, layout, accessibility, touch presentation | `jgengine-ui` | player-facing interface |
|
|
38
|
+
| models, sprites, materials, audio files, source licensing | `jgengine-assets` | asset discovery and catalogs |
|
|
39
|
+
| authority, transport, replication, sessions, host persistence | `jgengine-multiplayer` | network topology and persistence adapters |
|
|
36
40
|
|
|
37
|
-
|
|
41
|
+
World content routes editor-first: any request that adds, moves, restyles, or removes something visible in the world — however phrased ("design this world", "place the enemies", "make it look better") — starts in `jgengine-editor`; the other domains consume the authored document. Scenes normally require both `jgengine-editor` for authoring and `jgengine-world` for runtime consumption. Combat and multiplayer are opt-in, not default intake.
|
|
38
42
|
|
|
39
|
-
|
|
40
|
-
| --- | --- |
|
|
41
|
-
| Terrain, scenes, camera, movement, physics, maps, sensors, seeded/environment generation, grids, buildings | `jgengine-world` |
|
|
42
|
-
| Damage, effects, weapons, targeting, projectiles, loot, death | `jgengine-combat` |
|
|
43
|
-
| Items, quests, dialogue, economy, crafting, objectives, turns, social systems | `jgengine-gameplay` |
|
|
44
|
-
| Networking adapters, authority, rooms/topology, persistence/backend seams | `jgengine-multiplayer` |
|
|
45
|
-
| React HUD, shell affordances, controls, feedback, accessibility | `jgengine-ui` |
|
|
46
|
-
| Models, sprites, textures, audio, catalogs, attribution | `jgengine-assets` |
|
|
47
|
-
| Proof and screenshots | `jgengine-verify` after implementation |
|
|
43
|
+
## 3. Discover before designing
|
|
48
44
|
|
|
49
|
-
|
|
45
|
+
Within each selected domain:
|
|
50
46
|
|
|
51
|
-
|
|
47
|
+
0. Fastest start for a common composition: `npx jgengine recipe <name>` prints a vetted, SDK-typechecked snippet (imports + wired code) for `combat-loop`, `boss-telegraph`, `loot`, `quest`, `coop-presence`, `third-person-camera`; `npx jgengine recipe` lists them. Copy that instead of reconning per-file.
|
|
48
|
+
1. Search `capabilities.md` by intent; it maps needs to imports. Outside the monorepo (or before a domain skill is even loaded), `npx jgengine find <intent>` greps every shipped capability index at once and prints the primitive + import — reach for it the moment you're tempted to hand-roll a HUD window, inventory grid, paperdoll, hotkey listener, minimap, stat bar, or character motion. If you're writing a `z-index`, a `keydown` for a panel, a `<div>` inventory, or a limb bob, a shipped drop-in almost certainly exists (`usePanels`/`PanelHost`, `InventoryGrid`, `CharacterSheet`/`Paperdoll`, `PartMotionRig`, `EntityPreview`); games own the *skin*, not the re-derivation.
|
|
49
|
+
2. Open `api.md` only when exact signatures or export inventory are needed.
|
|
50
|
+
3. Open the linked reference only for a deeper recipe or trap.
|
|
51
|
+
4. For how several primitives wire into a running loop, read the domain's `recipes/` — connected, genre-free walkthroughs organized by composition seam; this skill's own [recipes/minimal-game.md](recipes/minimal-game.md) is the default whole-game walkthrough. Prefer a recipe over reading a game's source; the games under `Games/*` are not templates or references, and a hybrid game is just a different composition of the same primitives.
|
|
52
52
|
|
|
53
|
-
|
|
53
|
+
If no capability fits, identify the upstream package seam before writing game-local code. In this repository, implement a reusable primitive with its first adopter; if editor-owned content cannot be expressed, file the editor gap first.
|
|
54
54
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
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).
|
|
58
|
-
|
|
59
|
-
---
|
|
60
|
-
|
|
61
|
-
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`.
|
|
62
|
-
|
|
63
|
-
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.
|
|
64
|
-
|
|
65
|
-
## Packages
|
|
66
|
-
|
|
67
|
-
All published on npm, source at [github.com/Noisemaker111/jgengine](https://github.com/Noisemaker111/jgengine) (AGPL-3.0):
|
|
68
|
-
|
|
69
|
-
| Package | Role | May import |
|
|
70
|
-
|---------|------|------------|
|
|
71
|
-
| `@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 |
|
|
72
|
-
| `@jgengine/react` | `GameProvider`, hooks, headless UI primitives | react + core |
|
|
73
|
-
| `@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 |
|
|
74
|
-
| `@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 |
|
|
75
|
-
| `@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 |
|
|
76
|
-
| `@jgengine/sql` | `HostPersistence` on Postgres (structural pool, no hard `pg` dep) | core |
|
|
77
|
-
| `@jgengine/convex` | The Convex **adapter** behind the `GameBackend` seam | react + convex + core |
|
|
78
|
-
|
|
79
|
-
**Prefer the curated domain barrel** — a stable entrypoint that re-exports the domain's public surface, so you don't guess deep file paths: `@jgengine/core/{world,combat,gameplay,multiplayer,ui,procedural}` (e.g. `import { defineGame } from "@jgengine/core/gameplay"`). Not in the barrel? Fall back to the deep path `@jgengine/core/<domain>/<file>` (e.g. `@jgengine/core/runtime/gameContext`). Sibling packages (`@jgengine/{ws,node,sql,convex,react,assets,editor}`) already export from their package root. Maintainer: barrels regenerate with `bun run gen:barrels`; after changing core exports, run `bun run gen:skill-api` on a clean checkout.
|
|
80
|
-
|
|
81
|
-
## Hit a snag? File an issue
|
|
82
|
-
|
|
83
|
-
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.
|
|
84
|
-
|
|
85
|
-
## Upgrading? Read the changelog
|
|
86
|
-
|
|
87
|
-
Lockstep SDK packages (`@jgengine/{core,react,ws,node,sql,convex,shell,editor,assets}`) share one version line; CLI `jgengine` and `@jgengine/github` may lag. 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. Same data as typed values: `import { VERSION, CHANGELOG } from "@jgengine/core/meta/changelog"`.
|
|
88
|
-
|
|
89
|
-
## Concept → Type Reference
|
|
90
|
-
|
|
91
|
-
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>`.
|
|
92
|
-
|
|
93
|
-
| Concept | Import path (`@jgengine/core/…`) | Export(s) |
|
|
94
|
-
|---------|----------------------------------|-----------|
|
|
95
|
-
| Game boot | `game/defineGame` | `defineGame`, `GameDefinition`, `GameLoop`, `InventoryDeclaration`, `PhysicsConfig`, `GameServerConfig`, `TimeConfig` — use `ctx.scene.entity` (never deprecated `GameDefinition.scene`) |
|
|
96
|
-
| Composable systems | `game/defineSystem`, `game/systemSchedule`, `game/systemRuntime` | `defineSystem`, `SystemDefinition`, `SystemTick`, `compileSystemSchedule`, `composeGameLoop`, `DEFAULT_FIXED_STAGES`, `DEFAULT_FRAME_STAGES` — `defineGame({ systems })`; [reference-systems.md](reference-systems.md) |
|
|
97
|
-
| Entity meta | `scene/entityStore` | `entityMetaOf(entity, isMeta)` — type-guard narrow of `meta` (prefer over `as T`) |
|
|
98
|
-
| Simulation clock | `time/simClock` | `createSimClock`, `SimClock`, `TimeConfig`, `ClockSnapshot`, `CalendarTime` |
|
|
99
|
-
| Runner contract | `game/playableGame` | `PlayableGame`, `GameCameraConfig`, `CameraRigKind`, `CameraProjection`, `SideScrollCameraConfig`, `TopDownCameraConfig`, `RtsCameraConfig`, `ShoulderCameraConfig`, `LockOnCameraConfig`, `ChaseCameraConfig`, `ObserverCameraConfig`, `CameraShakeConfig`, `CinematicCameraConfig`, `CameraKeyframe`, `EntitySpriteConfig` |
|
|
100
|
-
| Runtime ctx | `runtime/gameContext` | `createGameContext`, `GameContext`, `GameContextContent`, `GameContextItemEntry`, `GameContextEntityEntry`, `GameContextObjectEntry`, `CatalogEntityRole` |
|
|
101
|
-
| 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` |
|
|
102
|
-
| Typed store handle | `store/defineStore` | `defineStore<T>(key, initial)` → `StoreHandle<T>` (`read`/`peek`/`write`/`update`/`clear`); pair with `useStore` (`@jgengine/react/store`). The cast-free default for a single fixed slot of run state |
|
|
103
|
-
| Typed keyed-store handle | `store/defineKeyedStore` | `defineKeyedStore<T>(keyFor, initial)` → `KeyedStoreHandle<T>` (`read`/`peek`/`write`/`update`/`clear`, all `(ctx, id, ...)`); pair with `useKeyedStore` (`@jgengine/react/store`). The `defineStore` sibling for a per-owner keyed family (per-user, per-instance) |
|
|
104
|
-
| Reactive keyed store | `store/observableKeyedStore` | `createObservableKeyedStore`, `ObservableKeyedStore` — backs `ctx.game.store`, sits under `defineStore`/`defineKeyedStore` |
|
|
105
|
-
| Scene instance role | `scene/entityStore` | `EntityRole`, `SceneEntity`, `SpawnOptions`, `EntityPose` |
|
|
106
|
-
| Sim → scene pose bind | `scene/bodyBind` | `createBodyBind`, `BodyBind`, `BodySnapshot`, `BodyBindDeps` — backs `ctx.scene.entity.bind` |
|
|
107
|
-
| Object spatial queries | `scene/objectQuery` | `raycastObjects`, `raycastObjectsAll`, `ObjectRaycastInput`, `ObjectRaycastHit` — backs `ctx.scene.object.raycast`/`raycastAll` |
|
|
108
|
-
| Runtime paint layer | `scene/paintLayer` | `createPaintLayer`, `PaintLayer`, `PaintStroke` — backs `ctx.scene.entity.paint` |
|
|
109
|
-
| Possession | `scene/possession` | `createPossession`, `Possession`, `PossessionDeps`, `PossessionSwappedEvent` |
|
|
110
|
-
| Form / shapeshift | `scene/form` | `createForms`, `Forms`, `FormDef`, `FormsDeps`, `FormChangedEvent` |
|
|
111
|
-
| Multiplayer adapters | `runtime/adapter`, `runtime/worldProjection` | `offline`, `ws`, `convex`, `socketIo`, `p2p`, `lan`, `fly`, `servers`, `MultiplayerTopology`, `ServersPoolConfig`, `resolveAuthority`, `isPresenceOnly`, `isServerAuthoritative`, `isOffline`, `visibleEntityIds`, `projectEntitiesForViewer`, `projectPerUserForViewer`, `projectByVisibleIds`, `policyProjectsViewers` — unset/`"client"` authority is presence-only; `"server"` is host-authoritative |
|
|
112
|
-
| Loot | `game/lootTable` | `lootTable`, `LootTableDef`, `LootEntry`, `Drop` |
|
|
113
|
-
| 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` |
|
|
114
|
-
| Loot filter | `game/lootFilter` | `lootFilter`, `evaluateLootFilter`, `LootFilterRule`, `LootFilterCondition`, `LootFilterItem`, `LootFilterOverride` |
|
|
115
|
-
| Loadout | `game/loadout` | `LoadoutDef`, `LoadoutItemEntry`, `Loadouts` |
|
|
116
|
-
| Cosmetic loadout | `game/cosmetics` | `createCosmetics`, `Cosmetics`, `CosmeticLoadoutDef` |
|
|
117
|
-
| Quest | `game/quest` | `QuestDef`, `QuestRewards`, `QuestObjective`, `QuestJournal` |
|
|
118
|
-
| World features | `world/features` | `WorldFeature`, `biomes`, `voxel`, `plots`, `tilemap`, `flat`, `environment`, `terrain`, `rain`, `snow`, `grass`, `ocean`, `building`, `road` |
|
|
119
|
-
| Street layout | `world/streets` | `laneCenters`, `sidewalkPaths`, `furnitureSpots`, `parkingSpots`, `sidewalkPoint`, `offsetPath`, `sidewalkWidthOf`, `StreetLane`, `FurnitureSpot`, `ParkingSpot` — where things belong on a `road()`: lanes for traffic, sidewalks for peds, curb anchors for furniture |
|
|
120
|
-
| Road ribbons | `world/roads` | `buildRoadRibbon`, `dashSegments`, `nearestOnPath`, `isOnRoad`, `pathLength`, `RoadRibbon`, `RoadSample`, `RoadPoint` — geometry + queries behind the `road()` environment feature |
|
|
121
|
-
| 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 |
|
|
122
|
-
| Terrain field | `world/terrain` | `TerrainField`, `noiseField`, `resolveTerrainField`, `rollingField`, `fractalNoise`, `valueNoise`, `withNormal`, `arenaField`, `flatField`, `resolveGroundStep`, `snapToGround`, `snapEntityToGround`, `resolveTerrainPalette`, `TERRAIN_MATERIAL_PALETTES` |
|
|
123
|
-
| Seeded RNG | `random/rng` | `seededRng`, `seededStreams` |
|
|
124
|
-
| 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 |
|
|
125
|
-
| Name generator | `random/nameGen` | `createNameGenerator`, `pickFrom`, `fillTemplate`, `NameGenerator`, `NameGeneratorOptions`, `SyllableBank` |
|
|
126
|
-
| Regions | `world/regions` | `createRegionField`, `isRegionField`, `RegionDef`, `RegionField`, `RegionSample` |
|
|
127
|
-
| Wind field | `world/wind` | `windField`, `WindField`, `WindFieldConfig`, `WindVector` |
|
|
128
|
-
| Water surface | `world/water` | `waterSurface`, `waterSurfaceFromDescriptor`, `synthesizeWaves`, `WaterSurface`, `GerstnerWave` |
|
|
129
|
-
| Scatter | `world/scatter` | `scatter`, `scatterAabb`, `ScatterConfig`, `ScatterPoint` |
|
|
130
|
-
| Content scatter | `world/scatterItems` | `scatterItems`, `pickWeighted`, `ScatterLayer`, `ScatterInstance` |
|
|
131
|
-
| Building generator | `world/buildings` | `generateBuilding`, `generateBuildingDistrict`, `createBuildingGrid`, `GeneratedBuilding` |
|
|
132
|
-
| Building index | `world/buildingIndex` | `buildingIndex`, `BuildingIndex`, `BuildingHit` |
|
|
133
|
-
| Scene summary | `world/environmentSummary` | `summarizeEnvironment`, `resolveStructureBuildings`, `EnvironmentSummary` |
|
|
134
|
-
| Map markers | `world/markers` | `createMarkerSet`, `MarkerSet`, `MapMarker`, `MarkerInput`, `MarkerKindStyle`, `DEFAULT_MARKER_KINDS`, `markerKindStyle` |
|
|
135
|
-
| Fog of war | `world/fog` | `createFogField`, `FogField`, `FogConfig`, `FogBounds`, `FogCells` |
|
|
136
|
-
| Minimap math | `world/minimap` | `projectToMinimap`, `clampToMinimapEdge`, `compassBearing`, `headingToBearing`, `bearingToCardinal`, `relativeBearing`, `MinimapView` |
|
|
137
|
-
| Ping | `game/ping` | `createPingSystem`, `classifyPing`, `PingSystem`, `PingPayload`, `PingCategory`, `PingCategoryDef`, `DEFAULT_PING_CATEGORIES`, `PING_FEED_ACTION` |
|
|
138
|
-
| Proximity prompt | `interaction/proximityPrompt` | `proximityPrompt`, `ProximityPrompt`, `ProximityPromptDisplay`, `keybind`, `gauge`, `label`, `command` |
|
|
139
|
-
| Skill-check minigame | `interaction/skillCheck` | `evaluateSkillCheck`, `skillCheckMarkerPosition`, `skillCheckZoneAt`, `SkillCheckConfig`, `SkillCheckZone`, `SkillCheckResult` |
|
|
140
|
-
| QTE sequencer | `interaction/qte` | `evaluateQteSequence`, `pendingQteStep`, `qteProgress`, `QteStep`, `QteInputEvent`, `QteOutcome` |
|
|
141
|
-
| Item use | `item/use` | `createItemUse`, `ItemUseHandler`, `ItemUseInput`, `ItemUseResult`, `ItemUseRejection` |
|
|
142
|
-
| Durability | `item/durability` | `createDurability`, `wear`, `repairQuote`, `isDisabled`, `createDurabilityTracker`, `DurabilitySpec`, `DurabilityState`, `RepairSpec`, `RepairQuote` |
|
|
143
|
-
| Affix roller | `item/affix` | `createAffixRoller`, `seededRng`, `AffixRoller`, `RollerConfig`, `AffixPool`, `AffixDef`, `RarityTier`, `ItemBaseDef`, `RolledItem`, `RolledAffix` |
|
|
144
|
-
| Modular item | `item/modularItem` | `createModularItem`, `install`, `computeEffectiveStats`, `missingRequiredSlots`, `ModularItemDef`, `MountSlotDef`, `PartDef`, `InstalledPart` |
|
|
145
|
-
| Storage tier | `inventory/storageTier` | `partitionOnDeath`, `createDeliveryQueue`, `insureLost`, `resolveConsolation`, `tierOf`, `StorageTier`, `ContainerSnapshot`, `DeathPartition`, `DeliveryQueue`, `InsurancePolicy`, `ConsolationPolicy` |
|
|
146
|
-
| Contested channel | `session/contestedChannel` | `createContestedChannel`, `ContestedChannel`, `ContestedChannelConfig`, `ContestedEvent`, `ContestedPhase`, `ContestedSnapshot` |
|
|
147
|
-
| Round state | `session/roundState` | `createRoundState`, `lossBonusFor`, `RoundState`, `RoundConfig`, `RoundPhase`, `RoundTeam`, `RoundEvent`, `RoundEconomy`, `RoundSnapshot`, `LossBonusRule` |
|
|
148
|
-
| Shrinking ring | `session/ring` | `createRing`, `ringSampleAt`, `Ring`, `RingConfig`, `RingPhase`, `RingSample`, `RingHit`, `RingPoint` |
|
|
149
|
-
| Extraction session | `session/extraction` | `createRaidSession`, `RaidSession`, `RaidSessionConfig`, `ExtractPoint`, `ExtractionResult`, `DeathResult`, `RaidStatus` |
|
|
150
|
-
| Role assignment | `session/roles` | `assignRoles`, `RoleSpec` |
|
|
151
|
-
| Downed / revive | `combat/downed` | `createDownedState`, `DownedState`, `DownedConfig`, `DownedPhase`, `DownedEntry`, `DownedEvent` |
|
|
152
|
-
| Persistence scopes | `runtime/persistenceScope` | `partitionScopes`, `resetRun`, `mergeScopes`, `clearRunFields`, `applyRunReset`, `planScenarioReset`, `ScopeSchema`, `ScenarioReset`, `PersistenceScope` |
|
|
153
|
-
| Inventory | `inventory/inventoryModel` | `InventoryLayout`, `InventorySet`, `ItemTraits` |
|
|
154
|
-
| Progression | `game/progression` | `curve`, `evalCurve`, `leveling`, `Curve`, `LevelingTrack`, `LevelProgress` |
|
|
155
|
-
| 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 |
|
|
156
|
-
| Inventory slots | `inventory/slotModel` | `createSlots`, `placeAt`, `removeAt`, `moveSlot`, `firstEmpty`, `compactSlots`, `Slot`, `SlotGrid` |
|
|
157
|
-
| Shaped inventory | `inventory/shapedGrid` | `createShapedGrid`, `placeShaped`, `moveShaped`, `removeShaped`, `canPlace`, `rotateFootprint`, `occupiedCells`, `gridAdjacencyQuery`, `cellFromPoint`, `ShapedGrid`, `Footprint`, `Placement`, `Rotation` |
|
|
158
|
-
| Card piles | `cards/cardPile` | `createCardPile`, `createCardPileState`, `draw`, `moveCards`, `shuffleZone`, `pileRng`, `CardPile`, `CardPileState`, `CardPileConfig` |
|
|
159
|
-
| Modifier pipeline | `cards/modifierPipeline` | `createModifierPipeline`, `runPipeline`, `Modifier`, `TraceStep`, `PipelineResult` |
|
|
160
|
-
| Lane board | `board/laneBoard` | `createLaneBoard`, `laneAggregate`, `laneOutcome`, `boardTotals`, `lanesWon`, `LaneBoard`, `LaneRule`, `LaneBoardConfig` |
|
|
161
|
-
| Timeline board | `board/timelineBoard` | `createTimelineBoard`, `tickTimeline`, `TimelineBoard`, `TimelineSlot`, `TimelineFire` |
|
|
162
|
-
| World geometry | `world/geometry` | `footprintAabb`, `aabbOverlap`, `snapToGrid`, `resolveMove`, `Aabb`, `Footprint` |
|
|
163
|
-
| Placement | `world/placement` | `validatePlacement`, `footprintObstacle`, `PlacementRules`, `PlacementResult` |
|
|
164
|
-
| Placement ghost | `world/placementController` | `createPlacementController`, `PlacementController`, `PlacementPreview`, `PlacementCommit`, `SnapMode`, `quarterTurnsToRotationY` |
|
|
165
|
-
| Place asset verb | `world/placeAsset` | `resolvePlaceAsset`, `placeAssetFromCommit`, `toStructureInput`, `toEditorMarker`, `PlaceAssetResult` |
|
|
166
|
-
| Connector sockets | `world/connectors` | `snapToNearest`, `socketsCompatible`, `worldSockets`, `socketWorldPosition`, `ConnectorSocket`, `ConnectorPieceDef`, `PlacedPiece`, `SnapResult` |
|
|
167
|
-
| Structural support | `world/support` | `solveSupport`, `toDebrisBodies`, `SupportPiece`, `SupportLink`, `SupportResult` |
|
|
168
|
-
| Wall/roof authoring | `world/walls` | `createWallDrawTool`, `footprintFromWalls`, `autoRoof`, `wallSegments`, `createSurfacePaint`, `WallDrawTool`, `RoofPlan`, `EnclosedFootprint` |
|
|
169
|
-
| Placed structures | `world/placedStructureStore` | `createPlacedStructureStore`, `PlacedStructure`, `PlacedStructureStore`, `PlacedStructureSnapshot` |
|
|
170
|
-
| Terraform | `world/terraform` | `createEditableTerrain`, `createTerraformBrush`, `brushWeight`, `EditableTerrain`, `TerraformBrush`, `TerraformEdit`, `TerraformMode` |
|
|
171
|
-
| Build permissions | `world/buildPermissions` | `createPlotPermissions`, `createContributionPool`, `PlotPermissions`, `ContributionPool`, `BuildRole`, `ContributionGoal` |
|
|
172
|
-
| Interiors | `world/interiors` | `createInteriors`, `Interior`, `Exterior`, `SpaceRef` |
|
|
173
|
-
| Game clock | `time/gameClock` | `getScaledElapsedMs`, `computeGameDay`, `SECONDS_PER_GAME_DAY` |
|
|
174
|
-
| 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 |
|
|
175
|
-
| Scene behaviors | `scene/behaviors` | `wander`, `patrol`, `promptable`, `talkable`, `player` |
|
|
176
|
-
| Capture check | `scene/captureCheck` | `captureChance`, `rollCapture`, `CaptureCheckInput` |
|
|
177
|
-
| Owned roster | `scene/roster` | `createRoster`, `Roster`, `RosterEntry`, `RosterCaptureOptions` |
|
|
178
|
-
| Economy wallet | `economy/wallet` | `createEmptyWallet`, `balance`, `grant`, `charge`, `canAfford`, `chargeAll` |
|
|
179
|
-
| Player listing marketplace | `economy/listingBook` | `createListingBook`, `ListingBook`, `ListingBookConfig`, `Listing`, `PostListingInput`, `PostListingResult`, `CancelListingResult`, `BuyListingResult`, `BuyListingOutcome`, `CollectionBoxSnapshot` — post/cancel/buy against a shared listing book with a house cut, an expiry sweep, and a per-seller collection box for proceeds/returns |
|
|
180
|
-
| Tech tree | `economy/techTree` | `createTechTree`, `TechTree`, `TechNodeDef`, `canUnlockTech`, `availableTech`, `unlockedRecipes`, `grantTech`, `techPrerequisitesMet` |
|
|
181
|
-
| Recipe graph | `crafting/recipe` | `createRecipeGraph`, `RecipeGraph`, `RecipeDef`, `RecipeItem`, `canCraft`, `craft`, `missingInputs`, `stationSatisfied`, `craftSeconds` |
|
|
182
|
-
| Production building | `crafting/production` | `productionBuilding`, `ProductionBuildingDef`, `createProductionState`, `tickProduction`, `feedProduction`, `drainOutput`, `advanceTransport`, `resolvePowerGrid` |
|
|
183
|
-
| Crop tile / farming | `crafting/crop` | `createCropField`, `CropField`, `CropDef`, `CropTileState`, `tillTile`, `plantCrop`, `waterTile`, `advanceCropDay`, `harvestCrop`, `applyToolToTiles`, `squarePattern`, `diamondPattern`, `createDayTicker` |
|
|
184
|
-
| Skill-check roll | `stats/rollCheck` | `rollCheck`, `CheckInput`, `CheckResult`, `CheckAdvantage` |
|
|
185
|
-
| Input bindings (full) | `input/actionBindings` | `hotbarSlotBindings`, `actionLabel`, `bindingLabel`, `resolveActionCommand`, `bindingMatches`, `createActionStateTracker` |
|
|
186
|
-
| Touch controls | `input/touchScheme` | `deriveTouchScheme`, `touchCode`, `touchActionLabel`, `touchButtonShape`, `withTouchCodes`, `TouchControlsConfig`, `TouchGestureBindings`, `TouchDragBinding`, `TouchButtonSpec`, `TouchButtonShape`, `TouchAnchor`, `TouchLayoutConfig`, `TouchMovementConfig`, `TouchStyle`, `TOUCH_STYLE_OPTIONS`, `TouchScheme`, `TouchJoystick`, `TouchButton` — `shape`/`anchor`/`layout`/`movement.axis`/`style` refine the derived dock; player picks the skin in Settings → Controls |
|
|
187
|
-
| Pointer hit | `input/pointer` | `PointerHit`, `PointerButton`, `aimToPoint`, `moveTargetFromHit`, `groundOf`, `PointerVec3` |
|
|
188
|
-
| Navmesh + A* | `nav/navGrid` | `createNavGrid`, `findPath`, `smoothPath`, `NavGrid`, `NavGridConfig`, `NavPoint`, `FindPathOptions` |
|
|
189
|
-
| Path follow | `nav/pathFollow` | `createPathFollow`, `advancePathFollow`, `pathFromNav`, `PathFollowConfig`, `PathFollowState`, `Waypoint` |
|
|
190
|
-
| 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 |
|
|
191
|
-
| Selection set | `scene/selection` | `createSelectionSet`, `SelectionSet`, `screenRect`, `selectWithinRect`, `rectContainsPoint`, `isMarquee`, `ScreenRect` |
|
|
192
|
-
| Context menu | `interaction/contextMenu` | `contextVerb`, `buildContextMenu`, `contextVerbInput`, `ContextVerb`, `ContextMenu` |
|
|
193
|
-
| Shared / group wallet | `economy/sharedWallet` | `createWalletBook`, `WalletBook`, `WalletScope`, `userScope`, `groupScope`, `balanceIn`, `grantTo`, `chargeFrom`, `contributionOf`, `contributorsOf` |
|
|
194
|
-
| Analog axis input | `input/axisInput` | `AxisInput`, `AxisChannel`, `AxisBindingMap`, `DRIVE_AXIS_BINDINGS`, `clampAxis`, `rampToward`, `NEUTRAL_AXIS` |
|
|
195
|
-
| Raw control polling | `runtime/inputSnapshot` | `createInputSnapshot`, `InputSnapshot` (`isDown`, `justPressed`, `justReleased`, `held`, `axis`) — backs `ctx.input` |
|
|
196
|
-
| Physics world | `physics/physicsWorld` | `PhysicsWorld`, `PhysicsWorldConfig` (`precision: "low" \| "standard" \| "high"` sets simulation fidelity; the individual solver/broadphase knobs are a deprecated advanced escape hatch), `PhysicsPrecision`, `PhysicsBounds`, `PhysicsStats`, `AddBodyOptions` (`{ shape: "box", halfExtents }` \| `{ shape: "sphere", radius }`), `JointOptions`, `JointKind`, `CollisionEvent` |
|
|
197
|
-
| Ballistic collision sweep | `physics/ballisticSweep` | `createBallisticSweep`, `BallisticSweep`, `BallisticSweepHit`, `BallisticSweepOptions` |
|
|
198
|
-
| Tweening / easing | `anim/easing` | `Easing`, `lerp`, `clamp01`, `smoothstep`, `easeInQuad`, `easeOutQuad`, `easeInOutQuad`, `easeInCubic`, `easeOutCubic`, `easeInOutCubic`, `easeOutBack`, `easeOutElastic`, `tween`, `timedProgress` |
|
|
199
|
-
| Async data source | `data/dataSource` | `createDataSource`, `DataSource`, `DataSourceState`, `DataSourceStatus`, `DataSourceOptions`, `DataSourceClock`, `RefreshOptions` |
|
|
200
|
-
| JSON fetch | `data/fetchJson` | `fetchJson`, `FetchJsonOptions`, `FetchImpl`, `HttpStatusError`, `JsonParseError` |
|
|
201
|
-
| JSON data source | `data/jsonDataSource` | `createJsonDataSource`, `JsonDataSourceOptions` |
|
|
202
|
-
| Dev proxy routing | `data/devProxy` | `proxiedUrl`, `parseDevProxyTable`, `DevProxyTable`, `ProxiedUrlOptions`, `DEFAULT_DEV_PROXY_PREFIX` |
|
|
203
|
-
| Grid-cell world rendering | `world/gridInstances` | `resolveGridInstances`, `GridInstanceTransform` |
|
|
204
|
-
| 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 |
|
|
205
|
-
| Turn loop | `turn/turnLoop` | `createTurnLoop`, `TurnLoop`, `TurnLoopConfig`, `TurnState`, `PoolConfig`, `PoolState`, `TurnLoopSnapshot` |
|
|
206
|
-
| Declared-action intent board | `turn/intent` | `createIntentBoard`, `IntentBoard`, `DeclaredIntent` — `declare(participantId, intent)`, `peek`, `all`, `consume`, `clear` |
|
|
207
|
-
| Commit modes | `turn/commit` | `createCommitController`, `CommitController`, `CommitMode`, `CommitOutcome`, `SubmittedAction` |
|
|
208
|
-
| Intent board | `turn/intent` | `createIntentBoard`, `IntentBoard`, `DeclaredIntent` |
|
|
209
|
-
| Tactical grid | `tactics/tacticalGrid` | `createTacticalGrid`, `TacticalGrid`, `TacticalGridConfig`, `Tile`, `ReachableTile`, `PushResult`, `PushCollision` |
|
|
210
|
-
| Predictive query | `tactics/predictiveQuery` | `predictAreaEffect`, `predictArcEffect`, `predictTiles`, `PredictiveDeps`, `PredictedTarget` |
|
|
211
|
-
| Sim snapshot | `tactics/snapshot` | `createSnapshotStore`, `SnapshotStore`, `SnapshotSlice`, `Snapshot`, `deepClone` |
|
|
212
|
-
| Surfaces | `tactics/surface` | `createSurfaceLayer`, `SurfaceLayer`, `SurfaceLayerConfig`, `SurfaceKindDef`, `SurfaceReaction`, `SurfaceEvent` |
|
|
213
|
-
| Area targeting | `combat/effects` | `resolveAreaTargets`, `AreaTarget`, `AreaTargetInput` (shared AoE targeting behind `effect` + the predictive query) |
|
|
214
|
-
| Environment field | `world/envField` | `createEnvironmentField`, `EnvironmentField`, `EnvironmentSample`, `EnvironmentFieldConfig`, `OccluderRect`, `HeatSource` |
|
|
215
|
-
| Weather + fire | `world/weather` | `resolveWeather`, `WeatherState`, `WeatherModifier`, `WeatherModifierTable`, `ResolvedWeather`, `createFireGrid`, `FireGrid`, `FireCell`, `FireGridConfig` |
|
|
216
|
-
| Realm composition | `world/realm` | `composeRealm`, `RealmCard`, `RealmBase`, `ComposedRealm`, `RealmEnvironmentParams`, `SpawnTableOverride` |
|
|
217
|
-
| Decay meters | `survival/decayMeter` | `createDecayMeterSet`, `DecayMeterSet`, `DecayMeterConfig`, `MeterThreshold`, `DecayMeterState` |
|
|
218
|
-
| Status moodles | `survival/moodle` | `createMoodleStack`, `stackMoodles`, `MoodleStack`, `Moodle`, `MoodleSeverity`, `TimedMoodleInput` |
|
|
219
|
-
| Multi-region health | `survival/regionHealth` | `createMultiRegionHealth`, `MultiRegionHealth`, `HealthRegionConfig`, `AilmentConfig`, `RegionHealthState`, `AilmentInstance` |
|
|
220
|
-
| Audio contract | `audio/audioFalloff` | `computeFalloffGain`, `resolveEmitterGain`, `distance3`, `AudioFalloffConfig`, `FalloffCurve`, `SoundDef`, `AudioBusDef`, `AudioBusId` |
|
|
221
|
-
| Beat clock | `time/beatClock` | `createBeatClock`, `createBeatInputBuffer`, `nextBeatTime`, `BeatClock`, `BeatClockConfig`, `BeatSnapshot`, `BeatInputBuffer`, `BufferedAction` |
|
|
222
|
-
| Spawn director | `ai/spawnDirector` | `createSpawnDirectorState`, `advanceSpawnDirector`, `advanceWave`, `raiseAlert`, `pickSpawnPoint`, `SpawnDirectorConfig`, `WaveManifest`, `SpawnEntry`, `SpawnRequest`, `DirectorContext`, `SpawnPointSelectionOptions`, `SpawnPointDistanceBias`, `SpawnPointBiasStrength` |
|
|
223
|
-
| Threat table | `ai/threat` | `createThreatTable`, `ThreatTable`, `ThreatTableConfig`, `ThreatEntry`, `HighestThreatOptions` |
|
|
224
|
-
| 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 |
|
|
225
|
-
| Job board | `ai/jobBoard` | `createJobBoard`, `JobBoard`, `JobDef`, `Job`, `JobPhase`, `WorkerState`, `JobReport`, `JobTickContext` |
|
|
226
|
-
| Crowd flow | `ai/crowd` | `computeFlowField`, `createCrowdField`, `selectPoi`, `FlowField`, `FlowFieldOptions`, `CrowdField`, `Poi`, `SelectPoiOptions` |
|
|
227
|
-
| Factions & reputation | `faction/factions`, `faction/reputation` | `createFactionGraph`, `createFactionRoster`, `FactionRelation`, `FactionDef`, `FactionGraph`, `FactionRoster`, `createReputationLedger`, `DEFAULT_REPUTATION_TIERS`, `tierForStanding`, `effectiveRelation`, `ReputationTier`, `ReputationLedger` |
|
|
228
|
-
| Physics actors | `physics/ragdoll`, `physics/carryable`, `physics/forceVolume`, `physics/spatialGrid` | `createRagdoll`, `Ragdoll`, `Carryable`, `carrySpeedMultiplier`, `ForceVolume`, `PlatformCarry`, `SpatialGrid` |
|
|
229
|
-
| Traversal (grapple/glide) | `physics/traversal` | `Grapple`, `GrappleConfig`, `Glide`, `GlideConfig` |
|
|
230
|
-
| Structural destruction | `physics/structure` | `StructureGraph`, `StructureNodeSpec`, `StructureEdgeSpec`, `StructureMaterial`, `StructureMaterialTable`, `CollapseEvent`, `DebrisConfig` |
|
|
231
|
-
| Destructible terrain | `world/carve` | `VoxelVolume`, `VoxelMaterial`, `VoxelMaterialTable`, `CarvableField`, `carvableTerrain`, `CarveOp`, `DepositOp`, `CraterOp`, `MoundOp`, `EMPTY_VOXEL` |
|
|
232
|
-
| Vehicle body | `physics/vehicleBody` | `createVehicleBody`, `VehicleBody`, `VehicleBodyConfig`, `WheelSpec`, `GripCurve`, `sampleGripCurve`, `DEFAULT_GRIP_CURVE` |
|
|
233
|
-
| Buoyant boat | `physics/buoyancy` | `createBuoyantBody`, `BuoyantBody`, `BuoyantBodyConfig` |
|
|
234
|
-
| Crash damage | `physics/damageZones` | `createDamageModel`, `DamageModel`, `DamageZoneDef`, `DamageTransition` |
|
|
235
|
-
| Mounts / rideables | `scene/mount` | `createMountController`, `MountController`, `MountKit`, `MountSeat`, `RideableConfig` |
|
|
236
|
-
| Shared-vehicle stations | `scene/stationClaim` | `createStationClaim`, `StationClaim`, `Station`, `SharedVehicleConfig`, `ClaimResult` |
|
|
237
|
-
| Lag compensation | `multiplayer/lagCompensation` | `createPositionHistory`, `PositionHistory`, `rewindTimestamp`, `resolveHitscan`, `raySphereDistance`, `HitscanRay`, `HitscanTarget` |
|
|
238
|
-
| Simultaneous commit | `multiplayer/simultaneousCommit` | `createCommitRound`, `CommitRound`, `SealedCommit`, `resolveCommits` |
|
|
239
|
-
| Combat-snapshot replay | `multiplayer/combatSnapshot` | `serializeBoard`, `cloneSnapshot`, `replayCombat`, `BoardSnapshot`, `SnapshotUnit`, `CombatRules`, `ReplayResult` |
|
|
240
|
-
| Session matchmaking | `multiplayer/matchmaking` | `browseSessions`, `findByJoinCode`, `quickMatch`, `matchesFilter`, `normalizeJoinCode`, `generateJoinCode`, `SessionListing`, `MatchFilter` |
|
|
241
|
-
| Auth identity | `multiplayer/identity` | `AuthSession`, `PlayerIdentity`, `sessionPlayer`, `resolveGuestSession` |
|
|
242
|
-
| Text chat | `game/chat`, `multiplayer/chatContract` | `createChat`, `Chat`, `ChatMessage`, `ChatChannelDef`, `whisperChannelId`, `createChatRateLimiter`, `ChatTransport`, `ChatSync`, `createLocalChatTransport` |
|
|
243
|
-
| 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) |
|
|
244
|
-
| Voice seam | `multiplayer/voiceContract` | `VoiceTransport`, `VoiceParticipant`, `VoiceRoute`, `createLocalVoiceTransport`, `createPushToTalk`, `PushToTalkMode` |
|
|
245
|
-
| Race state | `game/race` | `raceTrack`, `RaceTrack`, `createRaceState`, `RaceState`, `RaceEvent`, `RaceWinCondition`, `firstPastPost`, `topK`, `lastStanding`, `everyoneFinishes` |
|
|
246
|
-
| Race session | `game/race` | `RacePhase`, `RaceSessionState`, `idleRaceSession`, `startRaceCountdown`, `tickRaceSession`, `finishRaceSession` — pure `idle→countdown→racing→finished` clock; `racePlacements`, `placementOf`, `raceOutcomeOf` derive placement/win-lose from a finish order |
|
|
247
|
-
| Reveal query | `sensor/revealQuery` | `createRevealQuery`, `RevealQuery`, `RevealQueryOptions`, `RevealHit` |
|
|
248
|
-
| Hidden-state probe | `sensor/hiddenStateProbe` | `probeHiddenState`, `probeHiddenStateAll`, `HiddenStateSource`, `HiddenStateValue`, `SensorProbeOptions`, `SensorReading` |
|
|
249
|
-
| View-frustum sensor | `sensor/frustumSensor` | `createFrustumSensor`, `projectToView`, `framingScore`, `FrustumCamera`, `FrustumTarget`, `FrustumProjection`, `FrustumSample`, `FrustumSensor`, `FramingConfig` |
|
|
250
|
-
| Recording buffer | `sensor/recordingBuffer` | `createRecordingBuffer`, `RecordingBuffer`, `RecordingFrame`, `RecordingBufferOptions` |
|
|
251
|
-
| Concealment scoring | `sensor/concealment` | `colorDistance`, `concealmentScore`, `createConcealmentSensor`, `ColorHex`, `ConcealmentTarget`, `ConcealmentSample`, `ConcealmentSensor` |
|
|
252
|
-
| Freeze violation monitor | `sensor/freezeMonitor` | `createFreezeMonitor`, `FreezeMonitor`, `FreezeSubject`, `FreezeViolation` |
|
|
253
|
-
| Animation SM | `combat/animationState` | `createAnimationState`, `AnimationState`, `AnimationClip`, `FramePhase`, `FrameRange`, `phasesAtFrame`, `activeRangeAtFrame`, `frameAtMs` |
|
|
254
|
-
| Accumulator meter | `stats/accumulatorMeter` | `createAccumulatorMeter`, `AccumulatorMeter`, `AccumulatorMeterConfig`, `MeterTier`, `MeterAddResult`, `tierAt` |
|
|
255
|
-
| Stagger / buildup | `combat/breakMeters` | `createStaggerMeter`, `createBuildupMeter`, `StaggerMeter`, `BuildupMeter`, `BuildupProc` |
|
|
256
|
-
| Attack tags | `combat/attackTags` | `attackMeta`, `AttackTag`, `AttackMeta`, `hasTag`, `isBlockable`, `isParryable`, `isDodgeable`, `counters` |
|
|
257
|
-
| Defensive window | `combat/defensiveWindow` | `createDefensiveWindow`, `resolveDefense`, `DefensiveWindowConfig`, `DefenseKind`, `DefenseOutcome`, `windowActiveAt`, `iframeActiveAt` |
|
|
258
|
-
| Combo string | `combat/comboString` | `createComboRunner`, `advanceCombo`, `ComboString`, `ComboStep`, `AdvanceComboResult` |
|
|
259
|
-
| Hit reaction | `combat/hitReaction` | `resolveHitReaction`, `HitReaction`, `HitReactionConfig`, `CameraShake`, `applyImpulse` |
|
|
260
|
-
| Telegraph | `combat/telegraph` | `pointInTelegraph`, `telegraphProgress`, `telegraphFired`, `telegraphTurnProgress`, `telegraphFiredAtTurn`, `telegraphTurnsRemaining`, `TelegraphShape`, `TelegraphConfig` |
|
|
261
|
-
| Dash / dodge | `movement/dash` | `createDashState`, `DashState`, `DashConfig`, `DashBurst`, `iframeActive`, `dashOffset` |
|
|
262
|
-
| Ability kit | `combat/abilityKit` | `createAbilityKit`, `AbilityKit`, `AbilitySlotConfig`, `AbilitySlotSnapshot`, `AbilitySlotState`, `AbilityCastType`, `AbilityCastResult`, `AbilitySlotRetune` |
|
|
263
|
-
| 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` |
|
|
264
|
-
| Combo points | `combat/comboPoints` | `createComboPoints`, `ComboPoints`, `ComboPointsConfig` — discrete points accrued on action, expiring after a timeout from the last gain, spent in bulk |
|
|
265
|
-
| Event meter | `stats/eventMeter` | `createEventMeter`, `EventMeter`, `EventMeterConfig`, `EventMeterFeedResult` |
|
|
266
|
-
| Auto-target policy | `scene/autoTarget` | `selectAutoTarget`, `createAutoTargeter`, `AutoTargetPolicy`, `AutoTargeter`, `AutoTargetDeps` |
|
|
267
|
-
| Resistance matrix | `combat/resistance` | `resolveResistance`, `resistanceScale`, `ResistanceMatrix`, `ResistVerdict`, `ResistanceResult` |
|
|
268
|
-
| Run draft | `game/runDraft` | `createRunDraft`, `createRunModifierStack`, `RunDraft`, `RunModifierStack`, `RunModifierOffer` |
|
|
269
|
-
| Uniform-cell grid | `puzzle/cellGrid` | `CellGrid`, `CellRun`, `createCellGrid`, `cellAt`, `inGridBounds`, `withCell`, `withCells`, `fullRows`, `clearRows`, `collapseColumns`, `findRuns` |
|
|
270
|
-
| Falling piece | `puzzle/fallingPiece` | `FallingPiece`, `ShapeTable`, `LockDelayState`, `pieceCells`, `pieceCollides`, `mergePiece`, `dropDistance`, `gravityInterval`, `levelForLines`, `lineScore`, `createLockDelay`, `stepLockDelay` |
|
|
271
|
-
| 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 |
|
|
272
|
-
| Spawn/respawn points | `game/spawnPoints` | `createSpawnPoints`, `SpawnPoints`, `SpawnPointPose`, `RespawnTarget` |
|
|
273
|
-
| Level sequence | `game/levelSequence` | `createLevelSequence`, `LevelSequence`, `LevelSequenceConfig`, `LevelDescriptor`, `CurrentLevel`, `LevelSequenceStatus`, `LevelSequenceProgress` |
|
|
274
|
-
| Devtools overlay + tunables | `devtools/devtools` | `devtools`, `createDevtools`, `tunable`, `snapshotDevtools`, `instrumentLatency`, `Tunable`, `TunableOptions`, `TunableAccessor`, `DevtoolsControl`, `DiscoveredEntry`, `DevtoolsOverrides`, `DevtoolsSnapshot` |
|
|
275
|
-
| Tunable auto-discovery | `devtools/transformTunables` | `transformTunableExports`, `tunableModuleTable`, `tunableDiscoveryPlugin`, `TunableTransformResult` |
|
|
276
|
-
|
|
277
|
-
## Getting started (new project)
|
|
278
|
-
|
|
279
|
-
Fastest path — the `jgengine` CLI scaffolds the entire canonical shape below (harness, skeleton, stub game, verify test, AGENTS.md) as a booting game:
|
|
280
|
-
|
|
281
|
-
```sh
|
|
282
|
-
npx jgengine create my-game # then: cd my-game && bun dev
|
|
283
|
-
npx jgengine doctor # later, if the setup drifts (version skew, unstyled HUD, shape strays)
|
|
284
|
-
```
|
|
285
|
-
|
|
286
|
-
Manual equivalent:
|
|
287
|
-
|
|
288
|
-
```sh
|
|
289
|
-
bun add @jgengine/core @jgengine/react @jgengine/shell react react-dom three three-stdlib @react-three/fiber @react-three/drei
|
|
290
|
-
bun add -d @tailwindcss/vite tailwindcss # HUD styling (Vite + Tailwind v4)
|
|
291
|
-
```
|
|
292
|
-
|
|
293
|
-
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:
|
|
294
|
-
|
|
295
|
-
```html
|
|
296
|
-
<!-- index.html -->
|
|
297
|
-
<!doctype html>
|
|
298
|
-
<html lang="en">
|
|
299
|
-
<head>
|
|
300
|
-
<meta charset="UTF-8" />
|
|
301
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
302
|
-
<title>My Game</title>
|
|
303
|
-
</head>
|
|
304
|
-
<body>
|
|
305
|
-
<div id="root"></div>
|
|
306
|
-
<script type="module" src="/src/main.tsx"></script>
|
|
307
|
-
</body>
|
|
308
|
-
</html>
|
|
309
|
-
```
|
|
310
|
-
|
|
311
|
-
```ts
|
|
312
|
-
// vite.config.ts — monorepo-aware: the alias branch only fires when this folder
|
|
313
|
-
// sits inside the engine repo checkout; copied anywhere else, @jgengine/* resolves
|
|
314
|
-
// from npm dist and the alias list is empty
|
|
315
|
-
import { existsSync } from "node:fs";
|
|
316
|
-
import { fileURLToPath } from "node:url";
|
|
317
|
-
import tailwindcss from "@tailwindcss/vite";
|
|
318
|
-
import react from "@vitejs/plugin-react";
|
|
319
|
-
import { defineConfig } from "vite";
|
|
320
|
-
|
|
321
|
-
const engineSrc = (pkg: string) => fileURLToPath(new URL(`../../packages/${pkg}/src`, import.meta.url));
|
|
322
|
-
|
|
323
|
-
export default defineConfig({
|
|
324
|
-
plugins: [react(), tailwindcss()],
|
|
325
|
-
resolve: {
|
|
326
|
-
alias: existsSync(engineSrc("core"))
|
|
327
|
-
? [
|
|
328
|
-
{ find: /^@jgengine\/core\/(.*)$/, replacement: `${engineSrc("core")}/$1` },
|
|
329
|
-
{ find: /^@jgengine\/react\/(.*)$/, replacement: `${engineSrc("react")}/$1` },
|
|
330
|
-
{ find: /^@jgengine\/ws\/(.*)$/, replacement: `${engineSrc("ws")}/$1` },
|
|
331
|
-
{ find: /^@jgengine\/shell\/(.*)$/, replacement: `${engineSrc("shell")}/$1` },
|
|
332
|
-
{ find: /^@jgengine\/assets$/, replacement: `${engineSrc("assets")}/index.ts` },
|
|
333
|
-
{ find: /^@jgengine\/assets\/(.*)$/, replacement: `${engineSrc("assets")}/$1` },
|
|
334
|
-
]
|
|
335
|
-
: [],
|
|
336
|
-
},
|
|
337
|
-
});
|
|
338
|
-
```
|
|
339
|
-
|
|
340
|
-
```css
|
|
341
|
-
/* src/index.css */
|
|
342
|
-
@import "tailwindcss";
|
|
343
|
-
@source "../node_modules/@jgengine/react/dist";
|
|
344
|
-
@source "../node_modules/@jgengine/shell/dist";
|
|
345
|
-
```
|
|
346
|
-
|
|
347
|
-
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. In-repo, `index.css` also does `@import "./style.css";` and carries no game-specific rules itself — those live in a sibling `src/style.css` (no Tailwind import), which is what the `/play` runner lazy-loads per game so it isn't re-shipping the shared Tailwind base on every game switch.
|
|
348
|
-
|
|
349
|
-
```tsx
|
|
350
|
-
// main.tsx
|
|
351
|
-
import "./index.css";
|
|
352
|
-
|
|
353
|
-
import { createRoot } from "react-dom/client";
|
|
354
|
-
import { GameHost } from "@jgengine/shell/GameHost";
|
|
355
|
-
import { game } from "./game.config";
|
|
356
|
-
|
|
357
|
-
const root = document.getElementById("root");
|
|
358
|
-
if (root === null) throw new Error("main: missing #root mount element");
|
|
359
|
-
createRoot(root).render(<GameHost playable={game} />);
|
|
360
|
-
```
|
|
361
|
-
|
|
362
|
-
Add `"dev": "vite"` to `package.json`'s `scripts` — `bun dev` then launches the game standalone.
|
|
363
|
-
|
|
364
|
-
`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.
|
|
365
|
-
|
|
366
|
-
A multi-game host (a launcher, a dev registry) wires `GamePlayer` over a `GameRegistry`:
|
|
367
|
-
|
|
368
|
-
```tsx
|
|
369
|
-
import { GamePlayer } from "@jgengine/shell/GamePlayer";
|
|
370
|
-
import type { GameRegistry } from "@jgengine/shell/registry";
|
|
371
|
-
|
|
372
|
-
const games: GameRegistry = {
|
|
373
|
-
"my-game": () => import("./my-game").then((m) => m.game),
|
|
374
|
-
};
|
|
375
|
-
|
|
376
|
-
function App() {
|
|
377
|
-
return <GamePlayer gameId="my-game" registry={games} loading={<p>Loading…</p>} />;
|
|
378
|
-
}
|
|
379
|
-
```
|
|
380
|
-
|
|
381
|
-
`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.
|
|
382
|
-
|
|
383
|
-
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`.
|
|
384
|
-
|
|
385
|
-
## Scope
|
|
386
|
-
|
|
387
|
-
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.
|
|
388
|
-
|
|
389
|
-
| Engine owns | Your game owns |
|
|
390
|
-
|-------------|----------------|
|
|
391
|
-
| 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 |
|
|
392
|
-
|
|
393
|
-
**Rules:**
|
|
394
|
-
|
|
395
|
-
1. **Catalog-first** — shape and behavior of every id lives in game-owned catalog files. Runtime calls pass ids, positions, instance keys.
|
|
396
|
-
2. **Three buckets** — inventory items, scene objects, scene entities. Never merge them.
|
|
397
|
-
3. **Dumb place/spawn** — no behaviors on `place()`/`spawn()`; the catalog owns them.
|
|
398
|
-
4. **Commands for verbs** — input maps to actions, actions to commands/handlers; no raw keys in game logic.
|
|
399
|
-
5. **Primitives over glue** — a loop several games need (loot roll, shop buy, kit seeding) belongs in the engine, not copy-pasted per game.
|
|
400
|
-
6. **No speculative config** — `defineGame` fields exist only with a live engine consumer.
|
|
401
|
-
7. **This file stays domain-free.**
|
|
402
|
-
|
|
403
|
-
## The three buckets
|
|
404
|
-
|
|
405
|
-
| Bucket | What | API |
|
|
406
|
-
|--------|------|-----|
|
|
407
|
-
| **Inventory** | Stackable ids in containers | `ctx.player.inventory.put / take / move / has / count` |
|
|
408
|
-
| **Scene object** | Static world content | `ctx.scene.object.place / remove / move / rotate / list` |
|
|
409
|
-
| **Scene entity** | Movers driven per tick | `ctx.scene.entity.spawn / despawn / setPose / effect / …` |
|
|
410
|
-
|
|
411
|
-
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.
|
|
412
|
-
|
|
413
|
-
## Game repo layout
|
|
414
|
-
|
|
415
|
-
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/`. In this repo the gate also requires a root `package.json` script `"games:<id>": "bun run --cwd Games/<id> dev"` for every `Games/*` directory — add it with the scaffold, or the very first `check-types` fails before the compiler even runs. Dense files — one `catalog.ts` per domain, never one file per entry.
|
|
416
|
-
|
|
417
|
-
```
|
|
418
|
-
src/
|
|
419
|
-
game.config.ts single entry — export const game = defineGame({...}) from "@jgengine/shell/defineGame"
|
|
420
|
-
index.tsx barrel — export { game } from "./game.config" (+ any UI-preview scenario re-export)
|
|
421
|
-
main.tsx standalone host — mounts <GameHost playable={game}/> from "@jgengine/shell/GameHost"
|
|
422
|
-
loop.ts onInit / onNewPlayer (boot); prefer systems for per-frame work
|
|
423
|
-
world.ts WorldFeature + PhysicsConfig (only for games that have one)
|
|
424
|
-
game/
|
|
425
|
-
systems.ts defineSystem capabilities listed in defineGame({ systems })
|
|
426
|
-
keybinds.ts ActionCodesMap — named actions + hotbarSlotBindings(n)
|
|
427
|
-
inventories.ts inventory declarations
|
|
428
|
-
assets.ts Render catalog
|
|
429
|
-
content.ts itemById / entityById lookups over all catalogs
|
|
430
|
-
loadouts.ts Loadout ids → items/economy/unlocks per inventory
|
|
431
|
-
world/ zones.ts, setup.ts (place/spawn from onInit)
|
|
432
|
-
items/ <domain>/catalog.ts + use-handlers.ts
|
|
433
|
-
objects/ catalog.ts (+ loot tables beside their domain)
|
|
434
|
-
entities/ players/ enemies/ npcs/ — catalog.ts per role (never actors/)
|
|
435
|
-
quests/catalog.ts when using game.quest
|
|
436
|
-
progression/ curves.ts — game-owned XP curve numbers fed to game/progression
|
|
437
|
-
ui/GameUI.tsx ALL layout/positioning
|
|
438
|
-
ui/components/ content-only pieces GameUI places
|
|
439
|
-
```
|
|
440
|
-
|
|
441
|
-
## `defineGame` — the single authoring entry
|
|
442
|
-
|
|
443
|
-
`@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).
|
|
444
|
-
|
|
445
|
-
**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.
|
|
446
|
-
|
|
447
|
-
**Composable systems (`systems`)** — preferred runtime path: list meaningful capabilities (`combat()`, `mobs()`), each a `defineSystem({ id, tick, update, events?, feature?, save?, … })`. Engine compiles fixed/frame/interval/event/manual schedules with deterministic stage order. `feature` enables `ctx.game.*` without a redundant flag. Classic `loop` still works for boot/join. Full contract: [reference-systems.md](reference-systems.md).
|
|
448
|
-
|
|
449
|
-
**Opt-in `features`** — `defineGame({ features: { quest, trade, … } })` when not installing a system; omit and `ctx.game.<name>` is `undefined`. `chat` implies `social`.
|
|
450
|
-
|
|
451
|
-
**Offline whole-world save (`persist`)** — `defineGame({ persist: true })` binds `ctx.game.save`. Guide: `jgengine-gameplay` → whole-game save.
|
|
452
|
-
|
|
453
|
-
```ts
|
|
454
|
-
// game.config.ts — imports only
|
|
455
|
-
import { defineGame } from "@jgengine/shell/defineGame";
|
|
456
|
-
import { systems } from "./game/systems";
|
|
457
|
-
import { loop } from "./loop";
|
|
458
|
-
// …assets, content, GameUI, inventories, keybinds, physics, world
|
|
459
|
-
|
|
460
|
-
export const game = defineGame({
|
|
461
|
-
name: "My Game",
|
|
462
|
-
assets, world, physics, inventories, input: keybinds,
|
|
463
|
-
multiplayer: offline(), content, systems, loop, GameUI,
|
|
464
|
-
});
|
|
465
|
-
```
|
|
466
|
-
|
|
467
|
-
```ts
|
|
468
|
-
// game/keybinds.ts — named actions + generated hotbar slots; one key, one action
|
|
469
|
-
import { hotbarSlotBindings, type ActionCodesMap } from "@jgengine/core/input/actionBindings";
|
|
470
|
-
|
|
471
|
-
export const keybinds: ActionCodesMap = {
|
|
472
|
-
moveForward: ["KeyW"], moveBack: ["KeyS"], moveLeft: ["KeyA"], moveRight: ["KeyD"],
|
|
473
|
-
jump: ["Space"], sprint: ["ShiftLeft"],
|
|
474
|
-
interact: ["KeyE"],
|
|
475
|
-
crouch: { hold: ["KeyC"], toggle: ["KeyZ"] },
|
|
476
|
-
aim: { hold: ["mouse2"], toggle: ["KeyV"] },
|
|
477
|
-
tabTarget: ["Tab"], clearTarget: ["Escape"],
|
|
478
|
-
...hotbarSlotBindings(9), // hotbarSlot1..9 → Digit1..9 (a 10th slot gets Digit0)
|
|
479
|
-
};
|
|
480
|
-
```
|
|
481
|
-
|
|
482
|
-
```ts
|
|
483
|
-
// game/inventories.ts
|
|
484
|
-
import type { InventoryDeclaration } from "@jgengine/core/game/defineGame";
|
|
485
|
-
export const inventories: Record<string, InventoryDeclaration> = {
|
|
486
|
-
hotbar: { slots: 9, hud: "hotbar" },
|
|
487
|
-
backpack: { slots: 28, traits: itemTraits },
|
|
488
|
-
equipment: { slots: 4, accepts: ["weapon", "armor"], applyModifiers: true },
|
|
489
|
-
};
|
|
490
|
-
|
|
491
|
-
// world.ts — top of src/, not under game/
|
|
492
|
-
import type { PhysicsConfig } from "@jgengine/core/game/defineGame";
|
|
493
|
-
import { biomes, type WorldFeature } from "@jgengine/core/world/features";
|
|
494
|
-
export const world: WorldFeature = biomes({ map: "world/biomes", zones: "world/zones" });
|
|
495
|
-
export const physics: PhysicsConfig = { gravity: -32 };
|
|
496
|
-
```
|
|
497
|
-
|
|
498
|
-
- `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.
|
|
499
|
-
- 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.
|
|
500
|
-
- **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). **`hotbarSlotN` and a game's own `selectSlotN` are two different hotbar models, not a duplication** (#743): reserved `hotbarSlotN` is *direct-activate* — press `1` and the shell immediately uses/equips slot 1's item (Minecraft/shooter quick-use), so it never reaches a command. A *select-then-act* game (a weapon wheel where `1` picks the active weapon and a separate `fire` uses it) needs persistent selection state the shell doesn't own, so it binds its own `selectSlot1..N` actions, defines commands that write a store key, and reads it back through `hotbarSelection: () => ...` on `defineGame` (see `vice-isle`). Pick `hotbarSlotN` when the number key *is* the action; bind `selectSlotN` only when a later verb consumes the selection.
|
|
501
|
-
- **`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.
|
|
502
|
-
- 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.
|
|
503
|
-
- `server.mode` is a string your loop/commands interpret — the engine ships no gamemode presets.
|
|
504
|
-
- 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).
|
|
505
|
-
- `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.
|
|
506
|
-
- `devtools` defaults to `true` — every game gets the F2+D-toggled debug overlay (debug mode) (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. In the dev runner the Tune tab's **Save to source** button writes changed values back into the game's `.ts` files via the dev server's `/__jgengine/save` endpoint (`@jgengine/core/devtools/rewriteTunables` does the literal rewrite; unlocatable keys are reported skipped). See "Devtools — F2+D overlay and tunables" below.
|
|
507
|
-
|
|
508
|
-
### `@jgengine/core/game/defineGame` — the underlying primitive
|
|
509
|
-
|
|
510
|
-
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.
|
|
511
|
-
|
|
512
|
-
```ts
|
|
513
|
-
import { defineGame as defineEngineGame } from "@jgengine/core/game/defineGame";
|
|
514
|
-
import { offline } from "@jgengine/core/runtime/adapter";
|
|
515
|
-
|
|
516
|
-
const game = defineEngineGame({
|
|
517
|
-
name: "My Game",
|
|
518
|
-
assets, world, physics, inventories,
|
|
519
|
-
input: keybinds,
|
|
520
|
-
server: "persistent",
|
|
521
|
-
save: { auto: "5m", scope: "player+chunks" },
|
|
522
|
-
multiplayer: offline(),
|
|
523
|
-
loop, // GameLoop<GameContext>
|
|
524
|
-
});
|
|
525
|
-
```
|
|
526
|
-
|
|
527
|
-
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.
|
|
528
|
-
|
|
529
|
-
### `@jgengine/core/runtime/headlessRunner` — the renderer-free play loop
|
|
530
|
-
|
|
531
|
-
`createHeadlessRunner({ definition, content?, loop, player? })` drives a real game loop with **no React, R3F, or three.js** — the non-React game path for a server tick, a test, or a CLI replay. It builds the `GameContext`, runs `onInit`/`onNewPlayer` at construction, then each `step(dtSeconds, input?)` publishes the input, advances the sim clock (clamped to `maxStepSeconds`, default `0.05`), and runs `loop.onTick` plus behaviour nav. The shell's `FrameDriver` is one such driver bolted to R3F's `useFrame`; this is that same step distilled out of the render tree.
|
|
532
|
-
|
|
533
|
-
```ts
|
|
534
|
-
import { createHeadlessRunner } from "@jgengine/core/runtime/headlessRunner";
|
|
535
|
-
|
|
536
|
-
const runner = createHeadlessRunner({ definition: game, content, loop: game.loop });
|
|
537
|
-
runner.step(0.05, { held: ["moveRight"] }); // input in → world snapshot changes out
|
|
538
|
-
const hero = runner.ctx.scene.entity.get(runner.userId); // read the snapshot via runner.ctx
|
|
539
|
-
```
|
|
540
|
-
|
|
541
|
-
`runner.ctx` is the live `GameContext` — read the world through `ctx.scene`, `ctx.game.store`, `ctx.subscribe`/`ctx.version()`. `runner.input` is the same `InputSnapshot` `onTick` polls; `publishInput({ held, pointer })` pre-seeds it before the first step. Pass `playerMovement: true` (with optional `heading`) to also run the built-in keyboard walk controller as the shell does for pose-driven games — off by default since cartridge/tick-driven games move their own entities in `onTick`. `maxStepSeconds` matches whatever fixed step the caller ticks at (e.g. `0.1` for a coarse server tick) so a long clamp never fast-forwards the sim. Maintainer: new exports here are documented by hand; run `bun run gen:skill-api` on a clean checkout to refresh the generated `api.md`.
|
|
542
|
-
|
|
543
|
-
## `PlayableGame` — how a game plugs into a runner
|
|
544
|
-
|
|
545
|
-
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`:
|
|
546
|
-
|
|
547
|
-
```ts
|
|
548
|
-
export type PlayableGame<TUi = unknown> = {
|
|
549
|
-
game: GameDefinition;
|
|
550
|
-
content: GameContextContent; // { itemById?, entityById?, objectById? }
|
|
551
|
-
loop: Required<GameLoop<GameContext>>; // onInit, onNewPlayer, onTick
|
|
552
|
-
GameUI: TUi; // React component in web runners
|
|
553
|
-
prompts?: (ctx: GameContext) => readonly PositionedPrompt[]; // interact-key + HUD source
|
|
554
|
-
};
|
|
555
|
-
```
|
|
556
|
-
|
|
557
|
-
`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.
|
|
558
|
-
|
|
559
|
-
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?, attachments?, parts? }` (`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`. `attachments: [{ slot, model, position?, rotation?, scale? }]` parents a prop to a named rig bone (weapons/props following animation); `parts: [{ model, position?, rotation?, scale? }]` stacks static kit-of-parts children at fixed local offsets with no bone/rig involved — see `jgengine-assets` for both.
|
|
560
|
-
|
|
561
|
-
`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.
|
|
562
|
-
|
|
563
|
-
**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.
|
|
564
|
-
|
|
565
|
-
**Capture recipe.** Any game with a start/title screen declares `PlayableGame.capture` at build time: `capture: { play: ["<startCommand>"] }` (the same commands its start buttons dispatch; entries may be `{ name, input }` when a command needs arguments), plus optional named `states` for other screenshot-worthy screens. Without it, `shoot --mode play` fails loudly on the menu. Details: `jgengine-verify`.
|
|
566
|
-
|
|
567
|
-
**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.
|
|
568
|
-
|
|
569
|
-
**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.
|
|
570
|
-
|
|
571
|
-
**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`.
|
|
572
|
-
|
|
573
|
-
**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.
|
|
574
|
-
|
|
575
|
-
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.
|
|
576
|
-
|
|
577
|
-
### Object spatial queries, entity patching, and surface sampling
|
|
578
|
-
|
|
579
|
-
```ts
|
|
580
|
-
ctx.scene.object.at(x, y, z) // cell lookup, cell size 1, most-recent wins
|
|
581
|
-
ctx.scene.object.inBox(min, max) // inclusive AABB query
|
|
582
|
-
ctx.scene.object.raycast({ origin, direction, maxDistance, halfExtents?, filter? }) // → nearest hit or null
|
|
583
|
-
ctx.scene.object.raycastAll({ origin, direction, maxDistance, halfExtents?, filter? }) // → hits, nearest-first
|
|
584
|
-
ctx.scene.entity.update(id, patch) // name/position/rotations/role/movement/behaviors/meta; false for unknown id
|
|
585
|
-
```
|
|
586
|
-
|
|
587
|
-
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.
|
|
588
|
-
|
|
589
|
-
`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).
|
|
590
|
-
|
|
591
|
-
`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.
|
|
592
|
-
|
|
593
|
-
**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.
|
|
594
|
-
|
|
595
|
-
### Audio — positional emitters, listener falloff, buses
|
|
596
|
-
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.
|
|
597
|
-
### Camera rigs (`camera` field of `defineGame({...})`)
|
|
598
|
-
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:
|
|
599
|
-
| `rig` | For | Key config (`camera.<rig>`) |
|
|
600
|
-
|-------|-----|------------------------------|
|
|
601
|
-
| `orbit` (default) | Third-person chase | Top-level fields on `camera` itself — `initialDistance`, `minDistance`/`maxDistance`, `targetHeight`, `min/maxPolarAngle`, drag/zoom. There is **no `camera.orbit` block**; orbit is the one rig tuned at the top level |
|
|
602
|
-
| `first` | FPS mouse-look | `firstPerson: { eyeHeight, sensitivity, maxPitch, reticle, viewmodel }` |
|
|
603
|
-
| `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`) |
|
|
604
|
-
| `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 |
|
|
605
|
-
| `shoulder` | Over-the-shoulder (Helldivers 2, Remnant II) | `shoulder: { shoulderOffset, distance, ads, side }` — ADS + shoulder-swap (V) |
|
|
606
|
-
| `lockOn` | Souls-like strafe (Elden Ring) | `lockOn: { targetEntityId?, distance, framingBias, yawSmoothing }` — yaw binds to player→target; WASD becomes strafe |
|
|
607
|
-
| `chase` | Vehicle chase (Forza, Rocket League) | `chase: { distance, springDamping, fov: { base, max, speedForMax }, shakePerSpeed, view: "chase"|"cockpit"|"hood"|"rear" }` |
|
|
608
|
-
| `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) |
|
|
609
|
-
| `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 |
|
|
610
|
-
| `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 |
|
|
611
|
-
| `none` | No camera rig mounted | HUD-only presentations or a game that manages its own camera; see `presentation: "hud"` below |
|
|
612
|
-
**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.
|
|
613
|
-
|
|
614
|
-
## `GameContext` — the ctx surface
|
|
615
|
-
|
|
616
|
-
`createGameContext` (in `@jgengine/core/runtime/gameContext`) wires every system:
|
|
617
|
-
|
|
618
|
-
```
|
|
619
|
-
ctx.scene.object place, remove, move, rotate, get, list, subscribe,
|
|
620
|
-
at, inBox, raycast, raycastAll, catalog
|
|
621
|
-
ctx.scene.entity spawn, despawn, setPose, update, get, list,
|
|
622
|
-
stats.{get,set,delta}, setTarget, getTarget, cycleTarget,
|
|
623
|
-
canReceive, preview, effect, paint,
|
|
624
|
-
willHitProjectile, fireProjectile, settleProjectile,
|
|
625
|
-
distance, inRadius, hasLineOfSight, queryArc, moveToward,
|
|
626
|
-
spawnPoseOf, resetToSpawn, resetAllToSpawn,
|
|
627
|
-
form.{register,get,active,abilities,shapeshift,revert},
|
|
628
|
-
bind(key) — lazily-keyed sim-snapshot → scene-entity pose
|
|
629
|
-
mirror; bind(key).sync(bodies, dt?) replaces a per-body
|
|
630
|
-
setPose loop + spawn/despawn dance (see jgengine-world)
|
|
631
|
-
ctx.game commands, events, feed, loot, trade, quest, social, chat,
|
|
632
|
-
unlocks, economy, leaderboard, roster, store, cards, turn
|
|
633
|
-
ctx.game.social friends, party, presence, emotes.play, worldInvites
|
|
634
|
-
ctx.game.store set, delete, get, has, subscribe, mapSnapshot, arraySnapshot — game-defined
|
|
635
|
-
keyed reactive store slot (any value type); mutations bump ctx.version().
|
|
636
|
-
Prefer a typed defineStore handle over raw get/set — see below
|
|
637
|
-
ctx.game.cards pile(id, config?) — lazily creates (config required on first call) or returns
|
|
638
|
-
the existing notify-wrapped CardPile for id
|
|
639
|
-
ctx.game.turn loop(id, config?) — lazily creates (config required on first call) or returns
|
|
640
|
-
the existing notify-wrapped TurnLoop for id
|
|
641
|
-
ctx.player userId, isNew, inventory, stats (modifiers), loadout,
|
|
642
|
-
applyLoadout, movement (pose/aim), motion (impulse/setVerticalVelocity/setY/takePending),
|
|
643
|
-
possession, cosmetics
|
|
644
|
-
ctx.player.motion impulse(vy), setVerticalVelocity(vy), setY(y), takePending() — game-code
|
|
645
|
-
seam into the shell's vertical-motion integrator; drained once per frame
|
|
646
|
-
before gravity, so a jump pad or grapple release calls this from
|
|
647
|
-
onTick/commands instead of touching y directly
|
|
648
|
-
ctx.item use, weapon
|
|
649
|
-
ctx.input publish(held), isDown(action), held(), justPressed(action), justReleased(action)
|
|
650
|
-
— per-frame held-action snapshot, polled from onTick; justPressed/justReleased
|
|
651
|
-
fire exactly once on the up/down transition frame, replay-safe
|
|
652
|
-
ctx.world ground (TerrainField), groundHeightAt(x, z) — the canonical
|
|
653
|
-
sampler for the game's declared world; environment worlds
|
|
654
|
-
resolve their terrain field, every other world kind is 0.
|
|
655
|
-
Use it for every spawn/placement/waypoint y — never
|
|
656
|
-
hand-roll a noise sampler or hardcode y = 0 on relief
|
|
657
|
-
ctx.camera follow(entityId | null), followedEntityId(), setCinematic(config), cinematic(),
|
|
658
|
-
subscribe — runtime camera-follow/cinematic override; the shell reads
|
|
659
|
-
followedEntityId() each frame, falling back to the static
|
|
660
|
-
playable.camera.followEntityId when it returns undefined
|
|
661
|
-
ctx.time advance, now, calendar, snapshot; pause, play, toggle,
|
|
662
|
-
setSpeed, cycleSpeed; after, every, at (game-time timers)
|
|
663
|
-
ctx.subscribe / ctx.version change signal — UI layers bind via useSyncExternalStore
|
|
664
|
-
ctx.touch() bumps ctx.version()/notifies ctx.subscribe directly — the escape hatch for a
|
|
665
|
-
command that only mutates game-owned state outside entity/object/economy/store
|
|
666
|
-
(an external session map, a closure variable) and needs a reactive HUD refresh
|
|
667
|
-
without faking a ctx.game.store.set
|
|
668
|
-
```
|
|
669
|
-
|
|
670
|
-
`content.itemById(id)` supplies `{ use?, weapon?, trade? }` — exact shapes: `use` is the handler **name string** (not an object), `weapon` is a flat `Record<string, number | Record<string, number>>` built from your catalog stats (`damage`, `projectile.{...}`, `explosion.{...}`), and every lookup returns **`null`** (not `undefined`) for an unknown id; `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`. Call-shape gotchas that cost typecheck loops: `ctx.item.use.use(input)` takes **one** argument on the ctx surface (the two-arg `use(state, input)` is the raw factory shape); `ctx.scene.entity.moveToward(id, target, { speed, dt, stopDistance? })` — the third argument is an options object, never a bare `dt`; `nav/pathFollow`'s `createPathFollow(config)` returns the initial `PathFollowState` directly and `advancePathFollow(config, state, dt)` returns the **next state** (with `position: [x,y,z]`, `heading`, `done`) — there is no wrapper object, and `Waypoint` is a `[x, y, z]` tuple. 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.
|
|
671
|
-
|
|
672
|
-
### Two tiers: `ctx` runtime vs pure factories
|
|
673
|
-
|
|
674
|
-
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.
|
|
675
|
-
|
|
676
|
-
`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.
|
|
677
|
-
|
|
678
|
-
## `systems` + `loop` — lifecycle
|
|
679
|
-
|
|
680
|
-
Prefer `defineSystem` + `defineGame({ systems })` for per-frame work (no giant `onTick` fan-out). `loop` keeps boot/join:
|
|
681
|
-
|
|
682
|
-
```ts
|
|
683
|
-
// game/systems.ts
|
|
684
|
-
import { defineSystem } from "@jgengine/core/game/defineSystem";
|
|
685
|
-
export const combat = defineSystem({
|
|
686
|
-
id: "combat", tick: { type: "frame", stage: "combat" },
|
|
687
|
-
update(ctx, dt) { /* dt is game time */ },
|
|
688
|
-
});
|
|
689
|
-
export const systems = [combat];
|
|
690
|
-
// loop.ts — onInit registers catalogs/quests; onNewPlayer spawns player
|
|
691
|
-
```
|
|
692
|
-
|
|
693
|
-
`composeGameLoop` installs systems on `onInit`, ticks before residual `loop.onTick`. Stages: `input→movement→combat→ai→activities→cleanup` (+ frame `animation→camera→effects`). See [reference-systems.md](reference-systems.md).
|
|
694
|
-
|
|
695
|
-
## `ctx.time` — the simulation clock
|
|
696
|
-
|
|
697
|
-
`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).
|
|
698
|
-
|
|
699
|
-
- **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.
|
|
700
|
-
- **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.
|
|
701
|
-
- **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.
|
|
702
|
-
|
|
703
|
-
### Beat clock — BPM signal + input quantization
|
|
704
|
-
|
|
705
|
-
`@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.
|
|
706
|
-
|
|
707
|
-
## Content catalogs
|
|
708
|
-
## `ctx.game.store` — reactive game state
|
|
709
|
-
|
|
710
|
-
**Default to a typed handle — `defineStore` (`@jgengine/core/store/defineStore`) + `useStore` (`@jgengine/react/store`).** One handle per key, one type parameter, zero casts at any call site. This is the blessed run-state pattern — never re-author a `store.get(KEY) as T` accessor trio or a `useGameStore((ctx) => ctx.game.store.get(KEY) as T)` hook per game, and never fork run state into a module-level singleton read via `useSyncExternalStore`.
|
|
711
|
-
|
|
712
|
-
```ts
|
|
713
|
-
// stores.ts
|
|
714
|
-
export const runStore = defineStore<RunState>("run", () => createInitialRunState());
|
|
715
|
-
|
|
716
|
-
// loop.ts / commands (no cast, no undefined)
|
|
717
|
-
runStore.read(ctx) // value, or the initial before any write
|
|
718
|
-
runStore.peek(ctx) // T | undefined — distinguishes "never written"
|
|
719
|
-
runStore.write(ctx, next) // bumps ctx.version(), notifies ctx.subscribe
|
|
720
|
-
runStore.update(ctx, (r) => ({ ...r, score: r.score + 1 }))
|
|
721
|
-
runStore.clear(ctx)
|
|
722
|
-
|
|
723
|
-
// a React HUD
|
|
724
|
-
const run = useStore(runStore) // whole value
|
|
725
|
-
const status = useStore(runStore, (r) => r.status) // derived slice, own equality
|
|
726
|
-
```
|
|
727
|
-
|
|
728
|
-
Pass a factory for the initial when the fallback is a fresh mutable object; it runs at most once and its result is reused, so an unwritten slot keeps a stable identity (no per-read churn). Writes flow through the engine store, so run state stays replayable and host-authoritative — the guarantees a module singleton gives up.
|
|
729
|
-
|
|
730
|
-
The raw keyed store (`ctx.game.store`, `ObservableKeyedStore<unknown>`) sits under `defineStore` — reach past the handle only for genuinely ad-hoc, one-off reactive scratch state (a transient UI flag) where a named handle would be overkill:
|
|
731
|
-
|
|
732
|
-
```ts
|
|
733
|
-
ctx.game.store.set("health", 100) // any key, any value type
|
|
734
|
-
ctx.game.store.get("health") // unknown — cast at the call site (the smell defineStore removes)
|
|
735
|
-
ctx.game.store.has("health") / delete("health") / subscribe(listener)
|
|
736
|
-
```
|
|
737
|
-
|
|
738
|
-
## `ctx.game.cards` / `ctx.game.turn` — lazily-created piles and turn loops
|
|
739
|
-
|
|
740
|
-
`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.
|
|
741
|
-
|
|
742
|
-
## Movement, pose, input
|
|
743
|
-
## External data — `data/dataSource` and the dev proxy
|
|
744
|
-
|
|
745
|
-
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.
|
|
746
|
-
|
|
747
|
-
- **`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.
|
|
748
|
-
- **`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.
|
|
749
|
-
- **`createJsonDataSource<T>(url, options?)`** (`data/jsonDataSource`) — sugar combining the two above: a `DataSource<T>` whose `load` calls `fetchJson(url, options)`.
|
|
750
|
-
- **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.
|
|
751
|
-
|
|
752
|
-
## Multiplayer and the backend seam
|
|
753
|
-
## Genre cheat sheet
|
|
754
|
-
|
|
755
|
-
- **Voxel/crafting**: objects for blocks/machines, `voxel()`, `object.break`/`object.placeFromInventory`.
|
|
756
|
-
- **Tycoon/lab**: objects + `slotInventory`, `plots()`, configure via prompt → command.
|
|
757
|
-
- **Shooter**: `fireProjectile`/`settleProjectile`; grenades settle → `effect({ at, radius })`; `movement.poses`/`aim` + zoom modifier; `servers({ … })` + game-owned `server.mode`; loadout classes from commands.
|
|
758
|
-
- **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"`.
|
|
759
|
-
- **All combat games**: react to `entity.died` (feed/leaderboard/score) — never poll HP.
|
|
760
|
-
|
|
761
|
-
## Anti-patterns
|
|
762
|
-
|
|
763
|
-
| Wrong | Right |
|
|
764
|
-
|-------|-------|
|
|
765
|
-
| Player tuning in `defineGame` | Entity catalog `movement` + stats |
|
|
766
|
-
| `behaviors: […]` on place/spawn | Catalog entry |
|
|
767
|
-
| Engine `weapon.fire` / `consumable.use` / `combat.*` | `item.use` + catalog `use` → game handler |
|
|
768
|
-
| `ItemUseInput.to` for targets | `getTarget(from)` in handlers |
|
|
769
|
-
| `effect({ to })` for gunshots | `fireProjectile` + `settleProjectile` |
|
|
770
|
-
| Polling HP in `onTick` for kills | `entity.died` event |
|
|
771
|
-
| `combat.lootTable` / `loot.enemy` | `onDeath` on the entity that died |
|
|
772
|
-
| Hand-rolled `Math.random()` loot in commands | `lootTable()` + `ctx.game.loot.roll` |
|
|
773
|
-
| Hand-rolled `xpForLevel`/`levelFromXp` | `game/progression` `curve()` + `leveling()` |
|
|
774
|
-
| Hardcoded shop arrays | `item.trade.shops` + `tradableAt` |
|
|
775
|
-
| Kit seeding via scattered `put`/`grant` | `applyLoadout` |
|
|
776
|
-
| Per-user quest state hand-rolled | `game.quest.register` + binds |
|
|
777
|
-
| `useKillFeed` / per-domain feed hooks | `useFeed({ action })` |
|
|
778
|
-
| Raw keys in game logic | `defineGame` input actions |
|
|
779
|
-
| Positioning inside `ui/components/` or on primitives (`CurrencyPill className="absolute …"`) | Screen wrappers in `GameUI.tsx` only |
|
|
780
|
-
| Game UI classes without `@source` in host CSS | `@source` entries for your game dirs + `node_modules/@jgengine/{shell,react}` |
|
|
781
|
-
| One file per catalog entry / per brand | Dense `<domain>/catalog.ts` |
|
|
782
|
-
| Convex mutations called from game code | `commands.run` through the `GameBackend` transport |
|
|
783
|
-
| 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`) |
|
|
784
|
-
| 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 |
|
|
785
|
-
| Game nouns in this skill | Engine primitives + placeholder ids only |
|
|
786
|
-
| Per-body `setPose` every tick + a `despawn`/`spawn` respawn dance in `onNewPlayer` | `ctx.scene.entity.bind(key).sync(bodies, dt)` (see `jgengine-world`) |
|
|
787
|
-
|
|
788
|
-
## New-game definition of done
|
|
789
|
-
|
|
790
|
-
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.
|
|
791
|
-
|
|
792
|
-
- [ ] `game.config.ts` (`defineGame` from `@jgengine/shell/defineGame`) + `index.tsx` (barrel) + `main.tsx` (standalone host) + `loop.ts` + `game/content.ts`
|
|
793
|
-
- [ ] Catalogs: `game/entities/<role>/catalog.ts`, `game/items/<domain>/catalog.ts`, `game/objects/catalog.ts`; loot tables beside their domain
|
|
794
|
-
- [ ] Entity `stats` + `receive` orders aligned on the same stat ids; `role` set (drives targeting + camera)
|
|
795
|
-
- [ ] `game/items/use-handlers.ts` registered in `onInit`; handlers read `getTarget`/`aim`, never a target input
|
|
796
|
-
- [ ] `game/loadouts.ts` + `applyLoadout` in `onNewPlayer` (gated on `isNew`)
|
|
797
|
-
- [ ] `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**
|
|
798
|
-
- [ ] `onInit`: register handlers/loadouts/loot/quests, event listeners, feed binds, leaderboard tracks; `setupWorld`
|
|
799
|
-
- [ ] Player spawns with `id === ctx.player.userId`
|
|
800
|
-
- [ ] `game/ui/GameUI.tsx` owns layout; components use `@jgengine/react` hooks
|
|
801
|
-
- [ ] UI passes the **quality bar** above (contrast, scale, framing, genre fit) — not just hook wiring
|
|
802
|
-
- [ ] Camera tuned via `camera` in `defineGame({...})` — defaults untouched means the feel was never checked
|
|
803
|
-
- [ ] 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
|
|
804
|
-
- [ ] 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
|
|
805
|
-
- [ ] Co-located bun tests for pure game math (curves, cooldowns, spawn logic)
|
|
806
|
-
- [ ] Multiplayer via adapter config only; no direct backend calls
|
|
807
|
-
|
|
808
|
-
Report the above as the done-ledger (`jgengine-verify` → "The done-ledger"), not adjectives — a "done"/"premium"/"shipped" claim is the compacted `pass`/`fail`/`skipped(reason)` block, never "looks great."
|
|
809
|
-
|
|
810
|
-
## Quick reference
|
|
811
|
-
|
|
812
|
-
```
|
|
813
|
-
defineGame (shell) engine fields (assets, world, physics, inventories, input, systems, server, save, time, feed, multiplayer)
|
|
814
|
-
+ presentation fields (content, loop, GameUI, camera, …) — smart defaults fill the rest
|
|
815
|
-
defineGame (core) systems + loop composed; features OR-merged from system.feature
|
|
816
|
-
defineSystem id, tick (fixed|frame|interval|manual), events, create/start/update, save/replicate/reset/dispose
|
|
817
|
-
composeGameLoop compileSystemSchedule → installSystems; systems tick before residual loop.onTick
|
|
818
|
-
PlayableGame { game, content, loop, GameUI, camera, … } — runner contract
|
|
819
|
-
GameContext ctx.scene / ctx.game / ctx.player / ctx.item / ctx.camera / ctx.input + subscribe/version
|
|
820
|
-
scene.object place, remove, move, rotate, at, setVisual
|
|
821
|
-
scene.entity spawn, despawn, setPose, update; stats; targeting; effects;
|
|
55
|
+
## 4. Build and finish
|
|
822
56
|
|
|
57
|
+
Keep scene coordinates in the editor document, state serializable, randomness injected, and hot-path work bounded. Use `jgengine-verify` for evidence appropriate to the change. Inside this monorepo, `workflow` owns issue/PR completion. Visual polish work also uses the `jgengine-ui` quality reference.
|
|
823
58
|
|
|
59
|
+
**Required asset pass — completion is gated on real models.** A game is not done while its entities and props are still primitive markers or box placeholders when real models are available for them. Before claiming completion, run an asset pass: every placed entity has its `entityModels` set and every prop its `objectModels` set to real, resolved model refs — not primitive-shape markers. Scaffolds ship with `jgengine-assets` and `npx jgengine assets pull` installed but never auto-triggered, so this step is on you to run explicitly. `jgengine-assets` owns the how-to (sourcing, licensing, `assets pull`, catalog indexing, and resolving refs); load it for the workflow. If a game genuinely wants primitive shapes as its art direction, say so — otherwise unresolved markers/box props are unfinished, not a style.
|