threedog 0.1.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.
Files changed (244) hide show
  1. package/README.md +4 -4
  2. package/core/Animator.js +1 -0
  3. package/core/Assets.js +28 -0
  4. package/core/DebugOverrides.js +143 -0
  5. package/core/Describe.js +14 -3
  6. package/core/Engine.js +44 -72
  7. package/core/Events.js +59 -1
  8. package/core/I18n.js +2 -2
  9. package/core/Inspect.js +12 -32
  10. package/core/InspectScene.js +7 -3
  11. package/core/MaterialInfo.js +32 -0
  12. package/core/Ops.js +43 -59
  13. package/core/Saves.js +5 -4
  14. package/core/UrlState.js +3 -2
  15. package/core/Vars.js +1 -0
  16. package/core/Views.js +49 -0
  17. package/core/actor.js +2 -2
  18. package/core/assetReport.js +83 -0
  19. package/core/catalog.js +169 -0
  20. package/core/checks.js +67 -0
  21. package/core/claims.js +51 -0
  22. package/core/debugView.js +76 -0
  23. package/core/describeRender.js +51 -0
  24. package/core/describeText.js +11 -4
  25. package/core/errorCodes.js +33 -0
  26. package/core/errorHints.js +6 -1
  27. package/core/grid.js +127 -0
  28. package/core/gridLoad.js +19 -0
  29. package/core/holds.js +106 -0
  30. package/core/lifecycle.js +1 -0
  31. package/core/lightWatch.js +23 -3
  32. package/core/look/coreParts.js +112 -0
  33. package/core/look/layers.js +136 -0
  34. package/core/look/part.js +173 -0
  35. package/core/look/report.js +79 -0
  36. package/core/look/write.js +86 -0
  37. package/core/loop.js +22 -16
  38. package/core/modules.js +19 -5
  39. package/core/opsAtomic.js +31 -0
  40. package/core/opsCheck.js +25 -14
  41. package/core/opsFail.js +20 -0
  42. package/core/opsHistory.js +6 -6
  43. package/core/opsRun.js +77 -0
  44. package/core/params.js +132 -0
  45. package/core/renamed.js +22 -0
  46. package/core/saveApply.js +2 -2
  47. package/core/sceneMethods.js +9 -34
  48. package/core/services.js +73 -0
  49. package/core/startup.js +3 -1
  50. package/core/styleParts.js +11 -9
  51. package/core/thingExplain.js +68 -0
  52. package/core/thingOps.js +35 -24
  53. package/core/things.js +15 -1
  54. package/core/util.js +11 -0
  55. package/core/validate.js +23 -7
  56. package/docs/AI.md +93 -114
  57. package/docs/API.md +8 -9
  58. package/docs/CODEMAP.md +67 -53
  59. package/docs/COMMANDS.md +21 -7
  60. package/docs/CONVENTIONS.md +22 -11
  61. package/docs/THREE.md +3 -3
  62. package/docs/api/assets.md +3 -0
  63. package/docs/api/characters.md +5 -2
  64. package/docs/api/collision.md +4 -0
  65. package/docs/api/content.md +1 -0
  66. package/docs/api/engine.md +23 -14
  67. package/docs/api/events.md +5 -1
  68. package/docs/api/post.md +5 -4
  69. package/docs/api/saves.md +2 -1
  70. package/docs/api/sky.md +3 -3
  71. package/docs/api/style.md +8 -8
  72. package/docs/api/tools.md +5 -2
  73. package/docs/api/vegetation.md +1 -0
  74. package/docs/api/weather.md +1 -1
  75. package/docs/recipes/01-new-game.md +41 -43
  76. package/docs/recipes/02-npc.md +38 -22
  77. package/docs/recipes/03-items-pickups.md +4 -4
  78. package/docs/recipes/04-quests.md +23 -23
  79. package/docs/recipes/05-props-bake.md +5 -5
  80. package/docs/recipes/06-clock-events.md +13 -0
  81. package/docs/recipes/07-flow-scenes-pause.md +6 -2
  82. package/docs/recipes/08-weather-sky.md +6 -6
  83. package/docs/recipes/09-style-pack.md +35 -100
  84. package/docs/recipes/12-navmesh.md +22 -0
  85. package/docs/recipes/13-animation.md +25 -6
  86. package/docs/recipes/14-custom-module.md +6 -7
  87. package/docs/recipes/15-perf.md +9 -1
  88. package/docs/recipes/16-dev-bridge.md +52 -18
  89. package/docs/recipes/18-world.md +5 -2
  90. package/docs/recipes/19-shooting-picking.md +9 -8
  91. package/docs/recipes/20-content-actions-save.md +10 -10
  92. package/docs/recipes/21-camera.md +51 -2
  93. package/docs/recipes/22-shop-gold.md +16 -16
  94. package/docs/recipes/23-ops.md +46 -10
  95. package/docs/recipes/27-net.md +3 -3
  96. package/docs/recipes/28-terrain.md +2 -2
  97. package/docs/recipes/29-grid.md +47 -27
  98. package/docs/recipes/34-environment-lighting.md +11 -10
  99. package/docs/recipes/35-style-from-reference.md +41 -46
  100. package/docs/recipes/36-sky-ground-plant-looks.md +22 -20
  101. package/docs/recipes/37-terrain-look-hooks.md +34 -13
  102. package/docs/recipes/38-environment-look-hooks.md +49 -42
  103. package/docs/recipes/40-scene.md +29 -0
  104. package/docs/recipes/41-thing-registry.md +29 -0
  105. package/docs/recipes/42-terrain-shape.md +1 -1
  106. package/docs/recipes/43-shader-patches-surface-looks.md +37 -20
  107. package/docs/recipes/44-water-weather-look-hooks.md +11 -9
  108. package/docs/recipes/45-cascaded-shadows.md +2 -2
  109. package/docs/recipes/46-blender-art-route.md +26 -4
  110. package/docs/recipes/47-island-snow-backdrop.md +4 -3
  111. package/docs/recipes/48-make-material.md +70 -0
  112. package/docs/recipes/49-game-module-contract.md +71 -0
  113. package/docs/recipes/50-own-renderer.md +12 -0
  114. package/docs/recipes/51-capability-catalog.md +63 -0
  115. package/docs/recipes/52-look.md +146 -0
  116. package/docs/recipes/53-ground-up-close.md +58 -0
  117. package/examples/action/GAMEMAP.md +7 -7
  118. package/examples/action/content/index.js +2 -1
  119. package/examples/action/content/views.js +6 -0
  120. package/examples/action/main.js +3 -2
  121. package/examples/sheepisland/GAMEMAP.md +3 -4
  122. package/examples/styletest/GAMEMAP.md +3 -3
  123. package/examples/styletest/content/npcs.js +1 -1
  124. package/examples/styletest/main.js +2 -2
  125. package/examples/styletest/panel.js +3 -3
  126. package/examples/world/GAMEMAP.md +3 -3
  127. package/examples/world/content/npcs.js +1 -1
  128. package/examples/world/main.js +1 -1
  129. package/index.d.ts +35 -2
  130. package/index.js +6 -3
  131. package/llms.txt +13 -7
  132. package/modules/ambience/Ambience.js +5 -2
  133. package/modules/camera/FirstPersonCamera.js +3 -5
  134. package/modules/camera/FixedCamera.js +19 -12
  135. package/modules/camera/FollowCamera.js +14 -8
  136. package/modules/camera/RtsCamera.js +3 -5
  137. package/modules/camera/common.js +40 -10
  138. package/modules/camera/index.js +1 -1
  139. package/modules/camera/projection.js +34 -0
  140. package/modules/characters/Character.js +45 -31
  141. package/modules/characters/assetModel.js +35 -7
  142. package/modules/characters/astar.js +14 -7
  143. package/modules/characters/index.js +6 -3
  144. package/modules/characters/movers/simple.js +6 -1
  145. package/modules/characters/npcSim.js +8 -2
  146. package/modules/characters/pathAsync.js +12 -6
  147. package/modules/characters/pathJob.js +2 -1
  148. package/modules/characters/proceduralRig.js +50 -11
  149. package/modules/characters/useModel.js +22 -0
  150. package/modules/characters/walkTo.js +58 -0
  151. package/modules/collision/Collision.js +102 -4
  152. package/modules/content/explain.js +13 -0
  153. package/modules/content/index.js +3 -1
  154. package/modules/content/loader.js +3 -0
  155. package/modules/content/rules.js +1 -0
  156. package/modules/debug/DebugPanel.js +11 -5
  157. package/modules/entities/Entities.js +6 -2
  158. package/modules/flow/index.js +5 -2
  159. package/modules/gameplay/Dialogue.js +5 -2
  160. package/modules/gameplay/Interactions.js +12 -2
  161. package/modules/gameplay/Inventory.js +21 -11
  162. package/modules/gameplay/Quests.js +13 -3
  163. package/modules/gameplay/pickups.js +6 -4
  164. package/modules/grid/Layer.js +1 -1
  165. package/modules/grid/index.js +1 -1
  166. package/modules/grid/tiles.js +9 -5
  167. package/modules/hlod/index.js +5 -2
  168. package/modules/hud/index.js +5 -2
  169. package/modules/level/index.js +5 -3
  170. package/modules/lights/index.js +5 -2
  171. package/modules/music/Music.js +6 -2
  172. package/modules/nav/index.js +5 -3
  173. package/modules/net/Client.js +4 -3
  174. package/modules/net/Host.js +2 -2
  175. package/modules/net/index.js +5 -3
  176. package/modules/particles/Particles.js +1 -1
  177. package/modules/photo/Photo.js +10 -7
  178. package/modules/rigid/RigidBodies.js +5 -2
  179. package/modules/settings/Settings.js +6 -3
  180. package/modules/settings/apply.js +2 -1
  181. package/modules/sky/Sky.js +21 -19
  182. package/modules/sky/cascades.js +6 -6
  183. package/modules/sky/domeLayers.js +1 -1
  184. package/modules/sky/environment.js +39 -13
  185. package/modules/sky/fog.js +9 -6
  186. package/modules/sky/frame.js +4 -3
  187. package/modules/sky/look.js +3 -2
  188. package/modules/sky/lookFog.js +80 -0
  189. package/modules/sky/lookShadow.js +50 -0
  190. package/modules/sky/lookSky.js +108 -0
  191. package/modules/sky/shader.js +2 -2
  192. package/modules/sky/shadow.js +4 -10
  193. package/modules/sky/skyModule.js +4 -3
  194. package/modules/terrain/ChunkManager.js +2 -33
  195. package/modules/terrain/chunkLevels.js +40 -0
  196. package/modules/terrain/index.js +10 -2
  197. package/modules/terrain/lookGround.js +61 -0
  198. package/modules/timeline/Timeline.js +7 -3
  199. package/modules/timeline/Tween.js +3 -7
  200. package/modules/timeline/shots.js +6 -4
  201. package/modules/triggers/index.js +9 -2
  202. package/modules/vegetation/Vegetation.js +17 -4
  203. package/modules/vegetation/index.js +7 -4
  204. package/modules/vegetation/lookWind.js +37 -0
  205. package/modules/vegetation/nearFade.js +39 -0
  206. package/modules/water/Water.js +19 -3
  207. package/modules/water/look.js +80 -0
  208. package/modules/weather/Weather.js +22 -31
  209. package/modules/weather/look.js +75 -0
  210. package/modules/weather/particles.js +1 -1
  211. package/modules/weather/strings.js +15 -0
  212. package/modules/world/explain.js +11 -0
  213. package/modules/world/index.js +11 -4
  214. package/modules/world/thingSource.js +44 -0
  215. package/package.json +2 -1
  216. package/render/PostFX.js +48 -51
  217. package/render/detail.js +39 -15
  218. package/render/effects.js +4 -2
  219. package/render/fuse.js +12 -0
  220. package/render/lights.js +4 -2
  221. package/render/lookSurface.js +161 -0
  222. package/render/materials.js +27 -10
  223. package/render/postLook.js +86 -0
  224. package/render/surface.js +3 -1
  225. package/types/core.d.ts +223 -29
  226. package/types/gameplay.d.ts +22 -6
  227. package/types/generated/core/DebugOverrides.d.ts +52 -0
  228. package/types/generated/core/Events.d.ts +43 -0
  229. package/types/generated/core/Ops.d.ts +62 -21
  230. package/types/generated/core/Saves.d.ts +1 -0
  231. package/types/generated/core/Views.d.ts +33 -0
  232. package/types/generated/modules/debug/DebugPanel.d.ts +2 -2
  233. package/types/generated/modules/grid/Layer.d.ts +1 -0
  234. package/types/generated/modules/sky/Sky.d.ts +10 -17
  235. package/types/generated/modules/weather/Weather.d.ts +5 -15
  236. package/types/generated/render/PostFX.d.ts +20 -23
  237. package/types/generated/render/materials.d.ts +10 -0
  238. package/types/physics.d.ts +8 -0
  239. package/types/style.d.ts +35 -20
  240. package/types/world.d.ts +7 -1
  241. package/ui/Parts.js +6 -2
  242. package/ui/UI.js +1 -1
  243. package/ui/defaults.js +1 -1
  244. package/docs/api/debug.md +0 -10
@@ -0,0 +1,34 @@
1
+ // Orthographic projection for engine.camera, without replacing the camera object.
2
+ //
3
+ // engine.camera is one PerspectiveCamera that the render pass, post chain, cascaded shadows, sky and every module hold a reference to.
4
+ // Swapping in a THREE.OrthographicCamera would leave those pointing at the old camera, so the rig flips this same instance instead:
5
+ // updateProjectionMatrix() builds an orthographic matrix while camera.orthoSize is set (isPerspectiveCamera / isOrthographicCamera and
6
+ // left/right/top/bottom follow, so code that branches on the camera type keeps working), and the original perspective one otherwise.
7
+ // Resize needs nothing extra: canvasBox sets camera.aspect and calls updateProjectionMatrix().
8
+
9
+ /**
10
+ * Switch engine.camera between perspective and orthographic.
11
+ * @param {import('three').PerspectiveCamera} cam engine.camera
12
+ * @param {'perspective' | 'orthographic'} projection
13
+ * @param {number} [size] orthographic only: world units covered by the view height (before camera.zoom)
14
+ */
15
+ export function setProjection(cam, projection = 'perspective', size = 20) {
16
+ if (projection !== 'perspective' && projection !== 'orthographic') throw new Error(`projection must be 'perspective' or 'orthographic', got '${projection}'`);
17
+ if (projection === 'orthographic' && !(size > 0)) throw new Error(`orthographic projection needs size > 0 (world units of view height), got ${size}`);
18
+ if (!cam._perspectiveUpdate) {
19
+ const original = cam.updateProjectionMatrix;
20
+ cam._perspectiveUpdate = original;
21
+ cam.updateProjectionMatrix = function () {
22
+ if (!this.orthoSize) return original.call(this);
23
+ const top = this.orthoSize / 2 / this.zoom, right = top * this.aspect;
24
+ this.left = -right; this.right = right; this.top = top; this.bottom = -top;
25
+ this.projectionMatrix.makeOrthographic(-right, right, top, -top, this.near, this.far, this.coordinateSystem);
26
+ this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
27
+ };
28
+ }
29
+ const ortho = projection === 'orthographic';
30
+ if (ortho ? cam.orthoSize === size : !cam.orthoSize) return;
31
+ cam.orthoSize = ortho ? size : 0;
32
+ cam.isOrthographicCamera = ortho; cam.isPerspectiveCamera = !ortho;
33
+ cam.updateProjectionMatrix();
34
+ }
@@ -1,37 +1,39 @@
1
- // Character: procedural rig (from the style pack, gray capsule without one) or glTF model + procedural animation (walk, run, swim, idle breathing)
1
+ // Character: a body from a model asset (procedural rig from an asset pack, or a glTF model; gray capsule without one) + procedural animation (walk, run, swim, idle breathing)
2
2
  // + movement control (ground snap, collision, slope limit, swimming).
3
- // Used by both player and NPCs. To switch to a skeletal glTF model later, pass model + clips (or an animation state machine config); control logic stays the same.
3
+ // Used by both player and NPCs; a skeletal glTF body takes model + clips (or an animation state machine config), control logic stays the same.
4
4
  // The mover owns position: only the mover (movers/) changes a character's position inside move(); other systems (pathfinding, triggers, vehicles, loading)
5
5
  // request movement via placeAt (teleport), move (direction), enter / exit (vehicles).
6
6
  // Characters backed by a world record (the player, recordId = 'player') write position and motion state back to the record after every move / placeAt / enter / exit;
7
7
  // the record is saved, world splits near/far by it, the model is just its look.
8
8
  // Radius and step height default to engine.movement (the single source of "can walk through" parameters); passing radius / stepHeight overrides it for this character only.
9
9
  // How to walk is decided by the mover (movers/: 'simple' default, 'rapier' character controller); feel parameters are identical for both.
10
- // The procedural body (capsule, style-pack rig, limb swing) is in proceduralRig.js.
10
+ // The procedural body (capsule, rig read from a model asset, limb swing) is in proceduralRig.js; loading a body by asset name in assetModel.js.
11
11
  import * as THREE from 'three';
12
12
  import { xzOf } from '../../core/math.js';
13
13
  import { placeY } from '../../core/ground.js';
14
14
  import { warnOnce, warnMissing } from '../../core/validate.js';
15
- import { findClip } from '../../core/Animator.js';
15
+ import { reportError } from '../../core/errors.js';
16
16
  import { simpleMover } from './movers/simple.js';
17
17
  import { rapierMover } from './movers/rapier.js';
18
- import { loadAssetModel } from './assetModel.js';
19
- import { NO_CHARACTER, capsule, useRig, animateRig } from './proceduralRig.js';
18
+ import { loadAssetModel, buildNow, checkStyleCharacter } from './assetModel.js';
19
+ import { NO_CHARACTER, capsule, useRig, animateRig, rigFromObject, tintParts } from './proceduralRig.js';
20
+ import { walkTo } from './walkTo.js';
21
+ import { useModel } from './useModel.js';
20
22
 
21
23
  const STRINGS = { noClip: 'character has no skeletal animation; playAction(\'{name}\') skipped (the model needs this action)' };
22
24
  const MOVERS = { simple: simpleMover, rapier: rapierMover };
23
- // Default action names for the clips shorthand (character state -> glTF action name)
24
- const DEFAULT_CLIPS = { idle: 'Idle', walk: 'Walk', run: 'Run', swim: 'Swim', jump: 'Jump', fall: 'Fall', drive: 'Drive' };
25
25
 
26
26
  // Options Character understands (shared by player and NPC)
27
27
  export const CHARACTER_KEYS = ['colors', 'speed', 'runSpeed', 'radius', 'canSwim', 'swimDepth', 'swimSpeed', 'turnSpeed', 'acceleration', 'gravity',
28
- 'jumpSpeed', 'stepHeight', 'airControl', 'coyoteTime', 'canJump', 'model', 'clips', 'animation', 'mover', 'faceMode', 'faceTarget'];
28
+ 'jumpSpeed', 'stepHeight', 'airControl', 'coyoteTime', 'canJump', 'model', 'clips', 'animation', 'mover', 'faceMode', 'faceTarget', 'rig'];
29
29
  const FACE_MODES = ['move', 'camera', 'target', 'manual'];
30
30
 
31
31
  export class Character {
32
32
  /**
33
33
  * @param engine
34
- * @param o colors: { body, skin, legs, hair } (default from style pack style.character.colors)
34
+ * @param o model: the body, one path for all: a model asset name (a procedural builder from an asset pack, or a GLB name), or what
35
+ * engine.assets.model() returned; without model and rig a gray capsule (warned once). rig: a ready body (proceduralRig.js format)
36
+ * colors: { body, skin, legs, hair } per-character part colors (meshes marked userData.part); the style tints parts by material role
35
37
  * speed walk speed, runSpeed run speed (m/s), radius collision radius
36
38
  * canSwim whether it can swim (false: never enters water), swimDepth water depth at which swimming starts, swimSpeed swim speed multiplier
37
39
  * turnSpeed how fast it turns, acceleration how fast it starts/stops
@@ -44,13 +46,12 @@ export class Character {
44
46
  * faceMode which way it turns each move: 'move' (default, toward its velocity) | 'camera' (along cameraRig.forward(), over-the-shoulder aiming)
45
47
  * | 'target' (toward faceTarget: Object3D / Vector3 / { x, z }, lock-on strafing) | 'manual' (only face() turns it);
46
48
  * both are plain properties, change them at any time
47
- * model may be a registered asset name (default style.character.model): placeholder body until it loads, then swapped in (assetModel.js)
48
- * without model: style pack style.character.create(engine, colors) may return a custom procedural character (rig format below), else a gray capsule
49
+ * a file model name shows the capsule until it loads, then is swapped in (assetModel.js)
49
50
  */
50
51
  constructor(engine, { colors = {}, speed = 4.5, runSpeed = 7, radius = engine.movement.radius, canSwim = true, swimDepth = 1.0, swimSpeed = 0.45,
51
52
  turnSpeed = 10, acceleration = 12, gravity = -24, jumpSpeed = 8, stepHeight = engine.movement.stepHeight, airControl = 0.35, coyoteTime = 0.12,
52
53
  canJump = true,
53
- model = null, clips = null, animation = null, mover = 'simple', faceMode = 'move', faceTarget = null } = {}) {
54
+ model = null, clips = null, animation = null, mover = 'simple', faceMode = 'move', faceTarget = null, rig = null } = {}) {
54
55
  this.engine = engine;
55
56
  Object.assign(this, { speed, runSpeed, radius, canSwim, swimDepth, swimSpeedFactor: swimSpeed, turnSpeed, acceleration, gravity, jumpSpeed, stepHeight,
56
57
  airControl, coyoteTime, canJump });
@@ -74,29 +75,29 @@ export class Character {
74
75
  if (!MOVERS[mover]) warnMissing('mover', mover, Object.keys(MOVERS));
75
76
  const simple = simpleMover(this);
76
77
  this.mover = mover === 'rapier' ? rapierMover(this, simple) : simple;
77
- // default look comes from style pack style.character.colors; neutral gray without a style pack
78
- const c = { body: 0x8a8a8a, skin: 0xc8bfb5, legs: 0x5a5a5a, hair: 0x4a4a4a, ...(engine.style.character?.colors || {}), ...colors };
79
-
80
- model ??= engine.style.character?.model ?? null;
81
- if (model && typeof model !== 'string') { this._useModel(model, clips, animation); return; }
82
- // style-pack procedural character: the rig format is in proceduralRig.js
83
- const rig = engine.style.character?.create?.(engine, c);
78
+ checkStyleCharacter(engine); // bodies are assets now: an old style.character.create / model / colors throws renamed-api
79
+ this._colors = colors;
80
+ // one path for every body: an object, a procedural builder built now (joints exist at once), or a file asset loaded behind a capsule
81
+ const now = typeof model === 'string' ? buildNow(engine, model) : model;
82
+ if (now) { this._useModel(now, clips, animation); return; }
84
83
  if (!rig && !model) warnOnce(NO_CHARACTER);
85
- useRig(this, rig || capsule(c.body, engine));
84
+ useRig(this, rig || capsule(colors.body ?? 0x8a8a8a, engine));
86
85
  if (model) this._whenReady = loadAssetModel(this, model, m => this._useModel(m, clips, animation));
87
86
  }
87
+ /** A model object with userData.rig is a procedural body (limb swing); anything else animates by its clips */
88
88
  _useModel(model, clips, animation) {
89
- const engine = this.engine; this.root.add(model);
90
- const states = {};
91
- // default names only where the model has the clip (a model without Swim is fine) and the manifest mapped nothing (Assets.animate merges that under
92
- // these states, so a default Idle must not shadow a mapped Idle_Sword); names the game wrote are always kept so a typo is reported
93
- const have = model.userData.animations || [], map = engine.assets.mapping(model), mapped = map?.states || {};
94
- for (const [st, clip] of Object.entries(DEFAULT_CLIPS)) if (!mapped[st] && findClip(have, clip)) states[st] = { clip };
95
- for (const [st, clip] of Object.entries(clips || {})) states[st] = { clip };
96
- // the model's own mapping (fade, transitions) beats the style pack's default for every character; the game's per-character config beats both
97
- this.anim = engine.assets.animate(model, { ...engine.style.character?.animation, ...map, states, ...(animation || {}) });
89
+ const r = rigFromObject(model);
90
+ if (r) useRig(this, r); else useModel(this, model, clips, animation);
91
+ tintParts(model, this._colors);
98
92
  }
99
93
 
94
+ /**
95
+ * Walk to a point along characters.findPath on fixed steps (turn rate, skips passed points, re-plans when stuck). Returns a promise of
96
+ * { status: 'arrived' | 'noPath' | 'stuck' | 'cancelled' } (never rejects) with remove() to cancel; a new walkTo, dispose() or a save load cancels it (not saved). speed m/s, arrive metres, turnRate rad/s
97
+ * @example await guard.walkTo(player.position, { arrive: 1.5 })
98
+ */
99
+ walkTo(target, opts) { return walkTo(this, target, opts); }
100
+
100
101
  /** Request a jump (call when the jump key is pressed; has a jump buffer, so pressing slightly before landing counts) */
101
102
  jump() { if (this.canJump) this._jumpBuffer = 0.12; }
102
103
 
@@ -155,6 +156,7 @@ export class Character {
155
156
  /** Dispose this character completely: exit the vehicle first, release animation and mover, remove from the scene and dispose geometries and materials */
156
157
  dispose() {
157
158
  this._disposed = true; // a model still loading by asset name is dropped on arrival
159
+ this._walk?.remove(); // a walk in progress ends 'cancelled' (walkTo.js)
158
160
  this.exit();
159
161
  this.anim?.dispose();
160
162
  this.mover.dispose?.();
@@ -202,8 +204,20 @@ export class Character {
202
204
  this.root.rotation.y = this.facing;
203
205
  }
204
206
 
207
+ /**
208
+ * Run fn(character, dt) every frame right after this character's animation pose is applied (model clips or procedural rig), so a game can attach things to bones
209
+ * or adjust bones on top of the pose. Returns a handle; h.remove() stops it. Presentation only: never read it for gameplay timing.
210
+ * @param {(character: Character, dt: number) => void} fn
211
+ * @returns {{ remove(): void }}
212
+ * @example const h = player.onPose(() => sword.position.copy(player.object.getObjectByName('Hand_R').getWorldPosition(v)));
213
+ */
214
+ onPose(fn) { (this._poseFns ??= new Set()).add(fn); return { remove: () => this._poseFns.delete(fn) }; }
215
+ /** @internal */
216
+ _firePose(dt) { if (this._poseFns?.size) for (const f of [...this._poseFns]) { try { f(this, dt); } catch (err) { reportError(this.engine, err, 'character.onPose callback'); } } }
205
217
  /** @internal Call every frame: play animation */
206
- animate(dt) {
218
+ animate(dt) { this._animate(dt); if (!this.anim) this._firePose(dt); }
219
+ /** @internal */
220
+ _animate(dt) {
207
221
  const sp = this.moveAmount, t = this.engine.elapsed, st = this.state;
208
222
  this.phase += dt * (2.2 + sp * 1.25);
209
223
  const s = Math.sin(this.phase);
@@ -1,18 +1,46 @@
1
- // Character model named by asset (Character({ model: 'hero' }) or style.character.model): construction is synchronous, loading is not.
2
- // A model already loaded is swapped in at once (engine.assets.modelNow); otherwise the character keeps its placeholder body (style create() or the gray capsule) until engine.assets.model(name) resolves, then the copy
3
- // (SkeletonUtils clone, so many characters share one asset) replaces the body under the same root: position, facing, state and every
4
- // reference to the character or its root (collision, interactions, world view) stay valid. Loaded only when a string model is used.
1
+ // Character body named by asset (Character({ model: 'humanoid' | 'hero' })): construction is synchronous, loading is not.
2
+ // A procedural builder (manifest models: { humanoid: fn }, an asset pack's models) is built right here (buildNow), so its joints exist as soon as the
3
+ // character does and no placeholder frame shows. A file model already loaded is swapped in at once (engine.assets.modelNow); otherwise the
4
+ // character keeps its gray capsule until engine.assets.model(name) resolves, then the copy (SkeletonUtils clone, so many characters share one
5
+ // asset) replaces the body under the same root: position, facing, state and every reference to the character or its root (collision,
6
+ // interactions, world view) stay valid.
7
+ import * as THREE from 'three';
5
8
  import { warnOnce } from '../../core/validate.js';
6
9
  import { fmt } from '../../core/opsCheck.js';
10
+ import { renamed } from '../../core/errorHints.js';
11
+ import { makeMaterial } from '../../render/materials.js';
12
+
13
+ /**
14
+ * Bodies are assets, not style (0.2): a style pack that still gives style.character.create / model / colors throws renamed-api at once,
15
+ * instead of silently getting gray capsules. style.character.animation (default fade) stays: it is a look of motion, not a body.
16
+ */
17
+ export function checkStyleCharacter(engine) {
18
+ const sc = engine.style.character;
19
+ if (sc && ('create' in sc || 'model' in sc || 'colors' in sc)) renamed('characterBody');
20
+ }
21
+
22
+ /**
23
+ * Build a procedural model asset now (synchronously) when `name` is a registered builder; null when it is a file model, unknown, or the
24
+ * builder is async (those load through loadAssetModel). The builder gets this = { palette: style.palette, engine } like engine.assets.cached.
25
+ */
26
+ export function buildNow(engine, name) {
27
+ const build = engine.assets.builder(name);
28
+ if (!build) return null;
29
+ const v = build.call({ palette: engine.style.palette, engine });
30
+ if (!v || typeof v.then === 'function') return null;
31
+ if (v.isBufferGeometry) return new THREE.Mesh(v, makeMaterial('character', { vertexColors: !!v.attributes.color }, engine));
32
+ if (!v.name) v.name = name;
33
+ return v;
34
+ }
7
35
 
8
36
  const STRINGS = {
9
- unknown: 'Character model "{name}" is not a registered model asset (registered: {list}). Fix: use one of those names, or register it first: engine.assets.manifest({ models: { {name}: \'/models/{name}.glb\' } })',
37
+ unknown: 'Character model "{name}" is not a registered model asset (registered: {list}). Fix: use one of those names, or register it first: engine.assets.manifest({ models: { {name}: \'/models/{name}.glb\' } }). A procedural body is a generator in an asset pack (engine.assets.manifest(yourAssets)); without a model the player is a gray capsule',
10
38
  failed: 'Character model "{name}" did not load ({why}); the character keeps its placeholder body. Registered models: {list}; engine.loading has the error',
11
39
  };
12
40
 
13
41
  /**
14
42
  * Start loading the asset model for ch; returns the promise stored as ch.whenReady (never rejects).
15
- * Throws at once when a manifest is registered and lacks the name (paths with / or . load as files).
43
+ * Throws at once when no model asset has the name (paths with / or . load as files).
16
44
  * @param {import('./Character.js').Character} ch
17
45
  * @param {string} name
18
46
  * @param {(model: any) => void} use builds the model and Animator on ch
@@ -21,7 +49,7 @@ export function loadAssetModel(ch, name, use) {
21
49
  const e = ch.engine, A = e.assets;
22
50
  const names = [...A.entries].filter(([, x]) => x.type === 'model' && x.named).map(([n]) => n);
23
51
  const list = names.join(', ') || 'none; register them with engine.assets.manifest({ models })';
24
- if (names.length && !names.includes(name) && !/[/.]/.test(name)) throw new Error(fmt(STRINGS.unknown, { name, list }));
52
+ if (!names.includes(name) && !/[/.]/.test(name)) throw new Error(fmt(STRINGS.unknown, { name, list }));
25
53
  const fail = why => warnOnce(fmt(STRINGS.failed, { name, why, list }));
26
54
  const swap = m => {
27
55
  if (ch._disposed || e.disposed) { e.remove(m); return; } // removed before loading finished: never reaches the scene, the copy is released
@@ -2,6 +2,12 @@
2
2
  // engine.characters.findPath calls it with the collision module's walkability, the pathfinding worker (pathJob.js) with a snapshot of it.
3
3
  // In games use engine.characters.findPath / findPathAsync, do not import this directly. Worker-safe: no imports.
4
4
 
5
+ /** Default cell size from the character radius: a small character gets finer cells (never below the 1 m ground raster, never above the old 2 m); no radius = 2 */
6
+ const defaultStep = r => r == null ? 2 : Math.min(2, Math.max(1, r * 4));
7
+ const defaultNodes = step => Math.round(6000 * Math.max(1, 2 / step) ** 2); // finer cells need more of them to cover the same distance
8
+ /** The step / maxNodes findPath uses for a character radius when the caller gives none (pathAsync sizes its ground raster with the same numbers) */
9
+ export const astarDefaults = radius => { const step = defaultStep(radius); return { step, maxNodes: defaultNodes(step) }; };
10
+
5
11
  class MinHeap {
6
12
  constructor() { this.a = []; }
7
13
  push(n, f) { const a = this.a; a.push([f, n]); let i = a.length - 1; while (i > 0) { const p = (i - 1) >> 1; if (a[p][0] <= a[i][0]) break; [a[p], a[i]] = [a[i], a[p]]; i = p; } }
@@ -13,7 +19,8 @@ class MinHeap {
13
19
  * Grid A*: cells of step meters, searches at most maxNodes cells; returns [{ x, z }...] or null if no path.
14
20
  * @param {(x: number, z: number) => boolean} walkable can a character stand here (radius already applied)
15
21
  */
16
- export function findPath(walkable, sx, sz, gx, gz, { step = 2, maxNodes = 6000 } = {}) {
22
+ export function findPath(walkable, sx, sz, gx, gz, { radius, step = defaultStep(radius), maxNodes = defaultNodes(step) } = {}) {
23
+ const sample = Math.min(0.75, Math.max(0.15, radius ?? 0.4)); // smoothing samples a segment at most one radius apart: walkable() already grows colliders by radius, so nothing 2r wide is stepped over
17
24
  const key = (i, j) => i * 100003 + j;
18
25
  const si = Math.round(sx / step), sj = Math.round(sz / step), gi = Math.round(gx / step), gj = Math.round(gz / step);
19
26
  const open = new MinHeap(), g = new Map(), from = new Map(), walk = new Map();
@@ -27,8 +34,8 @@ export function findPath(walkable, sx, sz, gx, gz, { step = 2, maxNodes = 6000 }
27
34
  if (i === gi && j === gj) {
28
35
  const path = []; let k = key(i, j), cur = [i, j];
29
36
  while (cur) { path.push({ x: cur[0] * step, z: cur[1] * step }); cur = from.get(k); if (cur) k = key(cur[0], cur[1]); }
30
- path.reverse(); path[path.length - 1] = { x: gx, z: gz };
31
- return simplify(walkable, path);
37
+ path.reverse(); path[0] = { x: sx, z: sz }; path[path.length - 1] = { x: gx, z: gz }; // real start, not the snapped cell centre (which may even lie behind a wall)
38
+ return simplify(walkable, path, sample);
32
39
  }
33
40
  const gc = g.get(key(i, j));
34
41
  for (const [di, dj, c] of dirs) {
@@ -41,19 +48,19 @@ export function findPath(walkable, sx, sz, gx, gz, { step = 2, maxNodes = 6000 }
41
48
  return null;
42
49
  }
43
50
  // drop redundant corners: go straight when two points are directly walkable
44
- function simplify(walkable, path) {
51
+ function simplify(walkable, path, sample) {
45
52
  if (path.length < 3) return path;
46
53
  const out = [path[0]];
47
54
  let a = 0;
48
55
  while (a < path.length - 1) {
49
56
  let b = path.length - 1;
50
- while (b > a + 1 && !lineClear(walkable, path[a], path[b])) b--;
57
+ while (b > a + 1 && !lineClear(walkable, path[a], path[b], sample)) b--;
51
58
  out.push(path[b]); a = b;
52
59
  }
53
60
  return out;
54
61
  }
55
- function lineClear(walkable, p, q) {
56
- const d = Math.hypot(q.x - p.x, q.z - p.z), n = Math.ceil(d / 1.5);
62
+ function lineClear(walkable, p, q, sample) {
63
+ const d = Math.hypot(q.x - p.x, q.z - p.z), n = Math.ceil(d / sample);
57
64
  for (let i = 1; i < n; i++) { const t = i / n; if (!walkable(p.x + (q.x - p.x) * t, p.z + (q.z - p.z) * t)) return false; }
58
65
  return true;
59
66
  }
@@ -15,6 +15,7 @@ import { findPath } from './astar.js';
15
15
  import { findSpawn, moveInput } from './moveHelpers.js';
16
16
  import { AsyncPaths } from './pathAsync.js';
17
17
  import { checkOptions, warnOnce, DEV } from '../../core/validate.js';
18
+ import { readParams, keysSchema } from '../../core/params.js';
18
19
  import { codedError, coded } from '../../core/errorHints.js';
19
20
  import { DEV_STRINGS, STRINGS, validControl } from './playerStrings.js';
20
21
  import { footstepSynth, stepSound } from './footsteps.js';
@@ -41,20 +42,22 @@ function solvePath(e, from, to, o) {
41
42
  else if (!e.collision) res = { status: 'notReady', path: null };
42
43
  else {
43
44
  const [sx, sz] = xzOf(from), [gx, gz] = xzOf(to), radius = rest.radius ?? e.movement.radius;
44
- const path = findPath((x, z) => e.collision.walkableAt(x, z, radius), sx, sz, gx, gz, rest);
45
+ const path = findPath((x, z) => e.collision.walkableAt(x, z, radius), sx, sz, gx, gz, { ...rest, radius });
45
46
  // nav installed but not ready: A* is only a stand-in, tell the caller honestly
46
47
  res = { status: e.nav ? 'notReady' : path ? 'ok' : 'noPath', path };
47
48
  }
48
49
  return detailed ? res : res.path;
49
50
  }
50
51
 
52
+ const CHARACTERS_PARAMS = keysSchema(['npcs', 'brakeKeys', 'brakePad']);
53
+
51
54
  export function characters(opts = {}) {
55
+ readParams('characters', CHARACTERS_PARAMS, opts);
52
56
  const { npcs = true, brakeKeys, brakePad } = opts; // no brake key by default: characters({ ...presets.keys.brake }) or the game's own
53
57
  let mgr = null, paths = null, disposePlayer = null;
54
58
  return {
55
- name: 'characters', label: 'Characters', optional: ['cameraRig', 'sky', 'interactions', 'dialogue', 'nav', 'collision', 'rigid', 'world'],
59
+ name: 'characters', params: CHARACTERS_PARAMS, options: opts, label: 'Characters', noSkip: 'fixed only flushes path requests; schedules read the sky clock', optional: ['cameraRig', 'sky', 'interactions', 'dialogue', 'nav', 'collision', 'rigid', 'world'],
56
60
  install(e) {
57
- checkOptions('characters()', opts, ['npcs', 'brakeKeys', 'brakePad']);
58
61
  e.i18n.add(STRINGS);
59
62
  e.audio.register('footstep', footstepSynth, { builtIn: true });
60
63
  if (npcs) { mgr = new NPCManager(e); e.npcs = mgr; }
@@ -16,7 +16,12 @@ export function simpleMover(c) {
16
16
  const nh = e.surface(p.x, p.z, p.y), step = Math.hypot(p.x - ox, p.z - oz), maxClimb = e.collision?.maxClimb ?? e.movement.slopeRatio, rise = nh - Math.max(oh, c.grounded ? oh : p.y);
17
17
  const blocked = c.grounded ? (rise > c.stepHeight && step > 1e-4 && (nh - oh) / step > maxClimb) : nh > p.y + c.stepHeight;
18
18
  if (blocked) { p.x = ox; p.z = oz; c.velocity.set(0, 0); }
19
- e.collision?.resolve(p, c.radius);
19
+ const col = e.collision;
20
+ if (col?._blocked.length && col.blockedAt(p.x, p.z, c.radius)) { // addBlocked ground (river): slide along it, else stay put
21
+ const nx = p.x, nz = p.z;
22
+ if (!col.blockedAt(nx, oz, c.radius)) p.z = oz; else if (!col.blockedAt(ox, nz, c.radius)) p.x = ox; else { p.x = ox; p.z = oz; c.velocity.set(0, 0); }
23
+ }
24
+ col?.resolve(p, c.radius);
20
25
 
21
26
  const { ground, swimY } = water(c, ox, oz);
22
27
 
@@ -56,6 +56,12 @@ export function advance(e, W, rec, seconds) {
56
56
  settle(e, W, rec, x, z, Math.hypot(g.x - x, g.z - z) > rec.arriveDistance);
57
57
  }
58
58
 
59
+ /** Set rec.state; with events.traceSize > 0 a change is noted as an `npc:state` trace entry (from, to), so "why did it stop" has a cause chain */
60
+ function noteState(e, rec, next) {
61
+ if (rec.state !== next && e.events.traceSize > 0) e.events.note('npc:state', { obj: rec.id, data: { from: rec.state ?? null, to: next } });
62
+ rec.state = next;
63
+ }
64
+
59
65
  /**
60
66
  * Settle without a model: write the computed x, z back to data (position, facing, animation state); shared by every behaviour's far. The path is for the model,
61
67
  * so it is re-found at the new position after the model is built
@@ -65,7 +71,7 @@ export function settle(e, W, rec, x, z, moving) {
65
71
  const m = rec.motion ??= {};
66
72
  const facing = x !== p.x || z !== p.z ? Math.atan2(x - p.x, z - p.z) : m.facing ?? 0;
67
73
  Object.assign(m, { vx: 0, vz: 0, vy: 0, amount: 0, facing, grounded: true, swimming: false, coyote: 0 });
68
- rec.state = moving ? 'walk' : 'idle';
74
+ noteState(e, rec, moving ? 'walk' : 'idle');
69
75
  // NPC of another level: this level's ground height is meaningless for it, keep its y
70
76
  const here = rec.zone == null || W.zone == null || rec.zone === W.zone;
71
77
  W.move(rec.id, { x, y: here ? e.surface(x, z) : p.y, z });
@@ -121,7 +127,7 @@ export function goTo(e, W, rec, ch, goal, dt) {
121
127
  // position belongs to the mover: copy the model position back to data here (world also copies at the end of each fixed step; copying now means later
122
128
  // simulation and saves this step see the latest)
123
129
  rec.motion = ch.saveMotion(rec.motion ?? {});
124
- rec.state = ch.state;
130
+ noteState(e, rec, ch.state);
125
131
  W.move(rec.id, p);
126
132
  }
127
133
 
@@ -4,7 +4,7 @@
4
4
  // solveBatch runs here at the due step. The batch is tagged with the walkable state it was computed on (navmesh revision or collision version);
5
5
  // if that changed before it lands, it is recomputed here on the current state, so threads on / off / slow / crashed give identical paths.
6
6
  import { xzOf } from '../../core/math.js';
7
- import { solveBatch, pathHandler, RES, TILE, tileOf } from './pathJob.js';
7
+ import { solveBatch, pathHandler, astarDefaults, RES, TILE, tileOf } from './pathJob.js';
8
8
 
9
9
  /** Steps between sending a batch and its answers taking effect (4 = 67 ms): enough for a worker round trip, short enough that an NPC barely waits */
10
10
  const PATH_LAG = 4;
@@ -53,7 +53,7 @@ export class AsyncPaths {
53
53
  const reqs = list.map(({ sx, sz, gx, gz, o }) => {
54
54
  if (mode === 'nav') return { mode, s: { x: sx, y: e.surface(sx, sz), z: sz }, g: { x: gx, y: e.surface(gx, gz), z: gz }, reach: e.nav.reach(o.radius) };
55
55
  if (mode === 'none') return { mode };
56
- const radius = o.radius ?? e.movement.radius, step = o.step ?? 2, maxNodes = o.maxNodes ?? 6000;
56
+ const radius = o.radius ?? e.movement.radius, dflt = astarDefaults(radius), step = o.step ?? dflt.step, maxNodes = o.maxNodes ?? dflt.maxNodes;
57
57
  // A* may wander this far beyond the start-goal box; bounded by how far maxNodes cells can reach
58
58
  const m = Math.min(step * Math.sqrt(maxNodes / Math.PI), 16 + Math.hypot(gx - sx, gz - sz) / 2);
59
59
  for (let tx = tileOf(Math.min(sx, gx) - m); tx <= tileOf(Math.max(sx, gx) + m); tx++)
@@ -68,12 +68,18 @@ export class AsyncPaths {
68
68
  */
69
69
  tile(k, tx, tz) {
70
70
  const e = this.e, c = this.tiles.get(k);
71
- if (c && e.tick - c.at < TILE_TTL) return c;
72
- const data = new Uint8Array(TILE * TILE), col = e.collision, trees = [], span = TILE * RES;
73
- for (let j = 0; j < TILE; j++) for (let i = 0; i < TILE; i++) data[j * TILE + i] = col.groundWalkable((tx * TILE + i) * RES, (tz * TILE + j) * RES) ? 1 : 0;
71
+ const bv = e.collision.blockedVersion;
72
+ if (c && c.bv === bv && e.tick - c.at < TILE_TTL) return c;
73
+ const data = new Uint8Array(TILE * TILE), col = e.collision, trees = [], span = TILE * RES, blocked = col._blocked.length > 0;
74
+ // addBlocked fields are functions and cannot go to a worker: they are sampled into this same raster (the worker sees blocked cells as unwalkable).
75
+ // A cell counts as blocked if fn is true at its centre or on a ring of half a cell (blockedAt), so a 1 m cell never hides a thin river; bounds skip the sampling outside.
76
+ for (let j = 0; j < TILE; j++) for (let i = 0; i < TILE; i++) {
77
+ const x = (tx * TILE + i) * RES, z = (tz * TILE + j) * RES;
78
+ data[j * TILE + i] = col.groundWalkable(x, z) && !(blocked && col.blockedAt(x, z, RES / 2)) ? 1 : 0;
79
+ }
74
80
  // every collider that can touch a point of the tile: half diagonal + the largest character radius we expect + 1 (the same reach walkableAt uses)
75
81
  e.ground.forEachCollider?.((tx + 0.5) * span, (tz + 0.5) * span, span * 0.71 + 3, (x, z, r) => { trees.push(x, z, r); });
76
- const v = { data, trees, at: e.tick };
82
+ const v = { data, trees, at: e.tick, bv };
77
83
  this.tiles.set(k, v);
78
84
  if (this.tiles.size > 4096) for (const [kk, o] of this.tiles) if (e.tick - o.at >= TILE_TTL) this.tiles.delete(kk);
79
85
  return v;
@@ -2,7 +2,8 @@
2
2
  // and in engine.commits' fallback when a worker reply is late (pathAsync.js). Worker-safe: no three.js, no engine objects.
3
3
  // A batch carries everything that is not mirrored in the worker: start / goal (with ground heights), and for A* a raster of the ground half of walkability.
4
4
  // The worker mirrors the rest: the navmesh (imported from the bytes the nav module exports) and the collision module's colliders (rebuilt into the same grid).
5
- import { findPath as astar } from './astar.js';
5
+ import { findPath as astar, astarDefaults } from './astar.js';
6
+ export { astarDefaults };
6
7
  import { CollisionGrid, gridBlocks } from '../collision/grid.js';
7
8
  import { navSearch } from '../nav/navPath.js';
8
9
 
@@ -1,15 +1,50 @@
1
- // The procedural body of a Character (split out of Character.js): the gray capsule used when nothing draws a character, attaching a style pack's rig,
2
- // and the limb swing / body bob used when the character has no skeletal animation.
3
- // A rig is { root, body?, head?, joints?: { name: Group }, limbs: [{ joint, offset: 0 | Math.PI, amp, kind: 'arm' | 'leg', side? }] }; the style pack builds it.
1
+ // The procedural body of a Character (split out of Character.js): the gray capsule used when no model gives a body, attaching a rig, reading a rig
2
+ // out of a model asset (a pack's humanoid), per-character part colors, and the limb swing / body bob used without skeletal animation.
3
+ // A rig is { root, body?, head?, joints?: { name: Group }, limbs: [{ joint, offset: 0 | Math.PI, amp, kind: 'arm' | 'leg', side? }] }.
4
+ // A model asset carries the same thing as plain data by object NAME in root.userData.rig: names, not references, because userData survives
5
+ // clone and GLB export and object references do not; so a procedural builder and a baked / hand-made GLB with those names animate the same way.
4
6
  import * as THREE from 'three';
5
7
  import { makeMaterial } from '../../render/materials.js';
8
+ import { warnOnce } from '../../core/validate.js';
6
9
 
7
- /** Warned once when no style pack and no model give the character a body */
8
- export const NO_CHARACTER = 'characters: no style pack / model given, so characters are gray capsules (a placeholder). Pass one: a model '
9
- + "(createPlayer({ model: 'hero' }) or style.character.model), or a style pack whose style.character.create builds one, "
10
- + "e.g. createEngine({ style: lowpoly }) with lowpoly from '@threedog/style-lowpoly'";
10
+ /** Warned once when no model gives the character a body */
11
+ export const NO_CHARACTER = 'characters: no model given, so characters are gray capsules (a placeholder). Character bodies are assets: '
12
+ + "register a pack's models (engine.assets.manifest(yourAssets)) and pass createPlayer({ model: 'yourBody' }), "
13
+ + "a GLB asset name ({ model: 'hero' }), or a ready body ({ rig })";
11
14
 
12
- /** Neutral placeholder when the style pack draws no character: one gray capsule, no limbs (the shape belongs to style packs) */
15
+ /**
16
+ * The rig a model asset describes in root.userData.rig ({ body, head, joints: [names], limbs: [{ joint: name, offset, amp, kind, side }] }), names
17
+ * resolved to this copy's objects; null without rig data (a skinned GLB animates by clips instead).
18
+ * @param {THREE.Object3D} root
19
+ */
20
+ export function rigFromObject(root) {
21
+ const d = root?.userData?.rig;
22
+ if (!d) return null;
23
+ const get = n => {
24
+ const o = n ? root.getObjectByName(n) : null;
25
+ if (n && !o) warnOnce(`character model "${root.name || 'model'}": userData.rig names "${n}", but the model has no object with that name`);
26
+ return o || null;
27
+ };
28
+ const joints = {};
29
+ for (const n of d.joints || []) { const o = get(n); if (o) joints[n] = o; }
30
+ const limbs = (d.limbs || []).map(L => ({ ...L, joint: get(L.joint) })).filter(L => L.joint);
31
+ return { root, body: get(d.body), head: get(d.head), joints, limbs };
32
+ }
33
+
34
+ /**
35
+ * Per-character part colors ({ colors: { body: 0x4f6d8f } }): meshes marked userData.part get their own copy of the material in that color.
36
+ * A copy, because asset copies share materials: recoloring in place would recolor every character using the model.
37
+ */
38
+ export function tintParts(root, colors) {
39
+ if (!colors || !Object.keys(colors).length) return;
40
+ root.traverse(o => {
41
+ const c = o.isMesh ? colors[o.userData.part] : null;
42
+ if (c == null || !o.material?.color) return;
43
+ o.material = o.material.clone(); o.material.color.set(c);
44
+ });
45
+ }
46
+
47
+ /** Neutral placeholder when no model gives a body: one gray capsule, no limbs (body shapes belong to asset packs) */
13
48
  export function capsule(color, engine) {
14
49
  const body = new THREE.Group(); body.position.y = 0.85;
15
50
  const m = new THREE.Mesh(new THREE.CapsuleGeometry(0.3, 1.0, 4, 12).translate(0, -0.05, 0), makeMaterial('character', { color }, engine));
@@ -20,12 +55,16 @@ export function capsule(color, engine) {
20
55
 
21
56
  /** Put a rig under the character root and remember its parts */
22
57
  export function useRig(ch, rig) {
23
- ch.root.add(rig.root); ch._rig = rig;
58
+ if (rig.root.parent !== ch.root) ch.root.add(rig.root);
59
+ ch._rig = rig;
24
60
  ch.hips = rig.body || rig.root; ch.head = rig.head || null;
25
61
  ch.bodyBase = ch.hips.position.y;
26
62
  ch.limbs = rig.limbs || [];
27
- // named joints (lowpoly humanoid: armL armR legL legR) become properties so game poses can grab them; never shadow a Character field
28
- for (const k in rig.joints || {}) if (!(k in ch)) ch[k] = rig.joints[k];
63
+ // named joints (a humanoid rig: armL armR legL legR) become properties so game poses can grab them; never shadow a Character field
64
+ for (const k in rig.joints || {}) {
65
+ if (!(k in ch)) ch[k] = rig.joints[k];
66
+ else if (ch[k] !== rig.joints[k]) warnOnce(`character rig: joint "${k}" has the same name as the Character field ch.${k}, so ch.${k} stays the field; use rig.joints.${k} (or rename the joint)`);
67
+ }
29
68
  }
30
69
 
31
70
  /** Swing the limbs and bob the body for the current state (sp = move amount, t = elapsed seconds, st = character state) */
@@ -0,0 +1,22 @@
1
+ // Swap a loaded glTF model into a Character: attach it and build its animation state machine from the default / mapped / game-given clips.
2
+ // Split out of Character.js; Character._useModel calls it.
3
+ import { warnOnce } from '../../core/validate.js';
4
+ import { findClip } from '../../core/Animator.js';
5
+
6
+ const DEFAULT_CLIPS = { idle: 'Idle', walk: 'Walk', run: 'Run', swim: 'Swim', jump: 'Jump', fall: 'Fall', drive: 'Drive' };
7
+
8
+ export function useModel(ch, model, clips, animation) {
9
+ const engine = ch.engine; ch.root.add(model);
10
+ // a bone named like a Character field (e.g. "head", "root", "state") makes `ch[name]` mean the field, not the bone: easy to miss when a game
11
+ // reads bones by name; say it once per name and point at the safe lookup
12
+ model.traverse(o => { if (o.isBone && o.name && o.name in ch) warnOnce(`character model "${model.name || 'model'}": bone "${o.name}" has the same name as the Character field ch.${o.name}; read the bone with ch.root.getObjectByName('${o.name}'), not ch.${o.name}, or rename the bone`); });
13
+ const states = {};
14
+ // default names only where the model has the clip (a model without Swim is fine) and the manifest mapped nothing (Assets.animate merges that under
15
+ // these states, so a default Idle must not shadow a mapped Idle_Sword); names the game wrote are always kept so a typo is reported
16
+ const have = model.userData.animations || [], map = engine.assets.mapping(model), mapped = map?.states || {};
17
+ for (const [st, clip] of Object.entries(DEFAULT_CLIPS)) if (!mapped[st] && findClip(have, clip)) states[st] = { clip };
18
+ for (const [st, clip] of Object.entries(clips || {})) states[st] = { clip };
19
+ // the model's own mapping (fade, transitions) beats the style pack's default for every character; the game's per-character config beats both
20
+ ch.anim = engine.assets.animate(model, { ...engine.style.character?.animation, ...map, states, ...(animation || {}) });
21
+ ch.anim.afterPose = dt => ch._firePose(dt); // a mixer pose is applied inside the Animator's update, so the Animator tells us when it is done
22
+ }
@@ -0,0 +1,58 @@
1
+ // character.walkTo(target, opts): follow characters.findPath on fixed steps. Exists so a hand-written guard / pet / follower does not re-implement
2
+ // path following (turn rate, skipping passed points, stuck detection) every time. Steering only: the mover still owns position (see Character.js).
3
+ // Transient on purpose (like a noSkip timer): a walk is not saved and engine.skip does not fast-forward it. So it never outlives what it steers:
4
+ // one walk per character (a new walkTo cancels the old, else two hooks would fight over move()), and character.dispose() or a save load
5
+ // ends it with 'cancelled' (the loaded state has its own positions; the old path no longer applies). A game that must resume a walk saves the target.
6
+ import { xzOf } from '../../core/math.js';
7
+
8
+ const STUCK_PROGRESS = 0.15; // metres the character must gain on the next point within the stuck window, else it counts as stuck
9
+
10
+ /**
11
+ * @param {any} ch Character
12
+ * @returns {Promise<{ status: 'arrived' | 'noPath' | 'stuck' | 'cancelled' }> & { remove(): void }}
13
+ */
14
+ export function walkTo(ch, target, { speed, arrive = 0.5, turnRate = 8, stuckSeconds = 1.5, maxRepaths = 3, run = false } = {}) {
15
+ const e = ch.engine;
16
+ let done, hook, path = null, i = 0, heading = null, repaths = 0, bestD = Infinity, stuckT = 0;
17
+ const promise = new Promise(res => { done = res; });
18
+ ch._walk?.remove(); // one walk per character: the newer order wins
19
+ let onLoad = null, handle = null;
20
+ const finish = status => { if (!hook) return; hook.remove(); hook = null; onLoad?.remove(); if (ch._walk === handle) ch._walk = null; done({ status }); };
21
+ const dist = (p, x, z) => Math.hypot(p.x - x, p.z - z);
22
+ // points the character is already at or past (a later point is closer) would make it turn back, so drop them
23
+ const skipPassed = (x, z) => {
24
+ while (i < path.length - 1 && (dist(path[i], x, z) < arrive * 0.6 || dist(path[i + 1], x, z) < dist(path[i], x, z))) i++;
25
+ };
26
+ const solve = () => {
27
+ path = e.characters.findPath(ch.root.position, target, { radius: ch.radius });
28
+ i = 0; bestD = Infinity; stuckT = 0;
29
+ if (!path || !path.length) return false;
30
+ const [x, z] = xzOf(ch.root.position);
31
+ skipPassed(x, z);
32
+ return true;
33
+ };
34
+ if (!solve()) { queueMicrotask(() => done({ status: 'noPath' })); return Object.assign(promise, { remove() {} }); }
35
+ onLoad = e.events.on('save:loaded', () => finish('cancelled'));
36
+ hook = e.onFixed(dt => {
37
+ const [gx, gz] = xzOf(target), [x, z] = xzOf(ch.root.position);
38
+ if (Math.hypot(gx - x, gz - z) <= arrive) { ch.move(0, 0, false, dt); return finish('arrived'); }
39
+ skipPassed(x, z);
40
+ const p = path[i], d = dist(p, x, z);
41
+ // stuck: no gain on the next point for stuckSeconds, so replan; give up after maxRepaths
42
+ if (d < bestD - STUCK_PROGRESS) { bestD = d; stuckT = 0; }
43
+ else if ((stuckT += dt) > stuckSeconds) {
44
+ if (++repaths > maxRepaths || !solve()) { ch.move(0, 0, false, dt); return finish(repaths > maxRepaths ? 'stuck' : 'noPath'); }
45
+ return;
46
+ }
47
+ const want = Math.atan2(p.x - x, p.z - z);
48
+ heading ??= ch.facing;
49
+ let diff = want - heading; diff -= Math.PI * 2 * Math.round(diff / (Math.PI * 2));
50
+ const step = turnRate * dt;
51
+ heading += Math.abs(diff) <= step ? diff : Math.sign(diff) * step;
52
+ // slow down while the body is still turning toward the point, so it does not overshoot sideways
53
+ const align = Math.max(0.2, Math.cos(Math.min(Math.abs(diff), Math.PI / 2)));
54
+ ch.move(Math.sin(heading), Math.cos(heading), run, dt, (speed ?? (run ? ch.runSpeed : ch.speed)) * align);
55
+ });
56
+ handle = Object.assign(promise, { remove() { finish('cancelled'); } });
57
+ return ch._walk = handle;
58
+ }