threedog 1.0.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +90 -0
- package/README.md +1 -1
- package/core/assets/Animator.js +41 -3
- package/core/assets/Assets.js +100 -24
- package/core/assets/assetEntry.js +73 -20
- package/core/assets/assetHot.js +68 -16
- package/core/assets/assetLoad.js +6 -6
- package/core/assets/assetLod.js +9 -2
- package/core/assets/assetManifest.js +12 -2
- package/core/assets/assetPart.js +54 -0
- package/core/assets/ik.js +271 -0
- package/core/assets/modelNeeds.js +37 -0
- package/core/assets/namedModel.js +102 -29
- package/core/assets/nodeVisibility.js +15 -0
- package/core/audio/Audio.js +36 -4
- package/core/audio/audioReverb.js +99 -0
- package/core/audio/audioRules.js +1 -1
- package/core/audio/audioVoice.js +1 -1
- package/core/base/Events.js +14 -4
- package/core/base/Random.js +1 -1
- package/core/base/Vars.js +1 -1
- package/core/base/docRef.js +51 -0
- package/core/base/errorCodes.js +178 -126
- package/core/base/errorHints.js +9 -7
- package/core/base/errors.js +25 -10
- package/core/base/events.generated.js +2 -0
- package/core/base/freeParts.js +76 -0
- package/core/base/math.js +28 -0
- package/core/base/sections.js +5 -5
- package/core/base/validate.js +31 -3
- package/core/engine/Engine.js +16 -6
- package/core/engine/Loading.js +5 -3
- package/core/engine/copies.js +1 -1
- package/core/engine/headlessLoad.js +4 -1
- package/core/engine/lifecycle.js +32 -16
- package/core/engine/loop.js +71 -27
- package/core/engine/moduleSlots.js +2 -2
- package/core/engine/moduleTypes.js +3 -3
- package/core/engine/modules.js +65 -39
- package/core/engine/page.js +6 -3
- package/core/engine/services.js +6 -5
- package/core/engine/startup.js +5 -5
- package/core/input/Input.js +28 -14
- package/core/input/inputContext.js +28 -16
- package/core/input/inputKeyboard.js +31 -3
- package/core/input/inputPad.js +4 -0
- package/core/input/inputPointer.js +2 -1
- package/core/input/inputSeat.js +1 -1
- package/core/inspect/Budget.js +109 -19
- package/core/inspect/DebugOverrides.js +28 -4
- package/core/inspect/Describe.js +17 -9
- package/core/inspect/Inspect.js +4 -2
- package/core/inspect/InspectMaterials.js +3 -1
- package/core/inspect/InspectPerf.js +19 -9
- package/core/inspect/InspectScene.js +32 -7
- package/core/inspect/MaterialInfo.js +19 -2
- package/core/inspect/UrlState.js +46 -27
- package/core/inspect/catalog.js +28 -9
- package/core/inspect/debugView.js +2 -1
- package/core/inspect/describeRender.js +25 -13
- package/core/inspect/describeText.js +14 -6
- package/core/inspect/lightWatch.js +1 -1
- package/core/inspect/metadata.generated.js +35 -17
- package/core/inspect/pictureChecks.js +148 -0
- package/core/inspect/pictureMenu.js +84 -0
- package/core/inspect/pictureWriters.js +26 -6
- package/core/inspect/textureBytes.js +12 -2
- package/core/inspect/toolDoor.js +2 -4
- package/core/ops/Ops.js +11 -4
- package/core/ops/holds.js +27 -10
- package/core/ops/opsAtomic.js +15 -7
- package/core/ops/opsGuard.js +2 -2
- package/core/ops/opsRun.js +8 -7
- package/core/ops/sharedPoint.js +72 -21
- package/core/ops/stacks.js +56 -16
- package/core/saves/SaveStore.js +9 -3
- package/core/saves/Saves.js +32 -23
- package/core/saves/saveApply.js +96 -44
- package/core/saves/saveIds.js +1 -1
- package/core/saves/saveVersions.js +7 -5
- package/core/saves/session.js +17 -8
- package/core/saves/stateReplace.js +34 -15
- package/core/scene/Rays.js +52 -10
- package/core/scene/Views.js +13 -7
- package/core/scene/adaptive.js +144 -21
- package/core/scene/drawOnly.js +17 -0
- package/core/scene/gameLights.js +44 -3
- package/core/scene/sceneMethods.js +13 -11
- package/core/scene/stepPoses.js +11 -3
- package/core/scene/targeting.js +5 -3
- package/core/scene/thingOps.js +1 -1
- package/core/scene/tier.js +15 -0
- package/core/stream/Batching.js +30 -7
- package/core/stream/Stream.js +26 -7
- package/core/stream/batchGroups.js +2 -2
- package/core/stream/chunkStream.js +7 -5
- package/core/stream/prepare.js +77 -0
- package/core/time/skip.js +3 -1
- package/core/time/time.js +4 -2
- package/docs/AI.md +82 -83
- package/docs/API.md +16 -16
- package/docs/CODEMAP.md +16 -11
- package/docs/COMMANDS.md +31 -33
- package/docs/CONVENTIONS.md +37 -49
- package/docs/MIGRATING-0.8.md +2 -2
- package/docs/MIGRATING-1.0.md +2 -2
- package/docs/THREE.md +28 -35
- package/docs/api/assets.md +3 -1
- package/docs/api/audio.md +4 -2
- package/docs/api/budget.md +5 -0
- package/docs/api/cameraRig.md +2 -2
- package/docs/api/characters.md +10 -8
- package/docs/api/collision.md +6 -4
- package/docs/api/engine.md +16 -16
- package/docs/api/events.md +3 -2
- package/docs/api/ground.md +6 -5
- package/docs/api/hud.md +4 -2
- package/docs/api/input.md +5 -5
- package/docs/api/particles.md +2 -1
- package/docs/api/photo.md +3 -0
- package/docs/api/post.md +7 -4
- package/docs/api/quests.md +2 -2
- package/docs/api/rays.md +1 -2
- package/docs/api/saves.md +7 -7
- package/docs/api/settings.md +2 -2
- package/docs/api/tools.md +3 -1
- package/docs/api/vars.md +1 -1
- package/docs/api/vegetation.md +4 -2
- package/docs/api/world.md +1 -1
- package/docs/recipes/01-new-game.md +16 -17
- package/docs/recipes/02-npc.md +22 -18
- package/docs/recipes/03-items-pickups.md +37 -35
- package/docs/recipes/04-quests.md +15 -10
- package/docs/recipes/05-props-bake.md +101 -95
- package/docs/recipes/06-clock-events.md +28 -28
- package/docs/recipes/07-flow-scenes-pause.md +29 -26
- package/docs/recipes/08-weather-sky.md +52 -64
- package/docs/recipes/09-materials-lights-models.md +26 -17
- package/docs/recipes/10-blender-level.md +15 -10
- package/docs/recipes/11-vehicles.md +12 -7
- package/docs/recipes/12-navmesh.md +44 -26
- package/docs/recipes/13-animation.md +56 -45
- package/docs/recipes/14-custom-module.md +21 -18
- package/docs/recipes/15-perf.md +61 -55
- package/docs/recipes/16-dev-bridge.md +23 -33
- package/docs/recipes/18-world.md +36 -42
- package/docs/recipes/19-shooting-picking.md +20 -15
- package/docs/recipes/20-content-actions-save.md +48 -56
- package/docs/recipes/21-camera.md +45 -54
- package/docs/recipes/22-shop-gold.md +12 -7
- package/docs/recipes/23-ops.md +25 -23
- package/docs/recipes/26-ui-parts.md +67 -47
- package/docs/recipes/27-net.md +12 -7
- package/docs/recipes/28-terrain.md +24 -21
- package/docs/recipes/29-grid.md +32 -27
- package/docs/recipes/30-templates.md +21 -20
- package/docs/recipes/31-audio.md +39 -22
- package/docs/recipes/32-action-game.md +19 -14
- package/docs/recipes/33-stream-sources.md +15 -11
- package/docs/recipes/34-environment-lighting.md +126 -70
- package/docs/recipes/35-picture-from-reference.md +8 -8
- package/docs/recipes/36-ground-plants.md +27 -21
- package/docs/recipes/40-scene.md +19 -28
- package/docs/recipes/43-shader-patches-surfaces.md +15 -12
- package/docs/recipes/44-water-weather-hooks.md +34 -31
- package/docs/recipes/45-cascaded-shadows.md +35 -26
- package/docs/recipes/46-blender-art-route.md +6 -1
- package/docs/recipes/49-game-module-contract.md +13 -8
- package/docs/recipes/50-own-renderer.md +6 -2
- package/docs/recipes/51-capability-catalog.md +15 -8
- package/docs/recipes/52-around-the-picture.md +34 -32
- package/docs/recipes/53-ground-up-close.md +6 -1
- package/docs/recipes/55-mods-time-wrap.md +27 -19
- package/docs/recipes/56-webgpu-tsl.md +74 -43
- package/docs/recipes/57-control.md +18 -13
- package/docs/recipes/58-input.md +26 -16
- package/docs/recipes/59-depth-post-effects.md +8 -3
- package/docs/recipes/60-judge-the-picture.md +9 -8
- package/docs/recipes/61-deploy.md +5 -0
- package/docs/recipes/62-picture-code.md +70 -79
- package/docs/recipes/63-third-person-start.md +47 -45
- package/docs/recipes/64-particles.md +22 -10
- package/docs/recipes/65-swarm.md +18 -13
- package/docs/recipes/66-common-tasks.md +38 -35
- package/examples/action/GAMEMAP.md +2 -3
- package/examples/action/main.js +3 -3
- package/examples/action/picture/lights.js +3 -1
- package/examples/perf-island/GAMEMAP.md +3 -3
- package/examples/perf-island/picture/lights.js +2 -1
- package/examples/plain-picture/GAMEMAP.md +1 -1
- package/examples/rc2d/GAMEMAP.md +1 -1
- package/examples/styletest/GAMEMAP.md +2 -2
- package/examples/styletest/main.js +1 -1
- package/examples/techniques/interior-light/README.md +3 -3
- package/examples/techniques/interior-light/interiorLight.js +2 -4
- package/examples/techniques/interior-light/picture/lights.js +2 -1
- package/examples/techniques/modular-building/picture/lights.js +3 -1
- package/examples/techniques/outlines-and-rim/picture/lights.js +3 -1
- package/examples/techniques/procedural-animation/README.md +1 -1
- package/examples/techniques/procedural-animation/main.js +1 -1
- package/examples/webgpu-tsl/GAMEMAP.md +1 -1
- package/examples/world/GAMEMAP.md +2 -3
- package/examples/world/art/humanoid.js +1 -1
- package/examples/world/main.js +6 -3
- package/index.d.ts +2 -2
- package/llms.txt +101 -0
- package/modules/ambience/Ambience.js +21 -5
- package/modules/calendar/index.js +9 -5
- package/modules/calendar/schedule.js +23 -8
- package/modules/camera/FirstPersonCamera.js +3 -1
- package/modules/camera/FollowCamera.js +10 -5
- package/modules/camera/RtsCamera.js +4 -3
- package/modules/camera/common.js +70 -8
- package/modules/camera/contract.js +1 -1
- package/modules/characters/Character.js +16 -10
- package/modules/characters/NPC.js +31 -19
- package/modules/characters/assetModel.js +14 -9
- package/modules/characters/astar.js +6 -1
- package/modules/characters/contract.js +2 -2
- package/modules/characters/index.js +34 -22
- package/modules/characters/movers/manual.js +1 -1
- package/modules/characters/movers/rapier.js +17 -2
- package/modules/characters/movers/simple.js +1 -1
- package/modules/characters/movers/support.js +16 -7
- package/modules/characters/npcAvoid.js +2 -2
- package/modules/characters/npcSim.js +3 -2
- package/modules/characters/pathAsync.js +24 -8
- package/modules/characters/pathJob.js +1 -1
- package/modules/characters/player.js +10 -9
- package/modules/characters/playerStrings.js +5 -5
- package/modules/characters/proceduralRig.js +5 -5
- package/modules/characters/useModel.js +6 -0
- package/modules/characters/walkTo.js +1 -1
- package/modules/collision/Collision.js +29 -18
- package/modules/collision/grid.js +22 -4
- package/modules/content/index.js +3 -1
- package/modules/content/loader.js +1 -1
- package/modules/content/models.js +82 -33
- package/modules/content/props.js +2 -1
- package/modules/content/rules.js +11 -5
- package/modules/content/templates.js +3 -3
- package/modules/content/words.js +2 -2
- package/modules/debug/DebugPanel.js +9 -9
- package/modules/flow/index.js +9 -6
- package/modules/gameplay/Dialogue.js +34 -20
- package/modules/gameplay/Interactions.js +19 -15
- package/modules/gameplay/Inventory.js +9 -4
- package/modules/gameplay/Quests.js +12 -10
- package/modules/gameplay/pickups.js +23 -11
- package/modules/grid/index.js +1 -1
- package/modules/grid/preview.js +2 -2
- package/modules/grid/tiles.js +1 -1
- package/modules/hlod/index.js +4 -1
- package/modules/hud/index.js +47 -10
- package/modules/hud/parts.js +28 -9
- package/modules/level/geometry.js +8 -3
- package/modules/level/index.js +10 -5
- package/modules/level/load.js +4 -2
- package/modules/lights/sources.js +1 -1
- package/modules/music/Music.js +22 -4
- package/modules/nav/index.js +20 -10
- package/modules/particles/Particles.js +31 -14
- package/modules/particles/effect.js +20 -5
- package/modules/particles/lit.js +72 -0
- package/modules/photo/Photo.js +72 -28
- package/modules/photo/pathTrace.js +106 -0
- package/modules/rigid/RigidBodies.js +23 -14
- package/modules/rigid/Vehicles.js +3 -13
- package/modules/rigid/sync.js +2 -1
- package/modules/settings/Settings.js +52 -20
- package/modules/settings/apply.js +23 -9
- package/modules/settings/sections.js +39 -6
- package/modules/settings/strings.js +2 -0
- package/modules/settings/view.js +19 -3
- package/modules/sky/dome.js +15 -3
- package/modules/sky/environment.js +28 -12
- package/modules/sky/fog.js +1 -1
- package/modules/sky/frame.js +6 -1
- package/modules/sky/shader.js +4 -3
- package/modules/sky/skyModule.js +8 -4
- package/modules/swarm/Swarm.js +1 -1
- package/modules/terrain/ChunkManager.js +61 -15
- package/modules/terrain/chunkJob.js +2 -2
- package/modules/terrain/index.js +20 -5
- package/modules/terrain/terrainEdit.js +8 -4
- package/modules/terrain/terrainTexture.js +4 -2
- package/modules/timeline/Timeline.js +4 -3
- package/modules/timeline/Tween.js +3 -0
- package/modules/timeline/letterbox.js +1 -0
- package/modules/triggers/index.js +36 -17
- package/modules/vegetation/Vegetation.js +81 -19
- package/modules/vegetation/densityMap.js +13 -8
- package/modules/vegetation/draw.js +147 -24
- package/modules/vegetation/groundChunks.js +20 -5
- package/modules/vegetation/index.js +3 -3
- package/modules/vegetation/modelGeometry.js +9 -4
- package/modules/water/Water.js +11 -8
- package/modules/weather/Weather.js +7 -2
- package/modules/weather/shaders.js +25 -5
- package/modules/weather/weatherDraw.js +20 -6
- package/modules/world/World.js +2 -1
- package/modules/world/index.js +2 -2
- package/modules/world/persist.js +6 -2
- package/modules/world/views.js +15 -2
- package/package.json +4 -1
- package/presets.js +5 -5
- package/render/PostFX.js +84 -41
- package/render/backend.js +137 -16
- package/render/cascades.js +3 -1
- package/render/cascades.tsl.js +2 -0
- package/render/daylight.js +7 -1
- package/render/detail.js +7 -4
- package/render/effects.js +27 -8
- package/render/fogLook.js +24 -0
- package/render/fuse.js +5 -2
- package/render/fx/detail.tsl.js +9 -7
- package/render/fx/index.js +7 -2
- package/render/fx/library.tsl.js +1 -0
- package/render/fx/lightShaft.tsl.js +114 -0
- package/render/fx/noise.tsl.js +25 -8
- package/render/fx/objectOrigin.tsl.js +39 -10
- package/render/fx/particles.tsl.js +23 -6
- package/render/fx/patchNodes.tsl.js +17 -12
- package/render/fx/pcss.tsl.js +51 -0
- package/render/fx/postWebGPU.tsl.js +89 -29
- package/render/fx/sky.tsl.js +3 -9
- package/render/fxNumbers.js +10 -4
- package/render/impostor.tsl.js +107 -0
- package/render/lighting.js +33 -1
- package/render/lightmap.js +42 -28
- package/render/lights.js +19 -3
- package/render/materials.js +6 -4
- package/render/mergeCommon.js +4 -1
- package/render/occlusion.js +14 -4
- package/render/patches.js +79 -41
- package/render/postRuns.js +32 -0
- package/render/postWebGL.js +97 -10
- package/render/probes.js +10 -14
- package/render/shaderErrors.js +2 -1
- package/render/shadowCache.tsl.js +33 -5
- package/render/shadows.js +42 -16
- package/render/slots.js +8 -5
- package/render/vertexInputs.js +52 -0
- package/types/core.d.ts +114 -46
- package/types/gameplay.d.ts +56 -23
- package/types/generated/core/audio/Audio.d.ts +27 -1
- package/types/generated/core/base/Random.d.ts +1 -1
- package/types/generated/core/input/Input.d.ts +6 -8
- package/types/generated/core/input/inputSeat.d.ts +1 -1
- package/types/generated/core/inspect/Budget.d.ts +26 -0
- package/types/generated/core/inspect/DebugOverrides.d.ts +0 -2
- package/types/generated/core/saves/Saves.d.ts +10 -7
- package/types/generated/core/saves/session.d.ts +8 -2
- package/types/generated/core/scene/Rays.d.ts +1 -3
- package/types/generated/modules/particles/Particles.d.ts +1 -1
- package/types/generated/modules/world/World.d.ts +2 -1
- package/types/generated/render/PostFX.d.ts +35 -9
- package/types/physics.d.ts +43 -11
- package/types/pixel.d.ts +1 -1
- package/types/tsl.d.ts +62 -1
- package/types/world.d.ts +12 -3
- package/ui/Focus.js +7 -5
- package/ui/Parts.js +1 -1
- package/ui/touchPart.js +6 -3
package/modules/camera/common.js
CHANGED
|
@@ -18,8 +18,10 @@
|
|
|
18
18
|
import * as THREE from 'three';
|
|
19
19
|
import { defineOwned, dropOwned } from '../../core/ops/owned.js';
|
|
20
20
|
import { readParams, keysSchema } from '../../core/base/params.js';
|
|
21
|
+
import { pointSpotLights } from '../../core/scene/gameLights.js';
|
|
21
22
|
import { setFov, setProjection } from '../../core/scene/view.js';
|
|
22
|
-
import { codedError } from '../../core/base/errorHints.js';
|
|
23
|
+
import { codedError, coded } from '../../core/base/errorHints.js';
|
|
24
|
+
import { warnOnce } from '../../core/base/validate.js';
|
|
23
25
|
|
|
24
26
|
// the takeover calls the owned-camera warning quotes (core/ops/owned.js): takeCamera is the one explicit entry (its remove() gives the camera back);
|
|
25
27
|
// back is the hand-back for a camera the engine yielded to a direct write (that takeover has no handle)
|
|
@@ -38,6 +40,22 @@ function planar(dir, fallback = { x: 0, z: -1 }) {
|
|
|
38
40
|
const l = Math.hypot(dir.x, dir.z);
|
|
39
41
|
return l < 1e-4 ? { x: fallback.x, z: fallback.z } : { x: dir.x / l, z: dir.z / l };
|
|
40
42
|
}
|
|
43
|
+
/**
|
|
44
|
+
* A rig value kept to its range [rig[loName], rig[hiName]] (the documented limit). Asked for outside it, it is said once in dev, naming the option that
|
|
45
|
+
* widens it: a silent clamp made a game's wheel zoom do nothing past the default maxDistance. kept: return the value as given (a start value the first
|
|
46
|
+
* wheel notch or drag pulls in), else the limit
|
|
47
|
+
* @param {any} rig @param {string} kind the module function ('followCamera') @param {string} call where the value came from ('followCamera()', 'cameraRig.setView()')
|
|
48
|
+
* @param {string} name @param {number} v @param {string[]} names [loName, hiName] @param {boolean} [kept]
|
|
49
|
+
* @internal
|
|
50
|
+
*/
|
|
51
|
+
export function inRange(rig, kind, call, name, v, [loName, hiName], kept = false) {
|
|
52
|
+
const limit = v > rig[hiName] ? hiName : v < rig[loName] ? loName : null;
|
|
53
|
+
if (!limit) return v;
|
|
54
|
+
const at = rig[limit];
|
|
55
|
+
// a factory: the text is built only the one time it is said (a zoom past the limit asks every frame)
|
|
56
|
+
warnOnce(() => coded('camera-clamped', `${call}: ${name} ${v} is ${limit === hiName ? 'above' : 'below'} ${limit} (${at}), so the camera keeps to ${at}. To allow it: ${kind}({ ${limit}: ${v} }) or engine.cameraRig.${limit} = ${v}`), `camera-clamped:${call}:${limit}`);
|
|
57
|
+
return kept ? v : at;
|
|
58
|
+
}
|
|
41
59
|
/** Right direction from the forward direction (Y up) */
|
|
42
60
|
export const rightOf = f => ({ x: -f.z, z: f.x });
|
|
43
61
|
|
|
@@ -62,10 +80,54 @@ export const HIDE_RIG = {
|
|
|
62
80
|
if ((o.isMesh || o.isSkinnedMesh || o.isPoints || o.isLine) && !o.layers.isEnabled(this.hideLayer)) { this._hidden.push([o, o.layers.mask]); o.layers.set(this.hideLayer); }
|
|
63
81
|
});
|
|
64
82
|
},
|
|
65
|
-
_unhide() {
|
|
66
|
-
|
|
67
|
-
|
|
83
|
+
_unhide() { // follow calls it every frame
|
|
84
|
+
for (const [o, mask] of this._hidden) o.layers.mask = mask; this._hidden.length = 0;
|
|
85
|
+
// the body shows again: carried lights get hideLayer back (a body that is seen casts its shadow from every light, as in plain three.js)
|
|
86
|
+
if (this._lightTook?.size) { for (const l of this._lightTook) hideBit(l, this.hideLayer, true); this._lightTook.clear(); }
|
|
87
|
+
},
|
|
88
|
+
// Every light present now gets the hidden layer; point / spot lights added later get it from _carriedLights on the frame they show up
|
|
89
|
+
_shadowLayers() { this.engine.scene.traverse(o => { if (o.isLight && o.shadow?.camera) hideBit(o, this.hideLayer, true); }); },
|
|
90
|
+
/**
|
|
91
|
+
* A light the player carries (head lamp, torch, flashlight) is not shadowed by the player's own hidden body; the sun and other lights still are.
|
|
92
|
+
* Why: the hidden body still casts shadows on purpose (you see your shadow from the sun), but a lamp that sits in or right next to the body
|
|
93
|
+
* sees that body fill half its view, so every frame shows a hard black wedge the player cannot explain (the body they would explain it with is hidden).
|
|
94
|
+
* Rule, automatic, no new option: while the body is hidden, a casting point / spot light whose world position is inside the body's box,
|
|
95
|
+
* grown by one body width on every side, is "carried", and its shadow camera drops hideLayer. Both renderers then draw that light's shadow
|
|
96
|
+
* with the view camera's layers (three.js: a shadow camera with only layer 0 falls back to the camera's layers, WebGLShadowMap and ShadowNode alike),
|
|
97
|
+
* and the view camera does not see hideLayer, so the body is left out. A sun / directional light is never carried.
|
|
98
|
+
* The engine writes only the hideLayer bit, and only puts it back on a light it took it from; a game that clears the bit itself keeps it cleared.
|
|
99
|
+
* Cost: per frame one loop over the scene's point / spot lights (gameLights keeps the set) and, while hidden with a casting one, one box of the body.
|
|
100
|
+
*/
|
|
101
|
+
_carriedLights() {
|
|
102
|
+
const lights = pointSpotLights(this.engine), seen = this._lightSeen ??= new WeakSet(), took = this._lightTook ??= new Set(), bit = this.hideLayer;
|
|
103
|
+
// a carried light that left the scene gets its bit back now: it may come back later, or be added to another scene, as the game left it
|
|
104
|
+
for (const l of took) if (!lights.has(l)) { hideBit(l, bit, true); took.delete(l); }
|
|
105
|
+
if (!lights.size) return;
|
|
106
|
+
let box = null;
|
|
107
|
+
for (const l of lights) {
|
|
108
|
+
const c = l.shadow?.camera; if (!c) continue;
|
|
109
|
+
if (!seen.has(l)) { seen.add(l); hideBit(l, bit, true); } // a light added after onEnter also gets the body's shadow
|
|
110
|
+
let carried = false;
|
|
111
|
+
if (l.castShadow && this._hidden.length) {
|
|
112
|
+
if (!box) {
|
|
113
|
+
box = (this._carrierBox ??= new THREE.Box3()).setFromObject(this.target);
|
|
114
|
+
if (!box.isEmpty()) { const s = box.getSize(_sz); box.expandByScalar(Math.max(s.x, s.z)); }
|
|
115
|
+
}
|
|
116
|
+
carried = !box.isEmpty() && box.containsPoint(l.getWorldPosition(_lp));
|
|
117
|
+
}
|
|
118
|
+
if (carried && c.layers.isEnabled(bit)) { hideBit(l, bit, false); took.add(l); }
|
|
119
|
+
else if (!carried && took.delete(l)) hideBit(l, bit, true);
|
|
120
|
+
}
|
|
121
|
+
},
|
|
68
122
|
};
|
|
123
|
+
const _sz = new THREE.Vector3(), _lp = new THREE.Vector3();
|
|
124
|
+
/** Set or clear the hidden layer on a light's shadow camera; only a real change asks for a redraw (needsUpdate), so a light whose game redraws it
|
|
125
|
+
* rarely (autoUpdate off, a shadow budget) does not keep the old shadow (a wedge, or no body) until its next turn, and one that did not change costs nothing */
|
|
126
|
+
function hideBit(l, bit, on) {
|
|
127
|
+
const ly = l.shadow.camera.layers; if (ly.isEnabled(bit) === on) return;
|
|
128
|
+
if (on) ly.enable(bit); else ly.disable(bit);
|
|
129
|
+
l.shadow.needsUpdate = true;
|
|
130
|
+
}
|
|
69
131
|
|
|
70
132
|
/**
|
|
71
133
|
* Click-to-lock the mouse for a camera with a pointerLock flag (first person, over-the-shoulder follow); call from onEnter.
|
|
@@ -138,7 +200,7 @@ export function rigPlaced(engine) { RIG_OWNED.get(engine)?.mark(); }
|
|
|
138
200
|
const RIG_OWNED = new WeakMap(); // engine -> the camera's owned entry (one camera module per engine)
|
|
139
201
|
|
|
140
202
|
/** Camera kind table: kind name -> build(engine, opts, input). Each camera file registers once with defineRig; setCamera switches by name.
|
|
141
|
-
* input.
|
|
203
|
+
* input.define(name, o) declares an action owned by the camera module (once per name, removed with the module), so a rig built later by
|
|
142
204
|
* setCamera or a new session leaves no declaration behind */
|
|
143
205
|
const RIGS = new Map();
|
|
144
206
|
const RIG_PARAMS = new Map(); // kind -> params schema (the option keys of that camera)
|
|
@@ -157,7 +219,7 @@ export function rigModule(kind, opts) {
|
|
|
157
219
|
const cache = new Map(); // kind -> camera instance: params like distance and pitch survive switching away and back
|
|
158
220
|
const builtWith = new WeakMap(); // rig -> the options it was built with
|
|
159
221
|
let modInput = null; const declared = new Set();
|
|
160
|
-
const input = {
|
|
222
|
+
const input = { define: (n, o) => { if (!declared.has(n)) { declared.add(n); modInput.define(n, o); } } };
|
|
161
223
|
const make = (k, o) => {
|
|
162
224
|
const build = RIGS.get(k);
|
|
163
225
|
if (!build) throw codedError('camera-kind', `setCamera() has no camera kind '${k}'; available: ${[...RIGS.keys()].join(', ')}`);
|
|
@@ -197,7 +259,7 @@ export function rigModule(kind, opts) {
|
|
|
197
259
|
c.onEnter?.(false);
|
|
198
260
|
// The view the player had is save data. Written to a rig of the saved kind only: a follow rig's pitch means the opposite of a first-person one's, so across kinds
|
|
199
261
|
// only the heading carries (as in setCamera). A kind switched to at runtime is not restored: its options are the game's and are not save data
|
|
200
|
-
ctx.saves.
|
|
262
|
+
ctx.saves.define('cameraRig', { notAtomic: 'the view is output: no game rule reads it, and a rollback must not move the camera',
|
|
201
263
|
save: () => ({ kind: c.kind, yaw: c.yaw, pitch: c.pitch }),
|
|
202
264
|
load: d => {
|
|
203
265
|
const r = d.kind === c.kind ? c : home;
|
|
@@ -219,7 +281,7 @@ export function rigModule(kind, opts) {
|
|
|
219
281
|
for (const k of Object.keys(home)) delete home[k];
|
|
220
282
|
c = e.cameraRig = Object.assign(home, built, yaw !== undefined && { yaw, pitch });
|
|
221
283
|
cache.set(kind, home);
|
|
222
|
-
// follows the player only if the game asked (
|
|
284
|
+
// follows the player only if the game asked (addPlayer({ cameraFollow })), through the seat the load put it in: the rig was rebuilt after that seat was taken
|
|
223
285
|
const P = e.player, car = P?.cameraFollow ? P.vehicle : null;
|
|
224
286
|
c.onEnter?.(false); c.follow(car ? car.object : P?.cameraFollow ? P.root : null, car?.camera); fresh = true;
|
|
225
287
|
e.events.emit('camera:change', { kind, previous: old.kind }); // settings re-apply the player's sensitivity / fov to the rebuilt rig
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// What any camera module must provide (fields: see gameplay/inventory.contract.js; shared check: @threedog/tools/contract). It installs as engine.cameraRig.
|
|
2
2
|
// Exactly what other code reads from engine.cameraRig: forward() / right() (control: 'camera', faceMode 'camera', targeting), follow(object, opts?)
|
|
3
|
-
// (
|
|
3
|
+
// (addPlayer, entering / leaving a vehicle), focusPoint() (photo, where the world loads), screenToGround(ndcX, ndcY) (click-to-move, placing
|
|
4
4
|
// things); sensitivity / invertY are optional fields the settings menu writes when present. A camera that places engine.camera itself during a
|
|
5
5
|
// cutscene takeover leaves it alone while engine.cameraOverride is set (common.js).
|
|
6
6
|
export default {
|
|
@@ -24,6 +24,7 @@ import { seatsOf } from './seat.js';
|
|
|
24
24
|
import { useModel } from './useModel.js';
|
|
25
25
|
import { codedError, coded } from '../../core/base/errorHints.js';
|
|
26
26
|
import { isModelName } from '../../core/base/util.js';
|
|
27
|
+
import { passesOf } from '../collision/grid.js';
|
|
27
28
|
|
|
28
29
|
// A record whose jump / safe is the wrong kind of thing (a damaged or hand-edited save) is repaired so the game keeps running, but said out loud once: bad data is reported, not quietly fixed
|
|
29
30
|
function badField(v, name, want) { if (v != null) warnOnce(`[threedog] character motion: the world record's '${name}' is ${JSON.stringify(v)} but should be ${want}; it was replaced with a fresh one. Check the save or the code that writes the record`); return undefined; }
|
|
@@ -32,7 +33,7 @@ const BUILT_IN = { simple: simpleMover, rapier: rapierMover, manual: manualMover
|
|
|
32
33
|
|
|
33
34
|
// Options Character understands (shared by player and NPC)
|
|
34
35
|
export const CHARACTER_KEYS = ['colors', 'speed', 'runSpeed', 'radius', 'water', 'states', 'swimDepth', 'swimSpeed', 'turnSpeed', 'acceleration', 'gravity',
|
|
35
|
-
'jumpSpeed', 'stepHeight', 'airControl', 'coyoteTime', 'canJump', 'maxJumps', 'airJumpSpeed', 'jumpBuffer', 'fall', 'channel', 'model', 'clips', 'animation', 'mover', 'faceMode', 'faceTarget', 'rig', 'id'];
|
|
36
|
+
'jumpSpeed', 'stepHeight', 'airControl', 'coyoteTime', 'canJump', 'maxJumps', 'airJumpSpeed', 'jumpBuffer', 'fall', 'channel', 'model', 'clips', 'animation', 'mover', 'faceMode', 'faceTarget', 'rig', 'id', 'passes'];
|
|
36
37
|
const FACE_MODES = ['move', 'camera', 'target', 'manual'];
|
|
37
38
|
|
|
38
39
|
export class Character {
|
|
@@ -42,6 +43,7 @@ export class Character {
|
|
|
42
43
|
* engine.assets.model() returned; without model and rig a gray capsule (warned once). rig: a ready body (proceduralRig.js format)
|
|
43
44
|
* colors: { body, skin, legs, hair } per-character part colors (meshes marked userData.part; a capsule takes colors.body)
|
|
44
45
|
* speed walk speed, runSpeed run speed (m/s), radius collision radius
|
|
46
|
+
* passes the collider layers it walks through, e.g. ['gate'] (collision.addBox { layer }): its walking, paths and navmesh all follow it; plain, may be rewritten later
|
|
45
47
|
* water what water deeper than swimDepth does: 'swim' (default, floats, state 'swim') | 'block' (never enters it) | 'wade' (walks the
|
|
46
48
|
* bottom) | (character, { depth, x, z }) => one of those (per spot: a swim skill, a boat, depth); character:water fires on each change.
|
|
47
49
|
* swimDepth water depth at which it counts as deep, swimSpeed swim speed multiplier
|
|
@@ -70,7 +72,7 @@ export class Character {
|
|
|
70
72
|
constructor(engine, { colors = {}, speed = 4.5, runSpeed = 7, radius = engine.movement.radius, water = 'swim', states = null, swimDepth = 1.0, swimSpeed = 0.45,
|
|
71
73
|
turnSpeed = 10, acceleration = 12, gravity = -24, jumpSpeed = 8, stepHeight = engine.movement.stepHeight, airControl = 0.35, coyoteTime = 0.12,
|
|
72
74
|
canJump = true, maxJumps = 1, airJumpSpeed = null, jumpBuffer = 0.12, fall = false, channel = 'world',
|
|
73
|
-
model = null, clips = null, animation = null, mover = 'simple', faceMode = 'move', faceTarget = null, rig = null, id = null } = {}) {
|
|
75
|
+
model = null, clips = null, animation = null, mover = 'simple', faceMode = 'move', faceTarget = null, rig = null, id = null, passes } = {}) {
|
|
74
76
|
/** @internal the id option, else the generated one (a character without a world record); the getter id below is the one public form */ this._ownId = id;
|
|
75
77
|
/** @internal true for a world NPC's model (npcView.js): disposing it keeps the NPC's control slot */ this.npcModel = false;
|
|
76
78
|
this.engine = engine;
|
|
@@ -78,6 +80,7 @@ export class Character {
|
|
|
78
80
|
if (states != null && typeof states !== 'function') throw codedError('character-option', 'character option states: (character, facts) => state name | null', TypeError);
|
|
79
81
|
/** What deep water does ('swim' | 'block' | 'wade' | function); states: the game's state hook. Both plain, change them at any time */
|
|
80
82
|
this.water = water; this.states = states;
|
|
83
|
+
/** Collider layers this body goes through (character option passes); undefined: stopped by every collider */ this.passes = passesOf('character option passes', passes);
|
|
81
84
|
Object.assign(this, { speed, runSpeed, radius, swimDepth, swimSpeedFactor: swimSpeed, turnSpeed, acceleration, gravity, jumpSpeed, stepHeight,
|
|
82
85
|
airControl, coyoteTime, canJump, maxJumps, airJumpSpeed, jumpBuffer, channel });
|
|
83
86
|
if (fall && !(typeof fall.belowY === 'number' || typeof fall.belowY === 'function')) throw codedError('character-option', `character option fall: { belowY: -20 } (a height, or (character) => boolean), or false; got ${JSON.stringify(fall)}`, TypeError);
|
|
@@ -93,7 +96,7 @@ export class Character {
|
|
|
93
96
|
this.vy = 0; this.grounded = true; this._push = 0;
|
|
94
97
|
this.limp = null; this.disposed = false; // limp: the ragdoll that has the body (rigid/ragdoll.js)
|
|
95
98
|
this.root = new THREE.Group();
|
|
96
|
-
engine._poses.add(this.root);
|
|
99
|
+
this._pose = engine._poses.add(this.root, null, null, () => `character '${this.id}'`);
|
|
97
100
|
this.velocity = new THREE.Vector2();
|
|
98
101
|
this.facing = 0; this.phase = 0; this.moveAmount = 0;
|
|
99
102
|
this.swimming = false;
|
|
@@ -103,6 +106,7 @@ export class Character {
|
|
|
103
106
|
this.state = this.stateMark = 'idle';
|
|
104
107
|
/** The vehicle it sits in (null on foot) and its seat there (0 = driver, null on foot) */
|
|
105
108
|
/** @internal the seat relation (seat.js), null on foot */ this._ride = null; this.anim = null;
|
|
109
|
+
/** @internal set by addPlayer: tears the player's registry entry down and then this character (player.js), so dispose() reaches it from either side */ this._release = null;
|
|
106
110
|
/** false while a model named by asset loads (placeholder shows); await whenReady */
|
|
107
111
|
this.ready = true;
|
|
108
112
|
/**
|
|
@@ -119,10 +123,10 @@ export class Character {
|
|
|
119
123
|
this._colors = colors;
|
|
120
124
|
// one path for every body: an object, a procedural builder built now (joints exist at once), or a file asset loaded behind a capsule
|
|
121
125
|
const now = isModelName(model) ? buildNow(engine, model) : model;
|
|
122
|
-
if (now) { this._useModel(now, clips, animation); return; }
|
|
126
|
+
if (now && !now.then) { this._useModel(now, clips, animation); return; } // a promise: an async builder, waited on below
|
|
123
127
|
if (!rig && !model) warnOnce(NO_CHARACTER);
|
|
124
128
|
useRig(this, rig || capsule(colors.body, engine));
|
|
125
|
-
if (model) this._whenReady = loadAssetModel(this, model, m => this._useModel(m, clips, animation));
|
|
129
|
+
if (model) this._whenReady = loadAssetModel(this, model, m => this._useModel(m, clips, animation), now);
|
|
126
130
|
}
|
|
127
131
|
/** A model object with userData.rig is a procedural body (limb swing); anything else animates by its clips */
|
|
128
132
|
_useModel(model, clips, animation) {
|
|
@@ -156,7 +160,7 @@ export class Character {
|
|
|
156
160
|
/**
|
|
157
161
|
* Request a jump (call when the jump key is pressed). It waits jumpBuffer seconds for the ground, so pressing slightly before landing counts;
|
|
158
162
|
* on the ground or in coyote time it is the ground jump, otherwise an air jump while maxJumps allows. air: false = only a ground jump.
|
|
159
|
-
* @example
|
|
163
|
+
* @example addPlayer({ ..., maxJumps: 2 }); // double jump: the same jump key twice
|
|
160
164
|
*/
|
|
161
165
|
jump({ air = true } = {}) { const j = jumpOf(this); j.buffer = this.jumpBuffer || 1e-6; j.fresh = true; j.air = air; return this; }
|
|
162
166
|
/** Give back n jumps for this airtime (a pickup, a wall touch) @param {number} [n] */
|
|
@@ -332,7 +336,7 @@ export class Character {
|
|
|
332
336
|
if (e.player === this) this._driveCtx = e.input.push('vehicle', { pass: true }); // driving: brake lives in this context, walking-only keys are shadowed
|
|
333
337
|
if (e.player === this && !e.input.keysOf('brake').length) warnOnce(coded('input-keys', "the player drives without a brake key: no module binds one by itself. engine.input.bind(presets.bindings.brake) (B / gamepad LT) or engine.input.bind('brake', ['KeyX'])"));
|
|
334
338
|
this.root.visible = vehicle.hideDriver === false; this.velocity.set(0, 0); this.vy = 0; this.swimming = false; this.state = this.stateMark = 'drive'; this._store();
|
|
335
|
-
// only when the game asked the camera to follow the player (
|
|
339
|
+
// only when the game asked the camera to follow the player (addPlayer({ cameraFollow }))
|
|
336
340
|
if (e.player === this && this.cameraFollow) e.cameraRig?.follow(vehicle.object, vehicle.camera);
|
|
337
341
|
e.events.emit('vehicle:enter', { character: this, vehicle });
|
|
338
342
|
}
|
|
@@ -343,7 +347,7 @@ export class Character {
|
|
|
343
347
|
for (let n = 0; n < 8; n++) { // bounded: a vehicle with one exit answers the same point for every n
|
|
344
348
|
const p = v.exitPosition(seat, n);
|
|
345
349
|
if (!p) return null;
|
|
346
|
-
if (this.engine.collision?.walkableAt(p.x, p.z, this.radius, p.y) ?? true) return p;
|
|
350
|
+
if (this.engine.collision?.walkableAt(p.x, p.z, this.radius, p.y, this.passes) ?? true) return p;
|
|
347
351
|
}
|
|
348
352
|
return null;
|
|
349
353
|
}
|
|
@@ -370,6 +374,8 @@ export class Character {
|
|
|
370
374
|
}
|
|
371
375
|
/** Dispose this character completely: exit the vehicle first, release animation and mover, remove from the scene and dispose geometries and materials */
|
|
372
376
|
dispose() {
|
|
377
|
+
// a player made by addPlayer: its registry entry (st.players, keys, touch button, world:load listener) goes first, and calls this again with _release cleared
|
|
378
|
+
if (this._release) { const r = this._release; this._release = null; r(); return; }
|
|
373
379
|
this.disposed = true; // a model still loading by asset name is dropped on arrival
|
|
374
380
|
this.engine.control?.endTasks(this, 'gone');
|
|
375
381
|
// a character without a world record or NPC id has nothing to come back as: its control slot goes with it (records drop theirs on world:remove,
|
|
@@ -377,7 +383,7 @@ export class Character {
|
|
|
377
383
|
if (!this.recordId && !this.npcModel) this.engine.control?.forget(this.id);
|
|
378
384
|
this.exit({ force: true });
|
|
379
385
|
detach(this); // a disposed rider must leave the platform's rider list, or it is carried and kept alive for as long as the platform lives
|
|
380
|
-
this.
|
|
386
|
+
this._pose.remove();
|
|
381
387
|
this.anim?.dispose();
|
|
382
388
|
for (const m of new Set(this._movers.values())) m.dispose?.();
|
|
383
389
|
this.engine.characters?._capsules.delete(this._rig?.capsule);
|
|
@@ -449,7 +455,7 @@ export class Character {
|
|
|
449
455
|
animate(dt) {
|
|
450
456
|
dt *= this.engine.still ? 0 : this.engine.time.scale(this.channel, this.id);
|
|
451
457
|
if (!this.limp) this._animate(dt);
|
|
452
|
-
if (!this.anim) this._firePose(dt);
|
|
458
|
+
if (!this.anim?._hook) this._firePose(dt); // an Animator with a frame hook fires it itself, once the pose is applied; a model without clips (and no IK) has no hook
|
|
453
459
|
}
|
|
454
460
|
/** @internal */
|
|
455
461
|
_animate(dt) {
|
|
@@ -46,6 +46,7 @@ import { leaveLink } from './moveHelpers.js';
|
|
|
46
46
|
import { Behaviors } from './behaviors.js';
|
|
47
47
|
import { codedError } from '../../core/base/errorHints.js';
|
|
48
48
|
import { isModelName } from '../../core/base/util.js';
|
|
49
|
+
import { passesOf } from '../collision/grid.js';
|
|
49
50
|
|
|
50
51
|
const STRINGS = {
|
|
51
52
|
noInteract: 'NPC "{name}" has interact set, but the interactions() module is not installed: nothing can use it',
|
|
@@ -268,8 +269,9 @@ export class NPCManager {
|
|
|
268
269
|
position, zone = null, speed = 2.6, initial = false, behavior = 'schedule', mind = {}, ...rest } = opts;
|
|
269
270
|
if (io !== null && !(io && typeof io === 'object' && typeof io.op === 'string')) throw codedError('character-option', fmt(STRINGS.badInteract, { got: JSON.stringify(io) }), TypeError);
|
|
270
271
|
if (io) readParams('npcs.add() interact', keysSchema(['label', 'op', 'args', 'radius']), io);
|
|
272
|
+
passesOf('npcs.add() passes', rest.passes); // here, not when its body is first built near the player
|
|
271
273
|
const id = given ?? name, look = {}, runtime = { ...this._runtime.get(id) }; // a re-add keeps what it does not pass, as the record does
|
|
272
|
-
if (given == null
|
|
274
|
+
if (given == null && this._byName.has(id)) throw codedError('world-id', fmt(STRINGS.sameName, { name }));
|
|
273
275
|
// an asset name is data (saved); a model object, animation, clips and whatever is not plain stay in memory
|
|
274
276
|
for (const [k, v] of Object.entries(rest)) {
|
|
275
277
|
if ((RUNTIME_KEYS.includes(k) && !(k === 'model' && isModelName(v))) || !W.isPlain(v)) runtime[k] = v;
|
|
@@ -277,7 +279,8 @@ export class NPCManager {
|
|
|
277
279
|
}
|
|
278
280
|
if (io) { if (typeof io.label === 'function') runtime.interactLabel = io.label; else delete runtime.interactLabel; }
|
|
279
281
|
this._b.check(behavior);
|
|
280
|
-
|
|
282
|
+
const old = W.get(id);
|
|
283
|
+
if (old && old.kind !== KIND) throw codedError('world-id', fmt(STRINGS.notNpc, { id, kind: old.kind }));
|
|
281
284
|
const hpd = e.calendar?.hoursPerDay ?? 24;
|
|
282
285
|
// at may be 'HH:MM' or 0-1
|
|
283
286
|
const sched = schedule.map(s => { const [x, z] = xzOf(s.position), y = yOf(s.position); return { at: parseClock(s.at, hpd), x, ...(y !== undefined && { y }), z }; }).sort((a, b) => a.at - b.at);
|
|
@@ -285,23 +288,32 @@ export class NPCManager {
|
|
|
285
288
|
// the record keeps plain values only: a function label stays in runtime (above), the record gets null and the view reads runtime first
|
|
286
289
|
const interact = io && { label: typeof io.label === 'string' ? io.label : null, op: io.op, args: io.args ?? {}, radius: io.radius ?? 3.2 };
|
|
287
290
|
const def = { name, behavior, mind, schedule: sched, interact, pathStep, repath, arriveDistance, speed, look, zone };
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
291
|
+
// the name and the runtime entry (the presenters read it as the record arrives) are taken only now, and given back if the world write throws (checkPlain on a mind with a function, a
|
|
292
|
+
// dev id clash): a failed add leaves nothing behind, so a retry is not 'sameName' and a non-NPC id has no entry
|
|
293
|
+
const prev = this._runtime.get(id);
|
|
294
|
+
if (given == null) this._byName.add(id);
|
|
295
|
+
this._runtime.set(id, runtime);
|
|
296
|
+
try {
|
|
297
|
+
if (old) {
|
|
298
|
+
// re-add overrides only fields passed explicitly (unpassed zone, schedule etc. keep their values)
|
|
299
|
+
const patch = {};
|
|
300
|
+
const keys = ['name', 'interact', 'pathStep', 'repath', 'arriveDistance', 'speed', 'zone', 'schedule'];
|
|
301
|
+
for (const k of keys) if (opts[k] !== undefined) patch[k] = k === 'schedule' ? sched : def[k];
|
|
302
|
+
// a new behavior starts a new memory, as setBehavior does; naming the one it has is setup code running again, and the memory is state
|
|
303
|
+
const changes = opts.behavior !== undefined && behavior !== old.behavior;
|
|
304
|
+
if (changes) { patch.behavior = behavior; patch.nav = { ...old.nav, path: null, repath: 0 }; }
|
|
305
|
+
if (changes || opts.mind !== undefined) patch.mind = mind;
|
|
306
|
+
if (Object.keys(look).length) patch.look = { ...old.look, ...look };
|
|
307
|
+
W.set(id, patch);
|
|
308
|
+
} else {
|
|
309
|
+
const i = stopIndex(sched, timeOfDay(e)), at = position ?? (i != null ? sched[i] : { x: 0, z: 0 }), [x, z] = xzOf(at);
|
|
310
|
+
const nav = { stop: null, path: null, repath: 0 };
|
|
311
|
+
W.add({ id, kind: KIND, position: [x, placeAtHeight(e, `npcs.${id}`, x, z, yOf(at), 0, 0).y, z], ...def, state: 'idle', busy: false, nav, motion: null }, { initial });
|
|
312
|
+
}
|
|
313
|
+
} catch (err) {
|
|
314
|
+
if (prev) this._runtime.set(id, prev); else this._runtime.delete(id);
|
|
315
|
+
if (given == null) this._byName.delete(id);
|
|
316
|
+
throw err;
|
|
305
317
|
}
|
|
306
318
|
return this._handle(id);
|
|
307
319
|
}
|
|
@@ -13,17 +13,21 @@ import { builderArgs } from '../../core/assets/namedModel.js';
|
|
|
13
13
|
import { list as nameAndArgs } from '../../core/base/util.js';
|
|
14
14
|
|
|
15
15
|
/**
|
|
16
|
-
* Build a procedural model asset now (synchronously) when `name` is a registered builder; null when it is a file model
|
|
17
|
-
*
|
|
16
|
+
* Build a procedural model asset now (synchronously) when `name` is a registered builder; null when it is a file model or unknown. A builder that answers with a
|
|
17
|
+
* promise (async) is not run again by loadAssetModel: its promise is handed back (of the made model), and loadAssetModel waits on that one job.
|
|
18
|
+
* The builder gets this = { palette: engine.assets.palette, engine } like any generator in the manifest.
|
|
18
19
|
*/
|
|
19
20
|
export function buildNow(engine, model) {
|
|
20
21
|
const [name] = nameAndArgs(model), build = engine.assets.builder(name);
|
|
21
22
|
if (!build) return null;
|
|
22
23
|
const v = build.call({ palette: engine.assets.palette, engine }, ...builderArgs(engine, model));
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
24
|
+
const made = r => {
|
|
25
|
+
if (r.isBufferGeometry) return engine.assets.handOut(new THREE.Mesh(r, neutralMaterial('character', { vertexColors: !!r.attributes.color })), name);
|
|
26
|
+
if (!r.name) r.name = name;
|
|
27
|
+
return engine.assets.handOut(r, name);
|
|
28
|
+
};
|
|
29
|
+
if (typeof v?.then === 'function') return v.then(made);
|
|
30
|
+
return v ? made(v) : null;
|
|
27
31
|
}
|
|
28
32
|
|
|
29
33
|
const STRINGS = {
|
|
@@ -37,8 +41,9 @@ const STRINGS = {
|
|
|
37
41
|
* @param {import('./Character.js').Character} ch
|
|
38
42
|
* @param {string | any[]} model a name, or [name, ...args]
|
|
39
43
|
* @param {(model: any) => void} use builds the model and Animator on ch
|
|
44
|
+
* @param {Promise<any>} [job] the promise buildNow got from an async builder: the one run of it, so the generator is not called a second time
|
|
40
45
|
*/
|
|
41
|
-
export function loadAssetModel(ch, model, use) {
|
|
46
|
+
export function loadAssetModel(ch, model, use, job) {
|
|
42
47
|
const e = ch.engine, A = e.assets, [name, ...args] = nameAndArgs(model);
|
|
43
48
|
const names = [...A.entries].filter(([, x]) => x.type === 'model' && x.named).map(([n]) => n);
|
|
44
49
|
const list = names.join(', ') || 'none; register them with engine.assets.manifest({ models })';
|
|
@@ -59,8 +64,8 @@ export function loadAssetModel(ch, model, use) {
|
|
|
59
64
|
e.events.emit('character:model', { character: ch, model: m });
|
|
60
65
|
};
|
|
61
66
|
// already loaded (another NPC uses it, or this one was built before): swap now, so a character rebuilt far -> near never shows the placeholder
|
|
62
|
-
const now = A.entries.get(name)?.value ? A.modelNow(name) : null; // only when loaded: modelNow hints in dev when nothing loads it
|
|
67
|
+
const now = !job && A.entries.get(name)?.value ? A.modelNow(name) : null; // only when loaded: modelNow hints in dev when nothing loads it
|
|
63
68
|
if (now) { swap(now); return Promise.resolve(); }
|
|
64
69
|
ch.ready = false;
|
|
65
|
-
return A.model(name).then(swap).catch(err => { if (!ch.disposed) fail(err.message); }).finally(() => { ch.ready = true; });
|
|
70
|
+
return (job ?? A.model(name)).then(swap).catch(err => { if (!ch.disposed) fail(err.message); }).finally(() => { ch.ready = true; });
|
|
66
71
|
}
|
|
@@ -61,7 +61,12 @@ export function findPath(walkable, sx, sz, gx, gz, { radius, step = defaultStep(
|
|
|
61
61
|
const ni = s.i + di, nj = s.j + dj, t = reach(ni, nj, s.y);
|
|
62
62
|
if (!t.ok && !(ni === gi && nj === gj)) continue;
|
|
63
63
|
const ng = s.g + c;
|
|
64
|
-
|
|
64
|
+
// the cells being free says nothing about the way between them: a thin wall or fence lies between two free cell centres. Checked only for a step that would improve the cell, sampled
|
|
65
|
+
// every third of a cell (smoothing below samples finer). The first and last leg run from the real start / to the real goal, as the path does: a cell centre may lie behind a wall
|
|
66
|
+
if (ng < t.g) {
|
|
67
|
+
const from = s === first ? { x: sx, y, z: sz } : { x: s.i * step, y: s.y, z: s.j * step }, to = ni === gi && nj === gj ? { x: gx, y: t.y, z: gz } : { x: ni * step, y: t.y, z: nj * step };
|
|
68
|
+
if (lineClear(walkable, floor, level, from, to, step / 3)) { t.g = ng; t.from = s; open.push(t, ng + h(ni, nj), ng); }
|
|
69
|
+
}
|
|
65
70
|
}
|
|
66
71
|
}
|
|
67
72
|
return null;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// What any characters module must provide (fields: see gameplay/inventory.contract.js; shared check: @threedog/tools/contract).
|
|
2
2
|
// The player is the world record 'player' (saved with world, not under a key of its own); jumps, landings, launches and falls are events other
|
|
3
3
|
// modules listen to, fired by the character itself (not exercised by the shared check: they need a player on ground). kit is what a game's mover calls (mover.contract.js).
|
|
4
|
-
// What
|
|
4
|
+
// What addPlayer and control.characterOf hand out is character.contract.js: every member other modules use, the world protocol among them.
|
|
5
5
|
// position: who may write a character's position (design.md section 9). The record follows the character, so a write to the record of a live character is a placeAt (world.move).
|
|
6
6
|
export default {
|
|
7
7
|
name: 'characters',
|
|
8
|
-
api: ['
|
|
8
|
+
api: ['addPlayer', 'removePlayer', 'findSpawn', 'findPath', 'findPathAsync', 'support', 'moveInput', 'carryRiders', 'addVehicle'],
|
|
9
9
|
fields: ['kit'],
|
|
10
10
|
resolves: true, // calls engine.control.resolveWith; what it answers with is character.contract.js
|
|
11
11
|
position: {
|
|
@@ -10,11 +10,11 @@
|
|
|
10
10
|
// Vehicles are used through an interface (the { object, speed, drive(), seatPosition(), exitPosition() } returned by rigid.addWheeled); rigid is not imported
|
|
11
11
|
// here.
|
|
12
12
|
import { Character } from './Character.js';
|
|
13
|
-
import {
|
|
13
|
+
import { addPlayer } from './player.js';
|
|
14
14
|
import { NPCManager, NPC } from './NPC.js';
|
|
15
15
|
import { findPath } from './astar.js';
|
|
16
16
|
import { findSpawn, moveInput, withHeights } from './moveHelpers.js';
|
|
17
|
-
import { AsyncPaths, sourcePath } from './pathAsync.js';
|
|
17
|
+
import { AsyncPaths, sourcePath, noteAStarStandIn } from './pathAsync.js';
|
|
18
18
|
import { needMaterial } from '../../core/base/validate.js';
|
|
19
19
|
import { builtInSounds } from '../../core/assets/assetManifest.js';
|
|
20
20
|
import { readParams, keysSchema } from '../../core/base/params.js';
|
|
@@ -27,12 +27,14 @@ import { footstepSynth, stepSound } from './footsteps.js';
|
|
|
27
27
|
import { xzOf, yOf } from '../../core/base/math.js';
|
|
28
28
|
import { surfaceOr } from '../../core/scene/ground.js';
|
|
29
29
|
import { isEngineMade } from '../../render/patches.js';
|
|
30
|
+
import { keepPart } from '../../core/base/freeParts.js';
|
|
30
31
|
import { capsuleDefault, capsuleMaterial } from './proceduralRig.js';
|
|
32
|
+
import { passesOf } from '../collision/grid.js';
|
|
31
33
|
export { Character, NPC };
|
|
32
34
|
|
|
33
35
|
/**
|
|
34
36
|
* Characters module. Once installed:
|
|
35
|
-
* engine.characters.
|
|
37
|
+
* engine.characters.addPlayer({ spawn: {x, z}, colors, model, clips }) → player
|
|
36
38
|
* engine.npcs.add({ id, name, schedule, interact, ... }) → NPC handle (needs npcs: true, on by default; data lives in engine.world)
|
|
37
39
|
* engine.npcs.remove(npc or name); engine.characters.removePlayer()
|
|
38
40
|
* three.js object of player and NPC: .root (Group), position .position (Vector3); spawn / position accept a Vector3 directly
|
|
@@ -42,14 +44,16 @@ export { Character, NPC };
|
|
|
42
44
|
/** The characters.path rule, else navmesh when ready, else A* (characters.findPath; the one synchronous A* entry, see R20) */
|
|
43
45
|
function solvePath(e, st, from, to, o) {
|
|
44
46
|
const { detailed, id, ...rest } = o;
|
|
47
|
+
rest.passes = passesOf('characters.findPath()', o.passes);
|
|
45
48
|
let res = sourcePath(e, st.path, from, to, o);
|
|
46
49
|
if (res) { /* the game's source answered */ }
|
|
47
50
|
else if (e.nav?.ready) res = e.nav.findPath(from, to, { ...rest, detailed: true });
|
|
48
51
|
else if (!e.collision) res = { status: 'notReady', path: null };
|
|
49
52
|
else {
|
|
53
|
+
noteAStarStandIn(e);
|
|
50
54
|
const [sx, sz] = xzOf(from), [gx, gz] = xzOf(to), radius = rest.radius ?? e.movement.radius;
|
|
51
55
|
const floor = (x, z, y) => surfaceOr(e, x, z, y, y);
|
|
52
|
-
const path = findPath((x, z, y) => e.collision.walkableAt(x, z, radius, y), sx, sz, gx, gz, { ...rest, radius, y: floor(sx, sz, yOf(from)), goalY: yOf(to), floor, body: e.movement.height });
|
|
56
|
+
const path = findPath((x, z, y) => e.collision.walkableAt(x, z, radius, y, rest.passes), sx, sz, gx, gz, { ...rest, radius, y: floor(sx, sz, yOf(from)), goalY: yOf(to), floor, body: e.movement.height });
|
|
53
57
|
// nav installed but not ready: A* is only a stand-in, tell the caller honestly
|
|
54
58
|
res = { status: e.nav ? 'notReady' : path ? 'ok' : 'noPath', path };
|
|
55
59
|
}
|
|
@@ -66,7 +70,9 @@ const CHARACTERS_PARAMS = keysSchema(['npcs', 'npcTiers', 'animation', 'fall']);
|
|
|
66
70
|
* @param {any} animation characters({ animation })
|
|
67
71
|
*/
|
|
68
72
|
function charactersApi(e, st, animation) {
|
|
69
|
-
|
|
73
|
+
// keepPart: every capsule draws with this material, so removing one character must not dispose it. The hold goes when the material is replaced or the
|
|
74
|
+
// module unloads (dispose below), and a default one is then freed here, as no asset load owns it; a game's is ordinary again for engine.remove
|
|
75
|
+
const hold = m => { st.keep?.remove(); st.keep = keepPart(m); return (st.material = m); };
|
|
70
76
|
const api = {
|
|
71
77
|
/** @internal characters({ animation }): what every model's Animator starts from (useModel.js) */
|
|
72
78
|
_animation: animation,
|
|
@@ -78,12 +84,12 @@ function charactersApi(e, st, animation) {
|
|
|
78
84
|
* @example engine.characters.material = new THREE.MeshToonMaterial({ color: 0xd9a066 });
|
|
79
85
|
* @type {THREE.Material}
|
|
80
86
|
*/
|
|
81
|
-
get material() { return
|
|
87
|
+
get material() { return st.material ?? hold(capsuleDefault()); },
|
|
82
88
|
set material(m) {
|
|
83
89
|
needMaterial('character-option', 'engine.characters.material', m, '. Example: engine.characters.material = new THREE.MeshStandardMaterial({ color: 0xd9a066 })');
|
|
84
90
|
const old = api.material;
|
|
85
91
|
if (m === old) return;
|
|
86
|
-
|
|
92
|
+
hold(m);
|
|
87
93
|
for (const [mesh, color] of api._capsules) {
|
|
88
94
|
if (mesh.material !== old) mesh.material.dispose(); // the copy in a character's own color
|
|
89
95
|
mesh.material = capsuleMaterial(m, color);
|
|
@@ -109,12 +115,15 @@ function charactersApi(e, st, animation) {
|
|
|
109
115
|
/**
|
|
110
116
|
* Pathfinding (the only entry): navmesh if nav is ready, else A* (needs the collision module). Returns [{ x, y, z }…], null if unreachable: every point has its height, and a y on from / to picks the floor.
|
|
111
117
|
* Pass { detailed: true } to get { status, path }: 'ok' found | 'noPath' unreachable | 'notReady' nav installed but mesh not generated yet (path is the
|
|
112
|
-
* A* fallback, may be inaccurate; null without collision)
|
|
118
|
+
* A* fallback, may be inaccurate; null without collision). { passes: ['gate'] }: the path goes through colliders of those layers (collision.addBox { layer }), as the body does
|
|
119
|
+
* (walkTo and NPCs pass their character's passes themselves)
|
|
113
120
|
* Where paths come from is the rule 'characters.path' (findPathAsync, walkTo and NPCs follow it too; o.id picks an entry for one character): default 'walk' is the above, false is no path,
|
|
114
121
|
* a function ({ from, to, o }, engine) => [{ x, y?, z }…] | null | 'walk' is your own source, for flight, swimming or anything off the ground. It must be deterministic; it is not saved
|
|
115
122
|
* @example engine.mod('characters.path', { owner: 'birds', id: 'hawk', set: ({ from, to }) => [from, { x: to.x, y: 40, z: to.z }, to] });
|
|
116
123
|
*/
|
|
117
124
|
findPath(from, to, o = {}) { return solvePath(e, st, from, to, o); },
|
|
125
|
+
/** @internal may a nav crowd agent walk for this NPC: not with passes (the crowd's one mesh stops at every collider) or a 'characters.path' entry of its own (a game's source or false) */
|
|
126
|
+
_crowdFits(id, passes) { return !passes?.length && st.path.value(id) === 'walk'; },
|
|
118
127
|
/**
|
|
119
128
|
* findPath for many callers (NPC crowds, AI squads): solved in engine.threads workers, done(path, status) runs on a fixed step ~4 steps later
|
|
120
129
|
* via engine.commits, so threads on / off give the same paths. Keep findPath for the few that need a path now (click-to-move). Details: recipe 12
|
|
@@ -122,13 +131,12 @@ function charactersApi(e, st, animation) {
|
|
|
122
131
|
* @param {any} from
|
|
123
132
|
* @param {any} to
|
|
124
133
|
* @param {(path: { x: number, y: number, z: number }[] | null, status: 'ok' | 'noPath' | 'notReady') => void} done
|
|
125
|
-
* @param {{ radius?: number, step?: number, maxNodes?: number }} [opts]
|
|
134
|
+
* @param {{ radius?: number, passes?: string[], step?: number, maxNodes?: number }} [opts]
|
|
126
135
|
* @returns {{ remove: () => void }}
|
|
127
136
|
* @example const req = engine.characters.findPathAsync(guard.position, target, (path, status) => { guard.path = path; });
|
|
128
137
|
* req.remove(); // target changed before the answer came
|
|
129
138
|
*/
|
|
130
139
|
findPathAsync(from, to, done, opts) { return st.paths.request(from, to, done, opts); },
|
|
131
|
-
/** How many findPathAsync requests leave per fixed step (default 32); the rest wait for the next steps */
|
|
132
140
|
/**
|
|
133
141
|
* Bends a link crossing away from its straight line: (t, position, crossing, character) with t 0-1, called each step after position is set on the line, write to position.
|
|
134
142
|
* Depends only on its arguments, so a crossing saved halfway resumes on the same curve. null = the straight line
|
|
@@ -136,13 +144,14 @@ function charactersApi(e, st, animation) {
|
|
|
136
144
|
* @experimental
|
|
137
145
|
*/
|
|
138
146
|
linkPose: null,
|
|
147
|
+
/** How many findPathAsync requests leave per fixed step (default 32); the rest wait for the next steps */
|
|
139
148
|
get pathsPerStep() { return st.paths.perStep; },
|
|
140
149
|
set pathsPerStep(n) { st.paths.perStep = Math.max(1, n | 0); },
|
|
141
150
|
/**
|
|
142
151
|
* The 'camera' player control as a value: movement keys / stick relative to the camera (world axes, up = -Z, without a camera module), the 'run' action
|
|
143
152
|
* when the game bound one, input.autopilot.
|
|
144
153
|
* Returns a reused { x, z, run } (do not keep it). Call it from your own control function to wrap the default instead of rewriting it. seat: read an engine.input.seat() instead of engine.input
|
|
145
|
-
* @example
|
|
154
|
+
* @example addPlayer({ ...presets.player.thirdPerson, control: (p, input) => busy ? null : engine.characters.moveInput() }) // no movement while
|
|
146
155
|
* attacking
|
|
147
156
|
*/
|
|
148
157
|
moveInput(seat) { return moveInput(e, seat); },
|
|
@@ -162,7 +171,6 @@ function charactersApi(e, st, animation) {
|
|
|
162
171
|
*/
|
|
163
172
|
addVehicle(vehicle) { return e.ops.allow(() => addVehicle(e, vehicle)); },
|
|
164
173
|
/** @internal outside a fixed step: the rig calls it before it reads a rider's position (camera/common.js) */
|
|
165
|
-
/** @internal the camera calls this after its own step, so a rider and the view move together */
|
|
166
174
|
carryRiders() { carryRiders(e, true); },
|
|
167
175
|
/**
|
|
168
176
|
* Remove a player, by default engine.player (exit the vehicle first, stop responding to keys, dispose the model: animation, geometry, materials; the 'player' record in
|
|
@@ -186,13 +194,13 @@ function charactersApi(e, st, animation) {
|
|
|
186
194
|
* module at the player (and back after a vehicle)
|
|
187
195
|
* The world record, saving and describe().player work the same for every control. The engine drives the player on its channel (default
|
|
188
196
|
* 'player': dt passed to move and to the control function is engine.time.dt('player', 'player'), so engine.mod('time.player', ...) slows it)
|
|
189
|
-
* @example const player = engine.characters.
|
|
197
|
+
* @example const player = engine.characters.addPlayer({ ...presets.player.thirdPerson, spawn: engine.characters.findSpawn() })
|
|
190
198
|
* @example const roll = engine.control.take(player, { owner: 'roll', layer: 'script', step: () => ({ x: 0, z: 1, run: true }) }); engine.clock.after(0.4, () => roll.remove(), { channel: 'real' })
|
|
191
199
|
*/
|
|
192
200
|
// creating the player is setup (a game does it after loading its model, or on level:loaded), not a gameplay action: the ops guard lets its writes through
|
|
193
|
-
|
|
201
|
+
addPlayer(opts = {}) { return e.ops.allow(() => api._createPlayer(opts)); },
|
|
194
202
|
/** @internal */
|
|
195
|
-
_createPlayer(opts) { return
|
|
203
|
+
_createPlayer(opts) { return addPlayer(e, api, st, opts); },
|
|
196
204
|
};
|
|
197
205
|
return api;
|
|
198
206
|
}
|
|
@@ -200,9 +208,9 @@ function charactersApi(e, st, animation) {
|
|
|
200
208
|
/** The player's actions, declared once by the module (gone with it); the game binds their keys (presets.bindings.walk / .brake), so no option takes keys.
|
|
201
209
|
* optional: a player without jump or brake still works, reading them unbound stays silent */
|
|
202
210
|
function declareActions(ctx) {
|
|
203
|
-
ctx.input.
|
|
204
|
-
ctx.input.
|
|
205
|
-
ctx.input.
|
|
211
|
+
ctx.input.define('jump', { label: 'input.jump', optional: true });
|
|
212
|
+
ctx.input.define('run', { label: 'input.run', optional: true });
|
|
213
|
+
ctx.input.define('brake', { label: 'input.brake', context: 'vehicle', optional: true });
|
|
206
214
|
}
|
|
207
215
|
|
|
208
216
|
/** What the module listens to, all through ctx.track */
|
|
@@ -250,10 +258,10 @@ function describeCharacters(e, ctx, mgr) {
|
|
|
250
258
|
export function characters(opts = {}) {
|
|
251
259
|
readParams('characters', CHARACTERS_PARAMS, opts);
|
|
252
260
|
const { npcs = true, npcTiers, animation, fall } = opts;
|
|
253
|
-
// players: what
|
|
254
|
-
// engine.onFixed), so a game onFixed sees the same player position whether it was registered before or after
|
|
261
|
+
// players: what addPlayer made, by id. Their per-frame animation and per-step drive run in this module's own fixed / frame hooks (not
|
|
262
|
+
// engine.onFixed), so a game onFixed sees the same player position whether it was registered before or after addPlayer (phase 'early' = before the move,
|
|
255
263
|
// 'late' = after)
|
|
256
|
-
const st = { mgr: null, paths: null, path: null, players: new Map(), material: null };
|
|
264
|
+
const st = { mgr: null, paths: null, path: null, players: new Map(), material: null, keep: null };
|
|
257
265
|
return {
|
|
258
266
|
// before rigid: the player's move this step is in the physics step that follows (as when control was an onFixed)
|
|
259
267
|
content: { npcs: NPC_CONTENT },
|
|
@@ -285,7 +293,11 @@ export function characters(opts = {}) {
|
|
|
285
293
|
frame(dt, e) { for (const p of st.players.values()) p.character.animate(dt); carryRiders(e, true); },
|
|
286
294
|
describe(e, ctx) { describeCharacters(e, ctx, st.mgr); },
|
|
287
295
|
// a player, a queued path and the control lookup all outlive install unless they are ended here; the player's record stays in world, as NPC records do
|
|
288
|
-
dispose(e) {
|
|
296
|
+
dispose(e) {
|
|
297
|
+
for (const p of [...st.players.values()]) p.dispose(true); st.paths?.stop(); e.control.resolveWith(() => null); if (st.mgr) e.npcs = null;
|
|
298
|
+
if (isEngineMade(st.material)) st.material.dispose(); // the default capsule material is this module's (kept, so nothing else frees it); a game's stays the game's
|
|
299
|
+
st.keep?.remove(); st.material = st.keep = null;
|
|
300
|
+
},
|
|
289
301
|
};
|
|
290
302
|
}
|
|
291
303
|
|