threedog 0.2.0 → 0.2.1
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/README.md +4 -4
- package/core/Assets.js +12 -0
- package/core/Engine.js +13 -4
- package/core/describeRender.js +7 -1
- package/core/grid.js +127 -0
- package/core/gridLoad.js +19 -0
- package/core/loop.js +7 -2
- package/core/renamed.js +1 -0
- package/core/styleParts.js +9 -7
- package/docs/AI.md +28 -23
- package/docs/API.md +3 -3
- package/docs/CODEMAP.md +5 -3
- package/docs/COMMANDS.md +5 -3
- package/docs/CONVENTIONS.md +6 -6
- package/docs/api/assets.md +1 -0
- package/docs/api/characters.md +3 -2
- package/docs/api/engine.md +3 -3
- package/docs/api/style.md +7 -7
- package/docs/api/tools.md +3 -2
- package/docs/api/vegetation.md +1 -0
- package/docs/recipes/01-new-game.md +41 -43
- package/docs/recipes/02-npc.md +24 -24
- package/docs/recipes/03-items-pickups.md +4 -4
- package/docs/recipes/04-quests.md +23 -23
- package/docs/recipes/05-props-bake.md +5 -5
- package/docs/recipes/07-flow-scenes-pause.md +2 -2
- package/docs/recipes/08-weather-sky.md +5 -5
- package/docs/recipes/09-style-pack.md +35 -100
- package/docs/recipes/13-animation.md +22 -6
- package/docs/recipes/14-custom-module.md +6 -7
- package/docs/recipes/15-perf.md +8 -0
- package/docs/recipes/16-dev-bridge.md +7 -7
- package/docs/recipes/18-world.md +5 -2
- package/docs/recipes/19-shooting-picking.md +9 -8
- package/docs/recipes/20-content-actions-save.md +10 -10
- package/docs/recipes/22-shop-gold.md +16 -16
- package/docs/recipes/23-ops.md +2 -2
- package/docs/recipes/27-net.md +2 -2
- package/docs/recipes/28-terrain.md +2 -2
- package/docs/recipes/29-grid.md +47 -27
- package/docs/recipes/34-environment-lighting.md +2 -2
- package/docs/recipes/35-style-from-reference.md +41 -46
- package/docs/recipes/36-sky-ground-plant-looks.md +22 -20
- package/docs/recipes/37-terrain-look-hooks.md +34 -13
- package/docs/recipes/38-environment-look-hooks.md +47 -42
- package/docs/recipes/42-terrain-shape.md +1 -1
- package/docs/recipes/43-shader-patches-surface-looks.md +35 -20
- package/docs/recipes/44-water-weather-look-hooks.md +5 -5
- package/docs/recipes/45-cascaded-shadows.md +1 -1
- package/docs/recipes/46-blender-art-route.md +4 -4
- package/docs/recipes/47-island-snow-backdrop.md +4 -3
- package/docs/recipes/48-make-material.md +2 -2
- package/docs/recipes/49-game-module-contract.md +25 -25
- package/docs/recipes/51-capability-catalog.md +2 -2
- package/docs/recipes/52-look.md +43 -5
- package/docs/recipes/53-ground-up-close.md +58 -0
- package/examples/action/GAMEMAP.md +2 -2
- package/examples/action/main.js +3 -2
- package/examples/sheepisland/GAMEMAP.md +1 -1
- package/examples/styletest/content/npcs.js +1 -1
- package/examples/styletest/main.js +1 -1
- package/examples/world/content/npcs.js +1 -1
- package/examples/world/main.js +1 -1
- package/index.d.ts +8 -2
- package/index.js +3 -2
- package/llms.txt +9 -8
- package/modules/characters/Character.js +21 -19
- package/modules/characters/assetModel.js +35 -7
- package/modules/characters/proceduralRig.js +45 -10
- package/modules/content/index.js +1 -1
- package/modules/gameplay/pickups.js +1 -1
- package/modules/vegetation/Vegetation.js +15 -3
- package/modules/vegetation/index.js +1 -1
- package/modules/vegetation/nearFade.js +39 -0
- package/package.json +2 -1
- package/render/detail.js +39 -15
- package/types/core.d.ts +7 -5
- package/types/gameplay.d.ts +12 -6
- package/types/style.d.ts +20 -15
- package/types/world.d.ts +7 -1
package/docs/CONVENTIONS.md
CHANGED
|
@@ -108,8 +108,8 @@ inside template strings, which then throw on the first call).
|
|
|
108
108
|
|
|
109
109
|
## Core conventions
|
|
110
110
|
- Lighting without `sky`: every engine has `engine.lights = { sun, hemi }` (neutral); to light the scene yourself hide or adjust them and add three.js
|
|
111
|
-
lights. The engine ships no art: the humanoid, pickup shapes and flat shading
|
|
112
|
-
|
|
111
|
+
lights. The engine ships no art: the humanoid, pickup shapes and flat shading belong to a style pack or asset pack you add (e.g.
|
|
112
|
+
a pack with `terrain.config.shading: 'flat'`); without a style pack or model the engine shows a gray capsule, a gray box and flat gray ground at y
|
|
113
113
|
= 0, with a dev warning naming the fix.
|
|
114
114
|
- Gameplay state (world, containers, vars, quests) changes only in fixed steps or inside ops; dev warns otherwise (`.threedog/ops-guard.log` after
|
|
115
115
|
`npm test`). (game side)
|
|
@@ -125,7 +125,7 @@ inside template strings, which then throw on the first call).
|
|
|
125
125
|
(`recipes/20-content-actions-save.md` "Save format").
|
|
126
126
|
- Day / night comes only from sky: read `sky.isDay`, use `sky.daylight` (0-1) for fades; don't judge by clock time yourself.
|
|
127
127
|
- A game's own look parameters (colors, materials) belong in its style pack (`style`) or the content, never hard-coded into logic.
|
|
128
|
-
- Whatever a style pack provides as a factory can also be passed at the call site, and the call site wins (`
|
|
128
|
+
- Whatever a style pack provides as a factory can also be passed at the call site, and the call site wins (`spawnPickup(item, pos, { mesh })` over `style.pickup.model`); look-driven parts (sky, clouds, water, materials) are overridden with `engine.look.<part>.set / patch / replace`. A new style factory must ship with its call-site option.
|
|
129
129
|
- Vegetation `rule` must not contain functions (it is sent to a Worker).
|
|
130
130
|
- Terrain is editable: `engine.terrain.edit(pos, { lower|raise|flatten|paint })`, only inside an op or fixed step; custom
|
|
131
131
|
`terrain({ height, groundType })` must be pure functions.
|
|
@@ -133,9 +133,9 @@ inside template strings, which then throw on the first call).
|
|
|
133
133
|
never removes its world record.
|
|
134
134
|
- Window blur, tab hidden, pointer lock and WebGL context loss are listened to only in `core/page.js`; modules read `engine.page` or listen to
|
|
135
135
|
`page:*`. Show "saved" only after `saves.save` returns true.
|
|
136
|
-
-
|
|
137
|
-
now
|
|
138
|
-
|
|
136
|
+
- Character bodies are assets, not style: `createPlayer({ ...presets.player.thirdPerson, model: 'humanoid' | 'hero' })` (a procedural builder is built
|
|
137
|
+
now; a file shows a gray capsule and is swapped in when it loads: `await player.whenReady`, event `character:model`), or `{ rig }`; a name no model
|
|
138
|
+
asset has throws. Style packs tint bodies through material roles (cloth, skin, trousers, hair).
|
|
139
139
|
- Importing the engine makes `Mesh.prototype.customDepthMaterial` / `customDistanceMaterial` default to a depth material carrying the mesh material's
|
|
140
140
|
vertex patches, so wind-swayed meshes cast swaying shadows with nothing to set up; assigning your own value still wins. Shader time, wind and cloud
|
|
141
141
|
cover are per engine in `engine.uniforms` (share them in your own `ShaderMaterial`); with two engines on a page, pass the engine to
|
package/docs/api/assets.md
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
- `assets.model(nameOrUrl: string, opts?: { castShadow?, receiveShadow?, static? }) → Promise<Object3D>` — Get a model copy (name or path; geometry and materials are shared with other copies). static: true registers it in engine.rays (builds ray acceleration)
|
|
8
8
|
- `assets.modelNow(nameOrUrl: string, opts?: { castShadow?, receiveShadow?, static? }) → Object3D | null` — A model copy right now if it has already loaded, else null (never starts a load, never waits): lets code that rebuilds often skip the frame an await costs. Example: `const m = engine.assets.modelNow('villager') ?? await engine.assets.model('villager');`
|
|
9
9
|
- `assets.geometry(nameOrUrl: string) → Promise<BufferGeometry>` — Get the geometry of the first mesh in a model
|
|
10
|
+
- `assets.gridFromImage(nameOrUrl: string, opts?: { channel?, range?, bits? }) → Promise<{ data: Float32Array; wid…` — An image as grid data for sampleGrid: PNG at 8 or 16 bits (jpg / webp 8). channel 'r' (default) 'g' 'b' 'a' or 0-3; range maps pixels to [min, max] (default [0, 1])
|
|
10
11
|
- `assets.texture(nameOrUrl: string, opts?: { color?, pixelated?, repeat? }) → Promise<Texture>` — Get a texture (.ktx2 compressed textures also work)
|
|
11
12
|
- `assets.release(name: string)` — Release a resource and return GPU memory. Not released while copies of the model are still in the scene; it is released when the last copy is removed with engine.remove
|
|
12
13
|
- `assets.trim() → string[]` — Release every model that has no copy in use (called automatically after level changes). Models whose shared geometry was taken by geometry() / cached() are not released automatically. Returns the released names
|
package/docs/api/characters.md
CHANGED
|
@@ -106,7 +106,7 @@ Characters: createPlayer() (characters() module)
|
|
|
106
106
|
- `control: PlayerControl` Required, no default: 'camera' (keys relative to the camera) / 'none' (call player.move() yourself in onFixed) / (player, input, dt) => ({ x, z, run?, speed? }). Also the runtime property player.control. presets.player.* fill it
|
|
107
107
|
- `cameraFollow?: boolean` true: the camera module follows the player (and back after a vehicle, and on a new session). Omitted with a camera installed warns in dev
|
|
108
108
|
- **CharacterOptions** Character parameters (shared by the player and NPCs)
|
|
109
|
-
- `colors?: { body?, skin?, legs?, hair? }`
|
|
109
|
+
- `colors?: { body?, skin?, legs?, hair? }` Per-character part colors: recolor the body's meshes marked userData.part (a humanoid rig: body, skin, legs, hair); the style tints by material role
|
|
110
110
|
- `speed?: number` Walking speed (m/s), default 4.5
|
|
111
111
|
- `runSpeed?: number` Running speed (m/s), default 7
|
|
112
112
|
- `radius?: number` Collision radius (meters), default 0.4
|
|
@@ -121,7 +121,8 @@ Characters: createPlayer() (characters() module)
|
|
|
121
121
|
- `airControl?: number` Air control, 0–1
|
|
122
122
|
- `coyoteTime?: number` How long after walking off an edge a jump is still allowed (seconds)
|
|
123
123
|
- `canJump?: boolean` Whether it can jump, default true
|
|
124
|
-
- `model?: Object3D | string | null`
|
|
124
|
+
- `model?: Object3D | string | null` The body, one path for every kind: the name of a registered model asset, or what engine.assets.model() returned. A procedural builder name (from an asset pack) is built at once; a file model name shows a gray capsule and swaps in a copy when it loads (Character.ready / whenReady, event 'character:model'). Example: `engine.assets.manifest(yourAssets); engine.characters.createPlayer({ model: 'yourBody' }) // a generator or GLB name from an asset pack`
|
|
125
|
+
- `rig?: CharacterRig | null` A ready procedural body (CharacterRig), used instead of model (a hand-built guard / pet)
|
|
125
126
|
- `clips?: { idle?, walk?, run?, swim?, jump?, fall?, … } | null` Action name mapping { idle, walk, run, swim, jump, fall } (shorthand for animation)
|
|
126
127
|
- `animation?: AnimatorOptions | null` Skeletal animation state machine config (states, blend trees, one-shot actions), see AnimatorOptions
|
|
127
128
|
- `mover?: 'simple' | 'rapier'` Movement method: 'simple' built into the engine (default) / 'rapier' Rapier character controller (needs the rigid module)
|
package/docs/api/engine.md
CHANGED
|
@@ -4,13 +4,13 @@
|
|
|
4
4
|
- Options `EngineOptions`:
|
|
5
5
|
- `canvas?: HTMLCanvasElement | HTMLElement` Canvas element (required unless renderer is given), e.g. document.getElementById('view')
|
|
6
6
|
- `renderer?: any` A ready three.js renderer (WebGLRenderer or compatible) to use instead of creating one; canvas then defaults to renderer.domElement. The engine configures (pixel ratio, size, tone mapping, shadows) only a renderer it created itself. WebGL is the fully supported path; WebGPU-style renderers may not run shader patches or post effects (recipe 48)
|
|
7
|
-
- `style?: StyleInput` Style pack (looks only: materials, sky, lighting, post, UI look),
|
|
7
|
+
- `style?: StyleInput` Style pack (looks only: materials, sky, lighting, post, UI look), a pack you made or installed (import basePack from 'your-pack'), or a list of parts deep-merged left to right: [basePack, { sky: { sunSize: 600 } }]. Without one: neutral gray placeholders
|
|
8
8
|
- `shadows?: boolean` Real-time shadows, default true
|
|
9
9
|
- `shadowType?: 'basic' | 'pcf' | 'vsm'` Shadow filter: 'basic' (hard edge) / 'pcf' / 'vsm' (softest, costliest), default 'pcf'. Change later with engine.look.shadow.set({ type })
|
|
10
10
|
- `antialias?: boolean` MSAA anti-aliasing (kept with post effects on), default style.antialias, else on for desktop and off for low-tier devices
|
|
11
11
|
- `post?: Record<string, boolean>` Turn style post effects on or off by name at startup, e.g. { bloom: false }; default: each effect's own setting (costly ones off on low-tier devices)
|
|
12
|
-
- `pixelRatio?: number` Render resolution, default min(device pixel ratio, 1.5)
|
|
13
|
-
- `adaptiveResolution?: boolean` Automatically lower resolution when the frame rate is too low, default true
|
|
12
|
+
- `pixelRatio?: number` Render resolution, default min(device pixel ratio, 1.5); the low tier uses at least 0.75 x device pixel ratio (never below 1). describe().render.scale reports it
|
|
13
|
+
- `adaptiveResolution?: boolean` Automatically lower resolution when the frame rate is too low, default true. Never silent: a dev warning once, and describe().render.scale.autoLowered
|
|
14
14
|
- `targetFps?: number` Target frame rate for automatic resolution lowering, default 55
|
|
15
15
|
- `ui?: Record<string, UIPartValue>` UI parts: replace or turn off any piece of screen UI (loading, toast, title, hud.marker, hud.counter, hud.bar). Default title screen is off. Example: `createEngine({ canvas, ui: { loading: { title: 'My Game' }, title: { title: 'My Game' }, toast: false } })`
|
|
16
16
|
- `audio?: AudioConfig` Volume of each channel, 0–1
|
package/docs/api/style.md
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
# Style pack Style — createEngine({ style }), all the look (
|
|
1
|
+
# Style pack Style — createEngine({ style }), all the look (any style pack: a folder with index.js; recipes/09-style-pack.md)
|
|
2
2
|
|
|
3
3
|
- **Style** fields (all optional):
|
|
4
4
|
- `name?: string` Style pack name
|
|
5
|
-
- `exposure?: number | number[][] | ((sky: any) => number)` Exposure, default 1
|
|
6
|
-
- `toneMapping?: Loose<'aces' | 'agx' | 'neutral' | 'none'>` Tone mapping. Engine default 'none' (no style pack, no tone mapping); the style pack picks the look
|
|
5
|
+
- `exposure?: number | number[][] | ((sky: any) => number)` Exposure, default 1: a number, or over the day [[time 0-1, exposure], ...] (sorted, wraps across midnight) or (sky) => number, evaluated by the sky module every frame. engine.look.tone.set changes it at run time. Example: `exposure: [[0, 1.6], [0.3, 1], [0.75, 1.1]] // brighter nights`
|
|
6
|
+
- `toneMapping?: Loose<'aces' | 'agx' | 'neutral' | 'none'>` Tone mapping. Engine default 'none' (no style pack, no tone mapping); the style pack picks the look
|
|
7
7
|
- `background?: ColorLike` Background color (when there is no sky module)
|
|
8
8
|
- `post?: (Omit<import('./generate… & { slot? })[]` Post effects registered at startup, in any order (slot and order decide where each runs), e.g. [outline({ enabled: true }), bloom()] from '@threedog/post-effects'
|
|
9
9
|
- `materials?: Record<string, MaterialSpec | import('three').Material | ((…` Material per role (default, terrain, vegetation, character, water, building, pickup…): a spec, a three.js Material instance (cloned per use), or a function (params, purpose) => Material
|
|
10
10
|
- `antialias?: boolean` Anti-aliasing: true = MSAA (also inside post-processing), false = off (pixel art, sharp edges). Default: on for desktop, off for low tier; createEngine({ antialias }) wins
|
|
11
11
|
- `lighting?: MaterialLighting` Light shaping for every lit material of the pack (shadow tint, rim, wrap, glsl); a material's `lighting` wins, `lighting: false` opts out
|
|
12
12
|
- `seasons?: StyleSeasons` Seasonal tint: { spring: { foliage, ground }, ... }. mode 'multiply' (default) multiplies the color onto the surface (pick tints near white: orange times green is muddy); 'mix' moves the surface `strength` (0-1, default 0.5) of the way to the color. Season names are the other keys, so none can be called mode or strength
|
|
13
|
-
- `clouds?: { shadow?: number; scale?: number; speed?: number[] }` Cloud shadow: shadow darkest level 0–1 (default 0 = no cloud shadows
|
|
14
|
-
- `palette?: Record<string, ColorLike>` Named colors the procedural model generators read (trees, rocks, grass: a generator written with `function` gets them as this.palette;
|
|
13
|
+
- `clouds?: { shadow?: number; scale?: number; speed?: number[] }` Cloud shadow: shadow darkest level 0–1 (default 0 = no cloud shadows), scale cloud size (smaller means bigger clouds), speed [x, z]
|
|
14
|
+
- `palette?: Record<string, ColorLike>` Named colors the procedural model generators read (trees, rocks, grass: a generator written with `function` gets them as this.palette; a pack may use keys like bark, pine, leaf, rock, grassTip...). One place to retint all of them, e.g. style: [basePack, { palette: { leaf: 0xd98a3a } }]; keys left out keep the pack's values
|
|
15
15
|
- `wind?: StyleWind` Wind: frequency sway frequency multiplier
|
|
16
16
|
- `terrain?: StyleTerrain` Terrain colors etc.
|
|
17
17
|
- `sky?: StyleSky` Sky
|
|
18
18
|
- `weather?: StyleWeather` Weather look
|
|
19
19
|
- `water?: StyleWater` Water look
|
|
20
20
|
- `pickup?: { color?, size?, lift?, model? }` Default look of pickups on the ground: color (the item's own color wins), size (meters), lift height above ground (meters), model(item, { color, size }, engine) builds the shape (a geometry gets materials.pickup; make materials with engine.makeMaterial; without model a plain box)
|
|
21
|
-
- `character?: {
|
|
21
|
+
- `character?: { animation?: { fade?: number } }` How character motion looks: animation.fade skeletal animation transition seconds. Bodies are assets, not style ({ model: 'yourBody' } from an asset pack); a style tints body parts through materials roles (cloth, skin, trousers, hair). create / model / colors here throw renamed-api
|
|
22
22
|
- `ui?: StyleUI` UI colors, fonts, templates
|
|
23
23
|
- `particles?: Record<string, ParticleOptions>` Particle presets: name → parameters; default is the fallback for all effects
|
|
24
24
|
- `triggers?: { debugColor?: ColorLike; debugOpacity?: number }` Trigger zone debug wireframe
|
|
@@ -99,7 +99,7 @@
|
|
|
99
99
|
- `variation?: { blend?, jitter?, patches? }` How ground colors vary (plain data, sent to the terrain workers). Every default is the original look; set only what you want to change. blend: the two-color noise (size = wavelength in meters, default 33; strength = contrast, default 1). Example: `variation: { blend: { size: 14 }, jitter: { range: 0.04 }, patches: { size: 60, strength: 0.25, levels: 4, tint: 0xb59a5a } }`
|
|
100
100
|
- `config?: { shading?, colorResolution?, normals?, normalFn? }` Looks of the ground mesh only. shading: 'flat' one color and normal per triangle (facets) / 'smooth' (engine default) / 'texture' (per-chunk color map, colors independent of the mesh); colorResolution: color map pixels per chunk edge; normals: 'smooth' / 'flat' lighting in texture mode; normalFn: custom grid-point normal.
|
|
101
101
|
- `material?: Material | ((engine: Engine) => Material)` Whole ground material: a Material or (engine) => Material (uv = world xz / chunk size; terrain({ material }) wins)
|
|
102
|
-
- `detail?:
|
|
102
|
+
- `detail?: MaterialDetail` Detail layer over the ground, the same object as a material spec's `detail`: a noise ('grain' / 'paper' / 'stroke' / 'dabs'), a texture asset name, or your own `glsl`; plus scale, strength, fade ... (top-down world projection by default). Live: look.ground.set({ detail }). See recipes/53-ground-up-close.md
|
|
103
103
|
- **StyleUI**
|
|
104
104
|
- `bg?: string` Background color
|
|
105
105
|
- `fg?: string` Text color
|
package/docs/api/tools.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# Utility functions (imported from threedog)
|
|
2
2
|
|
|
3
|
-
- `postAdd(...effects: PostEffect[]) → Style` — A style part that adds post effects to the ones before it (a plain { post: [...] } would replace the whole list); an effect with the same name replaces that one in place. Style parts with it: createEngine({ style: [
|
|
4
|
-
- `postRemove(...names: string[]) → Style` — A style part that removes post effects by name from the ones before it: createEngine({ style: [
|
|
3
|
+
- `postAdd(...effects: PostEffect[]) → Style` — A style part that adds post effects to the ones before it (a plain { post: [...] } would replace the whole list); an effect with the same name replaces that one in place. Style parts with it: createEngine({ style: [basePack, postAdd(myGrain, bloom({ strength: 0.6 }))] })
|
|
4
|
+
- `postRemove(...names: string[]) → Style` — A style part that removes post effects by name from the ones before it: createEngine({ style: [basePack, postRemove('ao', 'outline')] })
|
|
5
5
|
- `presets: { weather, calendar, player, interactions, keys, camera }` — Opt-in gameplay presets: named option objects a game picks on purpose (the engine never applies one itself). Each only bundles options the game could write; spread and override: weather({ ...presets.weather.temperate, autoPool: ['clear', 'rain'] })
|
|
6
6
|
- `world(opts?: { cellSize?, radius?, farEvery?, farMaxPerTick?, buildPerFrame? }) → import("../../../core").ModuleDef…` — World data module: installed as engine.world. Put things here that must be saved, survive level changes and keep changing while far away; models are only built while nearby
|
|
7
7
|
- `net(opts?: { role, transport, sync?, syncEvery?, keepAlive?, rate?, … }) → import("../../../core").ModuleDef…` — (experimental) Optional co-op multiplayer: one host owns the state, clients mirror it and ask for changes through ops. Installed as engine.net. Host: peers' requests run as `ops.run(name, args, { source: 'net', actor })` only for ops defined with net: 'peer', with the op's args shape checked, the optional owner check, and a per-peer rate limit; the result comes back after the state diff that contains it. State: world records, containers, vars and the other save parts are sent as a snapshot on join and as diffs every syncEvery steps. Client: ops.run of a peer op returns { ok: true, pending: true, seq } (watch state or the net:result event, not the return value); its own avatar moves locally and is sent to the host (clamped to maxSpeed); other avatars glide between updates.
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
- `grids() → import("../../../core").ModuleDef…` — (experimental) Grid placement module: installed as engine.grids. Needs world(). Adds the ops grid.place / grid.remove / grid.move and the save key 'grids' (layers).
|
|
11
11
|
- `screenToGround(engine: Engine, ndcX: number, ndcY: number, opts?: { maxDistance?: number }) → Vector3 | null` — Screen coordinates (-1..1) -> point on the ground; null if the ray misses the ground
|
|
12
12
|
- `EASINGS: Record<EaseName, (t: number) => number>` — All easing functions: name -> function
|
|
13
|
+
- `sampleGrid(data: ArrayLike<number>, opts: { width, height, cellSize?, size?, origin?, interp?, … }) → (x: number, z: number) => number` — A grid of numbers (height, moisture, density, walkable...) as a function (x, z) -> value. data[j * width + i] sits at origin + (i, j) * cell. interp 'nearest' = flat steps, 'linear' (default) = bilinear, 'cubic' = smooth (clamp: true avoids overshoot). Outside: edge value, or `outside`.
|
|
13
14
|
- `ease(e: Ease) → (t: number) => number` — Name or function -> easing function
|
|
14
15
|
- `checkOptions(where: string, opts: object | null | undefined, known: string[], flags?: { loose?: boolean })` — Warn (once, in development) about unknown keys in an options object, with a "did you mean" hint. For your own modules. where names the call ('stamina()'); known lists the keys your code reads; loose only warns on near-misses (data with game-specific fields).
|
|
15
16
|
- `readParams(where: string, schema: Record<string, ParamSpec>, opts?: object) → T` — Module options read through a params schema: unknown keys and wrong types throw in dev with the fix, defaults are filled in. Also put params / options on the module definition so engine.catalog(name) shows them (recipes/51-capability-catalog.md).
|
package/docs/api/vegetation.md
CHANGED
|
@@ -27,6 +27,7 @@ Vegetation (vegetation() module; grows on terrain or on any ground provider)
|
|
|
27
27
|
- `wind?: number` Wind sway amplitude, 0 = still
|
|
28
28
|
- `nearOnly?: boolean` Only generated near the player (grass, flowers)
|
|
29
29
|
- `maxRing?: number` No longer drawn beyond this many rings
|
|
30
|
+
- `fade?: false | { start?: number; end?: number }` Distance fade of a near-only species (grass, flowers, pebbles, debris ...): instances shrink out over a band in metres from the player instead of popping per chunk at the ring edge. Default for nearOnly: end = maxRing x chunk size, start = 65% of it. `false` keeps the hard ring edge (also the default for species that are not nearOnly).
|
|
30
31
|
- `lodRing?: number` Switch to the low-detail model beyond this many rings, default 1
|
|
31
32
|
- `castShadow?: boolean` Cast shadows
|
|
32
33
|
- `shadowRing?: number` Cast shadows within this many rings
|
|
@@ -1,52 +1,50 @@
|
|
|
1
1
|
# Starting a new game (a workspace under games/)
|
|
2
2
|
|
|
3
|
-
Goal: create `games/
|
|
4
|
-
template (`npx threedog new-game
|
|
3
|
+
Goal: create `games/my-game/` (pick your own name) with its own page, modules, content data and tests, independent of other games. Start from the
|
|
4
|
+
template (`npx threedog new-game my-game`, section 0); the engine's own example is `examples/world/` in the package.
|
|
5
5
|
|
|
6
6
|
## 0. One-command setup (preferred)
|
|
7
7
|
```
|
|
8
|
-
npm run new-game my-
|
|
9
|
-
npm run new-game my-
|
|
8
|
+
npm run new-game -- my-game # clean start: ground, player, follow camera, sky; no gameplay
|
|
9
|
+
npm run new-game -- my-game --example # the sample: hp / hunger, a rest op, apples, a searchable stash, a HUD counter
|
|
10
|
+
npm run new-game -- my-game --style ./packs/mine # a style pack of your own (path) or a published one (package name) instead of the empty style/ folder
|
|
10
11
|
```
|
|
11
|
-
(npm
|
|
12
|
-
without `-- --blank`. The CLI form takes the flag directly: `npx threedog new-game my-farm --blank`.)
|
|
12
|
+
(The `--` matters: without it npm swallows the flags. The CLI form takes them directly: `npx threedog new-game my-game --example`. `--example` uses engine placeholders (gray box, capsule), so it works with any style.)
|
|
13
13
|
The name may only contain lowercase letters, digits and dashes; an existing directory under `games/` with the same name is refused. What it does:
|
|
14
|
-
1. Copies `packages/tools/templates/game/` to `games/my-
|
|
15
|
-
2. Creates the `node_modules/@threedog/my-
|
|
14
|
+
1. Copies `packages/tools/templates/game/` to `games/my-game/` (`__NAME__` in the files is replaced by the name); `--example` copies `templates/example/` over it first.
|
|
15
|
+
2. Creates the `node_modules/@threedog/my-game` link and updates the workspace entry in `package-lock.json` (if offline, only a warning).
|
|
16
16
|
3. Runs `map` (generates GAMEMAP.md), `check` and the game's smoke test in turn. Any failing step stops and says why.
|
|
17
17
|
|
|
18
|
-
The
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
`player.rest` op, the `onFixed` hunger timer, the HP counter in `onFrame` and the `stash.search` op; remove `sky: presets.calendar.cycle` if the
|
|
25
|
-
game has no day cycle. `spawn` and `places` take any `{ x, z }` (or `{ x, y, z }`); `findSpawn` is only for generated terrain.
|
|
18
|
+
The default game is deliberately empty: `openWorld` (terrain, follow camera, sky) + `content()`, a player, content files that are empty arrays / objects (each
|
|
19
|
+
has one comment line saying what goes there and which recipe teaches it), and an empty style pack in `style/index.js` (every section is a commented-out stub;
|
|
20
|
+
with it empty the engine shows gray placeholders; fill it with your own art using recipes 09 and 52). `CLAUDE.md` says "This game has no gameplay yet; build what DESIGN.md describes".
|
|
21
|
+
`--example` adds the patterns: `interactions / inventory / hud`, 3 apples on the ground and one stash (a template in `content/templates.js` placed by
|
|
22
|
+
`content/props.js`, searched through the op `stash.search`); its `main.js` shows the game's own state registered with `describe.add` and `saves.register`, an op
|
|
23
|
+
with `can` / `run`, and the `onFixed` / `onFrame` split. `spawn` and `places` take any `{ x, z }` (or `{ x, y, z }`); `findSpawn` is only for generated terrain.
|
|
26
24
|
To change the camera: `openWorld({ camera: 'firstPerson' })` (`follow` / `firstPerson` / `rts` / `fixed`, or pass a camera module directly; there is
|
|
27
25
|
no default).
|
|
28
26
|
- The comments in `main.js` list further gameplay modules you can add; usage is in `../api/<module>.md`.
|
|
29
|
-
- To change the starting point of new games, edit the real files in `packages/tools/templates/game
|
|
27
|
+
- To change the starting point of new games, edit the real files in `packages/tools/templates/game/` (and `templates/example/` for the sample).
|
|
30
28
|
- `DESIGN.md` is an empty template: write your gameplay ideas there. `CLAUDE.md` only points the way (read `node_modules/threedog/docs/AI.md` first,
|
|
31
29
|
then GAMEMAP, DESIGN) and does not copy engine rules.
|
|
32
|
-
- There is no `tests/`: when `tests/specs.mjs` does not exist, `npm test -w games/my-
|
|
30
|
+
- There is no `tests/`: when `tests/specs.mjs` does not exist, `npm test -w games/my-game` runs a smoke test automatically.
|
|
33
31
|
|
|
34
32
|
## 1. Creating the files by hand (to learn what each file is, or when the template doesn't fit)
|
|
35
33
|
| File | Content |
|
|
36
34
|
|---|---|
|
|
37
|
-
| `games/
|
|
38
|
-
| `games/
|
|
39
|
-
| `games/
|
|
40
|
-
| `games/
|
|
41
|
-
| `games/
|
|
42
|
-
| `games/
|
|
43
|
-
| `games/
|
|
44
|
-
| `games/
|
|
45
|
-
| `games/
|
|
35
|
+
| `games/my-game/package.json` | Copy `package.json` from the game template (or run `npx threedog new-game my-game`) and set `name` to `@threedog/my-game` (dependencies `threedog`, `@threedog/tools`, plus `@threedog/terrain-noise`, and your style pack (and `@threedog/post-effects` if the pack uses it) only when `main.js` imports it; the default style is the game's own `style/index.js`; scripts dev/build/preview/test/check/map) |
|
|
36
|
+
| `games/my-game/vite.config.js` | One line: `export default gameConfig(import.meta.dirname)` (imported from `@threedog/tools/vite`); *.html files in the directory are bundled automatically, no `input` needed. Without `@threedog/tools`, a plain vite config needs `worker: { format: 'es' }` (the engine's Workers are ES modules) or `vite build` fails; `threedog dev / build` on a folder with no vite config uses the preset |
|
|
37
|
+
| `games/my-game/index.html` | The page: one `<canvas id="view">` with a CSS size + `/main.js` (for more pages put `xxx.html` in the same directory); see §5 for embedding |
|
|
38
|
+
| `games/my-game/main.js` | Install modules, compute places, `content.load`, game-specific logic |
|
|
39
|
+
| `games/my-game/content/index.js` | Combines the content files into one object |
|
|
40
|
+
| `games/my-game/content/*.js` | Only these names are read: items pickups containers npcs dialogues quests actions places triggers level vegetation props templates audio grids renames rules, plus the game's own kinds (rules.js) |
|
|
41
|
+
| `games/my-game/DESIGN.md` | Hand-written design decisions (a few lines of `- **decision**: reason`), copied into GAMEMAP.md |
|
|
42
|
+
| `games/my-game/CLAUDE.md` | A few lines: read `node_modules/threedog/docs/AI.md`, then this directory's GAMEMAP.md and DESIGN.md (copy the template's) |
|
|
43
|
+
| `games/my-game/public/` | This game's art assets (URL `/models/...`); keep Blender source files in `games/my-game/art/models/`, `npm run assets -- -w my-game` compresses them over |
|
|
46
44
|
|
|
47
45
|
After creating them, run `npm install` once at the repository root (this links the new game into the workspaces so `threedog` can find it).
|
|
48
46
|
|
|
49
|
-
Outside the engine repository, a game installs `threedog` and `three` (plus
|
|
47
|
+
Outside the engine repository, a game installs `threedog` and `three` (plus your style pack, `@threedog/post-effects` / `@threedog/terrain-noise` if it imports them,
|
|
50
48
|
and `@threedog/tools` as a dev dependency for the CLI and the vite preset). To use an engine folder on disk instead of npm, install it with
|
|
51
49
|
`npm install --install-links <folder>`: a plain link skips the engine's own dependencies (Rapier, Recast) and the build cannot resolve them.
|
|
52
50
|
|
|
@@ -56,23 +54,23 @@ In a game's own repository, `threedog check`, `types` and `map` read only the ga
|
|
|
56
54
|
The template's `tsconfig.json` checks the game files only (`checkJs`), with `lib` ESNext + DOM (dependency typings such as Rapier's use
|
|
57
55
|
`Symbol.dispose`) and `skipLibCheck: true`; without a tsconfig, `threedog types` writes the same settings to `.threedog/tsconfig.types.json`.
|
|
58
56
|
|
|
59
|
-
`games/
|
|
57
|
+
`games/my-game/index.html` (minimal; the template's `index.html` has the same page with loading styles):
|
|
60
58
|
```html
|
|
61
59
|
<!doctype html>
|
|
62
|
-
<html lang="
|
|
63
|
-
<title
|
|
60
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
61
|
+
<title>My game</title><style>html,body{height:100%;margin:0;overflow:hidden;background:#141a17}#view{position:fixed;inset:0;width:100%;height:100%;display:block;outline:none}</style>
|
|
64
62
|
</head><body><canvas id="view" tabindex="0"></canvas><script type="module" src="/main.js"></script></body></html>
|
|
65
63
|
```
|
|
66
64
|
|
|
67
|
-
`games/
|
|
65
|
+
`games/my-game/main.js`:
|
|
68
66
|
```js
|
|
69
|
-
//
|
|
67
|
+
// my-game: ... (this first comment line appears in the file table of GAMEMAP.md)
|
|
70
68
|
import { createEngine, presets, openWorld, interactions, dialogue, inventory, quests, entities, content } from 'threedog';
|
|
71
|
-
import
|
|
69
|
+
import style from './style/index.js'; // the game's own style pack (the engine ships no art)
|
|
72
70
|
import { terrainPreset } from '@threedog/terrain-noise'; // optional terrain generator (nor a world shape)
|
|
73
71
|
import data from './content/index.js';
|
|
74
72
|
|
|
75
|
-
const engine = createEngine({ canvas: document.getElementById('view'), style
|
|
73
|
+
const engine = createEngine({ canvas: document.getElementById('view'), style, ui: { loading: { title: 'My game' } }, saveKey: 'my-game' });
|
|
76
74
|
// the preset only covers world and environment; the debug panel is installed in dev builds only (debug: true forces it in release too)
|
|
77
75
|
engine.use(openWorld({ camera: 'follow', seed: 42, terrain: terrainPreset(), time: 0.3 }),
|
|
78
76
|
// add gameplay modules as the game needs (a shooter has no inventory)
|
|
@@ -97,7 +95,7 @@ otherwise English) unless you set `createEngine({ locale })`. A game without ter
|
|
|
97
95
|
the level generator function under `models` in `engine.assets.manifest({ name, models })`, use `level({ url: name })` and pick your own modules, then
|
|
98
96
|
create the player and install content in `level:loaded`.
|
|
99
97
|
|
|
100
|
-
`games/
|
|
98
|
+
`games/my-game/content/index.js`:
|
|
101
99
|
```js
|
|
102
100
|
import items, { startItems } from './items.js';
|
|
103
101
|
import places from './places.js';
|
|
@@ -106,13 +104,13 @@ export default { items, startItems, places };
|
|
|
106
104
|
`content/places.js`: `export default { home: 'flat ground found at the start (coordinates computed in main.js)' };`
|
|
107
105
|
|
|
108
106
|
## 2. Verify
|
|
109
|
-
1. `npm run map` -> generates `games/
|
|
107
|
+
1. `npm run map` -> generates `games/my-game/GAMEMAP.md`; check the "engine modules" and "page /" sections.
|
|
110
108
|
2. `npm run check` -> content validation points out wrong file names, ids and clock-time formats; `npm run types` finds misused engine APIs.
|
|
111
|
-
3. `npm run shot -- -w
|
|
112
|
-
4. `npm test -w games/
|
|
113
|
-
test gameplay, write `games/
|
|
114
|
-
5. To see the picture: `npm run shot -- -w
|
|
115
|
-
`npm run dev --
|
|
109
|
+
3. `npm run shot -- -w my-game / --describe-only` -> the text has a `player` line with its position, the module list, and no "still loading".
|
|
110
|
+
4. `npm test -w games/my-game` -> without `tests/specs.mjs` it runs a smoke test (the page opens, the engine is ready, the console has no errors); to
|
|
111
|
+
test gameplay, write `games/my-game/tests/specs.mjs` in the style of the engine repository's `packages/engine/tests/specs.mjs`.
|
|
112
|
+
5. To see the picture: `npm run shot -- -w my-game /` (one image in `games/my-game/.threedog/shots/`); while developing run `npm run dev -w games/my-game` (or
|
|
113
|
+
`npm run dev -- my-game`) and open the printed address; read errors in `games/my-game/.threedog/errors.log`.
|
|
116
114
|
|
|
117
115
|
## 3. Preset parts
|
|
118
116
|
Every `openWorld()` part takes `false` or its module's options object, for example
|
|
@@ -145,4 +143,4 @@ root is laid exactly over it. So the layout decides:
|
|
|
145
143
|
<section style="position:relative;width:640px;height:360px"><canvas id="view" style="width:100%;height:100%;display:block"></canvas></section> <!-- in a page -->
|
|
146
144
|
```
|
|
147
145
|
A canvas with no CSS size takes its size from its own pixel buffer, which would grow on every resize; the engine then sizes it to the window and warns
|
|
148
|
-
once in dev. The pixel ratio (`createEngine({ pixelRatio })`, adaptive resolution)
|
|
146
|
+
once in dev. The pixel ratio (`createEngine({ pixelRatio })`, adaptive resolution) applies on top of the CSS size.
|
package/docs/recipes/02-npc.md
CHANGED
|
@@ -10,18 +10,18 @@ dialogue(), content())`.
|
|
|
10
10
|
`games/<game>/content/npcs.js`:
|
|
11
11
|
```js
|
|
12
12
|
export default {
|
|
13
|
-
|
|
14
|
-
name: '
|
|
13
|
+
guard: {
|
|
14
|
+
name: 'Gate guard',
|
|
15
15
|
colors: { body: 0xc89a5a, legs: 0x5b4a3a, hair: 0x3a2a1a }, // omit to use the style pack's default colors
|
|
16
16
|
start: { place: 'home', x: 6, z: -3 }, // starting position; omitted = the first stop of the schedule
|
|
17
17
|
schedule: [ // at is a clock time 'HH:MM'; at that time the NPC walks there (pathfinding is automatic)
|
|
18
18
|
{ at: '07:00', place: 'home', x: 6, z: -3 },
|
|
19
|
-
{ at: '13:00', place: '
|
|
19
|
+
{ at: '13:00', place: 'tower' },
|
|
20
20
|
{ at: '18:30', place: 'home', x: 2, z: 4 },
|
|
21
21
|
],
|
|
22
|
-
talk: '
|
|
22
|
+
talk: 'guard', // a dialogue id in dialogues.js; press E when near
|
|
23
23
|
},
|
|
24
|
-
cat: { name: '
|
|
24
|
+
cat: { name: 'Cat', start: { place: 'home' }, behavior: 'wander', mind: { radius: 6 } }, // no schedule: write behavior + start, omit schedule
|
|
25
25
|
};
|
|
26
26
|
```
|
|
27
27
|
A content NPC takes every `npcs.add` option (`speed`, `talkRadius`, `arriveDistance`, `pathStep`, `repath`, `talkLabel`, `model`...) written as a
|
|
@@ -29,35 +29,35 @@ field; a misspelt one errors with the closest name. `start` and `schedule` are t
|
|
|
29
29
|
`content/dialogues.js`:
|
|
30
30
|
```js
|
|
31
31
|
export default {
|
|
32
|
-
|
|
33
|
-
speaker: '
|
|
32
|
+
guard: {
|
|
33
|
+
speaker: 'Gate guard',
|
|
34
34
|
nodes: {
|
|
35
35
|
start: {
|
|
36
36
|
text: [ // several variants: the first whose condition holds is used
|
|
37
|
-
{ if: { flag: '
|
|
38
|
-
{ text: '
|
|
37
|
+
{ if: { flag: 'metGuard' }, text: 'Back again?' },
|
|
38
|
+
{ text: 'Halt. First time here?' },
|
|
39
39
|
],
|
|
40
|
-
do: { setFlag: '
|
|
40
|
+
do: { setFlag: 'metGuard' },
|
|
41
41
|
next: 'ask',
|
|
42
42
|
},
|
|
43
|
-
ask: { text: '
|
|
44
|
-
{ text: '
|
|
45
|
-
{ text: '
|
|
43
|
+
ask: { text: 'A pass costs one coin.', choices: [
|
|
44
|
+
{ text: 'Buy one', next: 'buy', if: { has: { coin: 1 } } },
|
|
45
|
+
{ text: 'No thanks' }, // a choice with no next = the dialogue ends; a plain node with no next waits for one more interact press, then ends
|
|
46
46
|
] },
|
|
47
|
-
buy: { text: '
|
|
47
|
+
buy: { text: 'Move along.', do: [{ take: { coin: 1 } }, { give: { pass: 1 } }], next: 'end' },
|
|
48
48
|
},
|
|
49
49
|
},
|
|
50
50
|
};
|
|
51
51
|
```
|
|
52
52
|
The words usable in conditions / effects are in the comment at the top of `modules/content/rules.js` (flag notFlag has lacks counter can / setFlag
|
|
53
53
|
give take bump startQuest toast particles marker clearMarker op).
|
|
54
|
-
The items used (coin,
|
|
55
|
-
from a level marker (such as `
|
|
54
|
+
The items used (coin, pass) must be defined in `items.js`, otherwise validation fails. A `place` name comes from `content.load(data, { places })` or
|
|
55
|
+
from a level marker (such as `npc_guard`). Add a new content file to `content/index.js`.
|
|
56
56
|
|
|
57
57
|
## 2. Add in code (temporary NPCs, dynamic schedules)
|
|
58
58
|
```js
|
|
59
|
-
engine.dialogue.define('passerby', { start: { text: '
|
|
60
|
-
const npc = engine.npcs.add({ id: 'passerby', name: '
|
|
59
|
+
engine.dialogue.define('passerby', { start: { text: 'Nice day.', speaker: 'Passerby' } });
|
|
60
|
+
const npc = engine.npcs.add({ id: 'passerby', name: 'Passerby', position: [10, 0, 5], schedule: [{ at: '08:00', position: [20, 0, 5] }], talk: 'passerby' }); // at: 'HH:MM' or 0-1; without id the name is used
|
|
61
61
|
engine.npcs.remove('passerby'); // remove by id, name or handle
|
|
62
62
|
```
|
|
63
63
|
|
|
@@ -88,7 +88,7 @@ them. Built in there is also `'wander'` (random wandering near home, using `engi
|
|
|
88
88
|
```js
|
|
89
89
|
npc.setBehavior('wander', { radius: 12 }); // home = current position, wander within 12 meters (pause: [2, 6] pause seconds, home: { x, z } sets the center)
|
|
90
90
|
npc.setBehavior('schedule'); // back to the schedule
|
|
91
|
-
engine.npcs.add({ id: 'dog', name: '
|
|
91
|
+
engine.npcs.add({ id: 'dog', name: 'Dog', position: [5, 0, 5], behavior: 'wander', mind: { radius: 8 } }); // wanders from the start
|
|
92
92
|
```
|
|
93
93
|
The behavior name and `mind` (the behavior's parameters and memory) are in the NPC data and are saved; after changing behavior or loading, the NPC
|
|
94
94
|
carries on with the new behavior. A wrong behavior name throws and lists the registered ones. NPCs in content can also write `behavior` + `mind`
|
|
@@ -141,8 +141,8 @@ engine.npcs.avoid.set(false); // turn off (ghosts, cro
|
|
|
141
141
|
|
|
142
142
|
## A guard you build yourself (`Character` + `walkTo`)
|
|
143
143
|
|
|
144
|
-
For a one-off (guard, pet, follower) that `schedule` / `wander` do not cover: `new Character(engine, { rig })` takes a ready body
|
|
145
|
-
`
|
|
144
|
+
For a one-off (guard, pet, follower) that `schedule` / `wander` do not cover: `new Character(engine, { rig })` takes a ready body
|
|
145
|
+
(`{ root, body?, head?, limbs?, joints? }`), or `{ model: 'humanoid' }` picks a body asset like any character ([13-animation](13-animation.md)); call `character.animate(dt)` each frame.
|
|
146
146
|
`character.walkTo(target, { speed, arrive, turnRate, run })` follows `characters.findPath` on fixed steps (turns at `turnRate` rad/s, skips passed
|
|
147
147
|
points, re-plans when it makes no progress for `stuckSeconds`, up to `maxRepaths`). It returns a promise of `{ status }`: `'arrived'` | `'noPath'` |
|
|
148
148
|
`'stuck'` | `'cancelled'` (never rejects), with `remove()` to cancel.
|
|
@@ -157,9 +157,9 @@ if ((await walk).status === 'noPath') guard.face(player); // walk.remove() can
|
|
|
157
157
|
## 3. Verify
|
|
158
158
|
- `npm run check`: content validation catches "dialogue id does not exist", "bad clock-time format", "node next points to a missing node". After
|
|
159
159
|
`npm run map` it shows up in the NPC table and dialogue graph of GAMEMAP.md.
|
|
160
|
-
- State: `npm run shot -- / --time 13:10 --wait 20 --describe-only`; the "nearby" list has an entry for
|
|
161
|
-
meters (only listed within 30 meters; add `--pos x,z` to stand by the
|
|
162
|
-
- Console / tests: `engine.npcs.get('
|
|
160
|
+
- State: `npm run shot -- / --time 13:10 --wait 20 --describe-only`; the "nearby" list has an entry for `Gate guard` tagged as an NPC with its distance in
|
|
161
|
+
meters (only listed within 30 meters; add `--pos x,z` to stand by the tower).
|
|
162
|
+
- Console / tests: `engine.npcs.get('guard').position`, `.currentStop()`; during a dialogue `engine.describe().ui.dialogue` = `{ speaker, text, typing, choices: [labels], lock }` (absent when no dialogue runs; the text version prints it as a `Dialogue:` line). `describe` does NOT expose the node id or the NPC id: `speaker` is the display name; to inspect the node, read the content file or listen to `engine.events.on("dialogue:line", ({ script, node, speaker, text }) => ...)` (also `dialogue:start` / `dialogue:end`).
|
|
163
163
|
- Advancing a dialogue in a headless test (typing and "keys ignored right after opening" both run on game time): press E when near -> `engine.step(1)`
|
|
164
164
|
to finish typing -> press a number key or run `engine.ops.run('dialogue.choose', { index: i })` (while typing it completes the sentence first) ->
|
|
165
165
|
`engine.step(0.3)`. No real-time waiting.
|
|
@@ -10,8 +10,8 @@ it grows back" is data in world (needs the world module that `openWorld()` inclu
|
|
|
10
10
|
```js
|
|
11
11
|
// Items: id -> name, icon, description. stack = how many fit in one slot (default 99; more spill into further slots), weight (optional), color = color when dropped on the ground
|
|
12
12
|
export default {
|
|
13
|
-
mushroom: { name: '
|
|
14
|
-
coin: { name: '
|
|
13
|
+
mushroom: { name: 'Mushroom', icon: '🍄', desc: 'Found in the woods', color: 0xc0504d },
|
|
14
|
+
coin: { name: 'Coin', icon: '🪙', stack: 99999 }, // currency: one slot however much you carry; full buying/selling in recipe 22
|
|
15
15
|
};
|
|
16
16
|
export const startItems = { coin: 3 }; // what the inventory holds at the start (optional)
|
|
17
17
|
```
|
|
@@ -39,7 +39,7 @@ changing level and coming back they are still picked up.
|
|
|
39
39
|
|
|
40
40
|
## 2. In code (dynamic drops, custom models)
|
|
41
41
|
```js
|
|
42
|
-
engine.inventory.define('gem', { name: '
|
|
42
|
+
engine.inventory.define('gem', { name: 'Gem', icon: '💎', color: 0x66ccff }); // shape: add mesh: (item, { color, size }, e) => Object3D | geometry, or model: 'generatorName', to set it on the item (wins over style.pickup.model; spawnPickup { mesh } wins over both)
|
|
43
43
|
const gem = engine.inventory.spawnPickup('gem', engine.player.position, { count: 1, respawnSeconds: 0 }); // returns a handle; gem.remove() deletes data and model together
|
|
44
44
|
// handle: { id: item, worldId: id in world, object: current model (null when far), remove() }; opts.id lets you write a stable id (spawning again with the same id reuses the existing one)
|
|
45
45
|
engine.inventory.add('coin', 2); // give directly; returns the entry key ('coin'), false if it doesn't fit
|
|
@@ -88,7 +88,7 @@ Both act on `ctx.actor`'s container (`'player'` by default).
|
|
|
88
88
|
can be undone.
|
|
89
89
|
```js
|
|
90
90
|
const r = engine.ops.run('inventory.trade', { take: 'rusty_key', give: 'gold_key' }); // also takeN / giveN; take may be an entry key ('sword#3')
|
|
91
|
-
if (!r.ok) say(r.
|
|
91
|
+
if (!r.ok) say(r.code); // 'notEnough' (A missing) | 'full' (B does not fit even after A leaves)
|
|
92
92
|
engine.ops.undo('inventory.trade', { take: 'rusty_key', give: 'gold_key' }, r.value); // gives A back (with its data), takes B away
|
|
93
93
|
engine.inventory.trade('rusty_key', 'gold_key'); // the same from code; a container has .trade() too
|
|
94
94
|
```
|
|
@@ -10,16 +10,16 @@ may also fail. When the current step has a `target`, hud shows a marker and dist
|
|
|
10
10
|
`games/<game>/content/quests.js`:
|
|
11
11
|
```js
|
|
12
12
|
export default {
|
|
13
|
-
'
|
|
14
|
-
title: '
|
|
15
|
-
desc: '
|
|
16
|
-
startOn: 'engine:ready', // the event that starts it automatically (or use { startQuest: '
|
|
13
|
+
'restore-power': {
|
|
14
|
+
title: 'Restore power',
|
|
15
|
+
desc: 'The engineer needs three fuses to restart the relay.',
|
|
16
|
+
startOn: 'engine:ready', // the event that starts it automatically (or use { startQuest: 'restore-power' } in a dialogue)
|
|
17
17
|
steps: [
|
|
18
|
-
{ id: 'talk', text: '
|
|
19
|
-
{ id: 'gather', text: '
|
|
20
|
-
{ id: 'return', text: '
|
|
18
|
+
{ id: 'talk', text: 'Talk to the engineer', done: { flag: 'metEngineer' }, target: { npc: 'engineer' } }, // the marker follows the NPC
|
|
19
|
+
{ id: 'gather', text: 'Find 3 fuses', done: { has: { fuse: 3 } }, target: 'storage' }, // a place name
|
|
20
|
+
{ id: 'return', text: 'Fit them at the relay', done: { flag: 'relayOn' }, target: { place: 'home', x: 0, z: 3 } },
|
|
21
21
|
],
|
|
22
|
-
reward: [{ take: {
|
|
22
|
+
reward: [{ take: { fuse: 3 } }, { give: { coin: 5 } }, { toast: 'Power restored!' }],
|
|
23
23
|
},
|
|
24
24
|
};
|
|
25
25
|
```
|
|
@@ -39,18 +39,18 @@ Not every quest is a straight line. A step can hold several goals done in any or
|
|
|
39
39
|
`fail` ends the quest early:
|
|
40
40
|
```js
|
|
41
41
|
'defend-camp': {
|
|
42
|
-
title: '
|
|
42
|
+
title: 'Hold the camp',
|
|
43
43
|
startOn: 'engine:ready',
|
|
44
44
|
steps: [
|
|
45
|
-
{ text: '
|
|
46
|
-
{ all: [ // text defaults to the required goals: "
|
|
47
|
-
{ text: '
|
|
48
|
-
{ text: '
|
|
49
|
-
{ text: '
|
|
45
|
+
{ text: 'Reach the camp', done: { flag: 'atCamp' }, target: 'camp' },
|
|
46
|
+
{ all: [ // text defaults to the required goals: "Hold the north gate / Hold the south gate"
|
|
47
|
+
{ text: 'Hold the north gate', done: { counter: { northWaves: 3 } }, target: 'northGate' },
|
|
48
|
+
{ text: 'Hold the south gate', done: { counter: { southWaves: 3 } }, target: 'southGate' },
|
|
49
|
+
{ text: 'No ally hurt', done: { notFlag: 'allyHurt' }, optional: true }, // a bonus: never blocks, shown done if met in time
|
|
50
50
|
] },
|
|
51
51
|
],
|
|
52
52
|
fail: { flag: 'campBurned' }, // checked while the quest is active
|
|
53
|
-
onFail: [{ toast: '
|
|
53
|
+
onFail: [{ toast: 'The camp has fallen' }, { setFlag: 'mayRetryCamp' }],
|
|
54
54
|
reward: { give: { coin: 20 } },
|
|
55
55
|
},
|
|
56
56
|
```
|
|
@@ -60,18 +60,18 @@ Not every quest is a straight line. A step can hold several goals done in any or
|
|
|
60
60
|
|
|
61
61
|
## 2. In code (complex conditions, or when you need functions)
|
|
62
62
|
```js
|
|
63
|
-
engine.quests.define('
|
|
64
|
-
title: '
|
|
65
|
-
steps: [{ text: '
|
|
63
|
+
engine.quests.define('slimes3', {
|
|
64
|
+
title: 'Clear the cellar',
|
|
65
|
+
steps: [{ text: 'Defeat 3 slimes', done: e => e.vars.counter('slimes') >= 3, target: () => engine.npcs.get('engineer')?.position }], // the function returns a position every frame: when the NPC is far away and has no model, root is null, so read position from the data
|
|
66
66
|
reward: e => e.inventory.add('coin', 3),
|
|
67
67
|
});
|
|
68
|
-
engine.quests.start('
|
|
69
|
-
engine.vars.bump('
|
|
68
|
+
engine.quests.start('slimes3');
|
|
69
|
+
engine.vars.bump('slimes'); // each time one is defeated
|
|
70
70
|
engine.events.on('quest:done', ({ id }) => { /* quest completed */ }); // there are also quest:start, quest:step, quest:part and quest:fail
|
|
71
71
|
```
|
|
72
|
-
To turn off automatic markers: `hud({ questMarkers: false })`. To add a marker by hand: `const m = engine.hud.marker('
|
|
73
|
-
content effects can add them too: `{ marker: '
|
|
74
|
-
`engine.hud.counter('
|
|
72
|
+
To turn off automatic markers: `hud({ questMarkers: false })`. To add a marker by hand: `const m = engine.hud.marker('gate', { label: 'Gate' }); m.remove();`;
|
|
73
|
+
content effects can add them too: `{ marker: 'gate' }` / `{ clearMarker: 'gate' }`. A counter in the screen corner:
|
|
74
|
+
`engine.hud.counter('slimes', { label: 'Slimes', value: 2, max: 3 })`.
|
|
75
75
|
|
|
76
76
|
## 3. Verify
|
|
77
77
|
- `npm run check`: a wrong item / flag / place name / NPC id in a step is an error; "flag is only checked but never set" is a warning. After
|