threedog 0.0.0-stage → 0.1.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 +5 -0
- package/LICENSE +21 -0
- package/README.md +39 -2
- package/core/Animator.js +267 -0
- package/core/Assets.js +240 -0
- package/core/Audio.js +267 -0
- package/core/Baked.js +72 -0
- package/core/Batching.js +247 -0
- package/core/Budget.js +221 -0
- package/core/Clock.js +94 -0
- package/core/Commits.js +77 -0
- package/core/Describe.js +134 -0
- package/core/Engine.js +221 -0
- package/core/Events.js +95 -0
- package/core/I18n.js +94 -0
- package/core/Input.js +245 -0
- package/core/Inspect.js +97 -0
- package/core/InspectScene.js +187 -0
- package/core/Jobs.js +146 -0
- package/core/Loading.js +149 -0
- package/core/Ops.js +272 -0
- package/core/Random.js +52 -0
- package/core/Rays.js +160 -0
- package/core/SaveStore.js +85 -0
- package/core/Saves.js +253 -0
- package/core/Stream.js +279 -0
- package/core/Threads.js +158 -0
- package/core/UrlState.js +93 -0
- package/core/Vars.js +34 -0
- package/core/actor.js +23 -0
- package/core/assetEntry.js +89 -0
- package/core/assetLoad.js +190 -0
- package/core/assetManifest.js +35 -0
- package/core/audioRules.js +121 -0
- package/core/audioVoice.js +225 -0
- package/core/batchGroups.js +116 -0
- package/core/canvasBox.js +63 -0
- package/core/dayTime.js +15 -0
- package/core/describeText.js +136 -0
- package/core/easing.js +34 -0
- package/core/errorCodes.js +172 -0
- package/core/errorHints.js +203 -0
- package/core/errors.js +40 -0
- package/core/events.generated.js +84 -0
- package/core/ground.js +102 -0
- package/core/inputContext.js +69 -0
- package/core/inputDefaults.js +22 -0
- package/core/inputPad.js +35 -0
- package/core/inputPointer.js +48 -0
- package/core/inputTouch.js +48 -0
- package/core/lifecycle.js +68 -0
- package/core/lightWatch.js +36 -0
- package/core/loop.js +199 -0
- package/core/math.js +33 -0
- package/core/modules.js +182 -0
- package/core/movement.js +19 -0
- package/core/mulberry32.js +14 -0
- package/core/opsCheck.js +86 -0
- package/core/opsGuard.js +26 -0
- package/core/opsHistory.js +27 -0
- package/core/page.js +78 -0
- package/core/pureWorker.js +5 -0
- package/core/saveApply.js +128 -0
- package/core/saveFiles.js +139 -0
- package/core/saveIds.js +53 -0
- package/core/saveVersions.js +97 -0
- package/core/scatter.js +92 -0
- package/core/sceneMethods.js +125 -0
- package/core/screenToGround.js +39 -0
- package/core/session.js +171 -0
- package/core/shadowTypes.js +15 -0
- package/core/skip.js +104 -0
- package/core/startup.js +133 -0
- package/core/streamCells.js +24 -0
- package/core/streamSources.js +73 -0
- package/core/styleParts.js +96 -0
- package/core/targeting.js +64 -0
- package/core/thingOps.js +157 -0
- package/core/things.js +198 -0
- package/core/threadPure.js +120 -0
- package/core/threadServe.js +25 -0
- package/core/tier.js +11 -0
- package/core/validate.js +188 -0
- package/docs/AI.md +149 -0
- package/docs/API.md +84 -0
- package/docs/CODEMAP.md +335 -0
- package/docs/COMMANDS.md +96 -0
- package/docs/CONVENTIONS.md +134 -0
- package/docs/PERF.md +217 -0
- package/docs/THREE.md +86 -0
- package/docs/api/ambience.md +15 -0
- package/docs/api/assets.md +60 -0
- package/docs/api/audio.md +53 -0
- package/docs/api/budget.md +40 -0
- package/docs/api/cameraRig.md +120 -0
- package/docs/api/characters.md +142 -0
- package/docs/api/clock.md +7 -0
- package/docs/api/collision.md +35 -0
- package/docs/api/content.md +63 -0
- package/docs/api/debug.md +10 -0
- package/docs/api/dialogue.md +39 -0
- package/docs/api/engine.md +190 -0
- package/docs/api/entities.md +61 -0
- package/docs/api/events.md +91 -0
- package/docs/api/flow.md +27 -0
- package/docs/api/grids.md +11 -0
- package/docs/api/ground.md +16 -0
- package/docs/api/hlod.md +34 -0
- package/docs/api/hud.md +31 -0
- package/docs/api/i18n.md +10 -0
- package/docs/api/input.md +24 -0
- package/docs/api/interactions.md +31 -0
- package/docs/api/inventory.md +66 -0
- package/docs/api/jobs.md +10 -0
- package/docs/api/level.md +41 -0
- package/docs/api/lightPool.md +56 -0
- package/docs/api/music.md +34 -0
- package/docs/api/nav.md +26 -0
- package/docs/api/net.md +14 -0
- package/docs/api/openWorld.md +24 -0
- package/docs/api/particles.md +41 -0
- package/docs/api/photo.md +15 -0
- package/docs/api/post.md +9 -0
- package/docs/api/quests.md +36 -0
- package/docs/api/rays.md +26 -0
- package/docs/api/rigid.md +84 -0
- package/docs/api/saves.md +31 -0
- package/docs/api/settings.md +36 -0
- package/docs/api/sky.md +58 -0
- package/docs/api/stream.md +31 -0
- package/docs/api/style.md +134 -0
- package/docs/api/terrain.md +34 -0
- package/docs/api/timeline.md +39 -0
- package/docs/api/tools.md +55 -0
- package/docs/api/triggers.md +56 -0
- package/docs/api/vars.md +9 -0
- package/docs/api/vegetation.md +52 -0
- package/docs/api/water.md +48 -0
- package/docs/api/weather.md +29 -0
- package/docs/api/world.md +30 -0
- package/docs/recipes/01-new-game.md +148 -0
- package/docs/recipes/02-npc.md +151 -0
- package/docs/recipes/03-items-pickups.md +158 -0
- package/docs/recipes/04-quests.md +83 -0
- package/docs/recipes/05-props-bake.md +159 -0
- package/docs/recipes/06-clock-events.md +104 -0
- package/docs/recipes/07-flow-scenes-pause.md +128 -0
- package/docs/recipes/08-weather-sky.md +74 -0
- package/docs/recipes/09-style-pack.md +234 -0
- package/docs/recipes/10-blender-level.md +67 -0
- package/docs/recipes/11-vehicles.md +55 -0
- package/docs/recipes/12-navmesh.md +57 -0
- package/docs/recipes/13-animation.md +146 -0
- package/docs/recipes/14-custom-module.md +91 -0
- package/docs/recipes/15-perf.md +78 -0
- package/docs/recipes/16-dev-bridge.md +146 -0
- package/docs/recipes/18-world.md +185 -0
- package/docs/recipes/19-shooting-picking.md +76 -0
- package/docs/recipes/20-content-actions-save.md +176 -0
- package/docs/recipes/21-camera.md +104 -0
- package/docs/recipes/22-shop-gold.md +107 -0
- package/docs/recipes/23-ops.md +139 -0
- package/docs/recipes/26-ui-parts.md +138 -0
- package/docs/recipes/27-net.md +96 -0
- package/docs/recipes/28-terrain.md +80 -0
- package/docs/recipes/29-grid.md +87 -0
- package/docs/recipes/30-templates.md +131 -0
- package/docs/recipes/31-audio.md +126 -0
- package/docs/recipes/32-action-game.md +33 -0
- package/docs/recipes/33-stream-sources.md +37 -0
- package/docs/recipes/34-environment-lighting.md +35 -0
- package/docs/recipes/35-style-from-reference.md +89 -0
- package/docs/recipes/36-sky-ground-plant-looks.md +116 -0
- package/docs/recipes/37-terrain-look-hooks.md +97 -0
- package/docs/recipes/38-environment-look-hooks.md +81 -0
- package/docs/recipes/40-scene.md +79 -0
- package/docs/recipes/41-thing-registry.md +64 -0
- package/docs/recipes/42-terrain-shape.md +64 -0
- package/docs/recipes/43-shader-patches-surface-looks.md +118 -0
- package/docs/recipes/44-water-weather-look-hooks.md +133 -0
- package/docs/recipes/45-cascaded-shadows.md +51 -0
- package/docs/recipes/46-blender-art-route.md +92 -0
- package/docs/recipes/47-island-snow-backdrop.md +44 -0
- package/examples/action/DESIGN.md +3 -0
- package/examples/action/GAMEMAP.md +127 -0
- package/examples/action/content/actions.js +8 -0
- package/examples/action/content/audio.js +9 -0
- package/examples/action/content/index.js +9 -0
- package/examples/action/content/items.js +4 -0
- package/examples/action/content/places.js +4 -0
- package/examples/action/content/props.js +11 -0
- package/examples/action/content/templates.js +10 -0
- package/examples/action/look.js +5 -0
- package/examples/action/main.js +137 -0
- package/examples/action/models.js +25 -0
- package/examples/sheepisland/GAMEMAP.md +108 -0
- package/examples/sheepisland/content/index.js +6 -0
- package/examples/sheepisland/content/props.js +19 -0
- package/examples/sheepisland/content/templates.js +5 -0
- package/examples/sheepisland/content/vegetation.js +8 -0
- package/examples/sheepisland/main.js +71 -0
- package/examples/sheepisland/params.js +25 -0
- package/examples/sheepisland/style/index.js +79 -0
- package/examples/sheepisland/style/models.js +59 -0
- package/examples/sheepisland/views.js +9 -0
- package/examples/styletest/GAMEMAP.md +135 -0
- package/examples/styletest/content/index.js +9 -0
- package/examples/styletest/content/items.js +8 -0
- package/examples/styletest/content/npcs.js +8 -0
- package/examples/styletest/content/places.js +5 -0
- package/examples/styletest/content/props.js +16 -0
- package/examples/styletest/content/templates.js +9 -0
- package/examples/styletest/content/vegetation.js +31 -0
- package/examples/styletest/look.js +11 -0
- package/examples/styletest/main.js +95 -0
- package/examples/styletest/models.js +87 -0
- package/examples/styletest/overrides.js +33 -0
- package/examples/styletest/panel.js +135 -0
- package/examples/styletest/params.js +32 -0
- package/examples/styletest/views.js +31 -0
- package/examples/world/DESIGN.md +5 -0
- package/examples/world/GAMEMAP.md +171 -0
- package/examples/world/content/actions.js +8 -0
- package/examples/world/content/audio.js +25 -0
- package/examples/world/content/bodies.js +12 -0
- package/examples/world/content/containers.js +4 -0
- package/examples/world/content/dialogues.js +33 -0
- package/examples/world/content/index.js +17 -0
- package/examples/world/content/items.js +10 -0
- package/examples/world/content/npcs.js +14 -0
- package/examples/world/content/pickups.js +11 -0
- package/examples/world/content/places.js +6 -0
- package/examples/world/content/props.js +12 -0
- package/examples/world/content/quests.js +15 -0
- package/examples/world/content/rules.js +23 -0
- package/examples/world/content/templates.js +5 -0
- package/examples/world/content/vegetation.js +32 -0
- package/examples/world/main.js +168 -0
- package/examples/world/models.js +28 -0
- package/index.d.ts +279 -0
- package/index.js +120 -0
- package/llms.txt +56 -0
- package/modules/ambience/Ambience.js +183 -0
- package/modules/camera/FirstPersonCamera.js +133 -0
- package/modules/camera/FixedCamera.js +155 -0
- package/modules/camera/FollowCamera.js +85 -0
- package/modules/camera/RtsCamera.js +134 -0
- package/modules/camera/common.js +152 -0
- package/modules/camera/index.js +11 -0
- package/modules/characters/Character.js +223 -0
- package/modules/characters/NPC.js +242 -0
- package/modules/characters/assetModel.js +42 -0
- package/modules/characters/astar.js +59 -0
- package/modules/characters/behaviors.js +72 -0
- package/modules/characters/footsteps.js +13 -0
- package/modules/characters/index.js +212 -0
- package/modules/characters/moveHelpers.js +29 -0
- package/modules/characters/movers/common.js +62 -0
- package/modules/characters/movers/rapier.js +74 -0
- package/modules/characters/movers/simple.js +38 -0
- package/modules/characters/npcAvoid.js +129 -0
- package/modules/characters/npcSim.js +144 -0
- package/modules/characters/npcView.js +42 -0
- package/modules/characters/pathAsync.js +107 -0
- package/modules/characters/pathJob.js +61 -0
- package/modules/characters/pathWorker.js +7 -0
- package/modules/characters/playerStrings.js +12 -0
- package/modules/characters/proceduralRig.js +54 -0
- package/modules/collision/Collision.js +176 -0
- package/modules/collision/grid.js +63 -0
- package/modules/content/ids.js +95 -0
- package/modules/content/index.js +152 -0
- package/modules/content/loader.js +187 -0
- package/modules/content/models.js +69 -0
- package/modules/content/packs.js +69 -0
- package/modules/content/props.js +89 -0
- package/modules/content/rules.js +133 -0
- package/modules/content/templates.js +189 -0
- package/modules/debug/DebugPanel.js +168 -0
- package/modules/entities/Entities.js +239 -0
- package/modules/entities/build.js +25 -0
- package/modules/entities/index.js +4 -0
- package/modules/flow/index.js +98 -0
- package/modules/gameplay/Container.js +227 -0
- package/modules/gameplay/Containers.js +89 -0
- package/modules/gameplay/Dialogue.js +216 -0
- package/modules/gameplay/Interactions.js +243 -0
- package/modules/gameplay/Inventory.js +214 -0
- package/modules/gameplay/Quests.js +195 -0
- package/modules/gameplay/boxOps.js +60 -0
- package/modules/gameplay/dialogueBox.js +48 -0
- package/modules/gameplay/interactionPrompt.js +28 -0
- package/modules/gameplay/inventoryOps.js +137 -0
- package/modules/gameplay/pickups.js +113 -0
- package/modules/gameplay/questLog.js +54 -0
- package/modules/gameplay/questSave.js +71 -0
- package/modules/grid/Grid.js +184 -0
- package/modules/grid/Layer.js +142 -0
- package/modules/grid/index.js +236 -0
- package/modules/grid/ops.js +73 -0
- package/modules/grid/preview.js +85 -0
- package/modules/grid/tiles.js +75 -0
- package/modules/hlod/index.js +164 -0
- package/modules/hud/index.js +164 -0
- package/modules/hud/parts.js +80 -0
- package/modules/level/geometry.js +46 -0
- package/modules/level/heightfield.js +160 -0
- package/modules/level/index.js +231 -0
- package/modules/level/nodes.js +84 -0
- package/modules/lights/index.js +224 -0
- package/modules/music/Music.js +290 -0
- package/modules/music/index.js +2 -0
- package/modules/music/rules.js +28 -0
- package/modules/nav/index.js +154 -0
- package/modules/nav/navPath.js +17 -0
- package/modules/net/Client.js +136 -0
- package/modules/net/Host.js +117 -0
- package/modules/net/Net.js +49 -0
- package/modules/net/index.js +75 -0
- package/modules/net/sync.js +114 -0
- package/modules/net/transports.js +118 -0
- package/modules/particles/Particles.js +179 -0
- package/modules/particles/effect.js +112 -0
- package/modules/particles/shaders.js +28 -0
- package/modules/photo/Photo.js +143 -0
- package/modules/rigid/RigidBodies.js +262 -0
- package/modules/rigid/Vehicles.js +97 -0
- package/modules/rigid/sync.js +158 -0
- package/modules/settings/Settings.js +294 -0
- package/modules/settings/apply.js +20 -0
- package/modules/settings/index.js +3 -0
- package/modules/settings/sections.js +156 -0
- package/modules/settings/strings.js +53 -0
- package/modules/settings/view.js +65 -0
- package/modules/sky/Sky.js +257 -0
- package/modules/sky/calendar.js +80 -0
- package/modules/sky/cascades.js +125 -0
- package/modules/sky/clouds.js +79 -0
- package/modules/sky/domeLayers.js +33 -0
- package/modules/sky/environment.js +115 -0
- package/modules/sky/fog.js +136 -0
- package/modules/sky/frame.js +76 -0
- package/modules/sky/layers.js +69 -0
- package/modules/sky/look.js +50 -0
- package/modules/sky/schedule.js +80 -0
- package/modules/sky/shader.js +96 -0
- package/modules/sky/shadow.js +80 -0
- package/modules/sky/skyModule.js +59 -0
- package/modules/terrain/ChunkManager.js +291 -0
- package/modules/terrain/chunkJob.js +19 -0
- package/modules/terrain/chunkQueries.js +42 -0
- package/modules/terrain/chunkWorker.js +5 -0
- package/modules/terrain/index.js +110 -0
- package/modules/terrain/mountTerrain.js +32 -0
- package/modules/terrain/terrainColorMap.js +41 -0
- package/modules/terrain/terrainDefaults.js +39 -0
- package/modules/terrain/terrainEdit.js +139 -0
- package/modules/terrain/terrainGen.js +155 -0
- package/modules/terrain/terrainIsland.js +131 -0
- package/modules/terrain/terrainMesh.js +92 -0
- package/modules/terrain/terrainShape.js +108 -0
- package/modules/terrain/terrainShapeMain.js +41 -0
- package/modules/terrain/terrainTexture.js +44 -0
- package/modules/timeline/Timeline.js +249 -0
- package/modules/timeline/Tween.js +118 -0
- package/modules/timeline/letterbox.js +24 -0
- package/modules/timeline/shots.js +88 -0
- package/modules/triggers/index.js +261 -0
- package/modules/vegetation/Vegetation.js +255 -0
- package/modules/vegetation/groundChunks.js +177 -0
- package/modules/vegetation/index.js +40 -0
- package/modules/vegetation/modelGeometry.js +21 -0
- package/modules/water/Water.js +144 -0
- package/modules/water/surface.js +88 -0
- package/modules/weather/Weather.js +251 -0
- package/modules/weather/particles.js +92 -0
- package/modules/weather/shaders.js +49 -0
- package/modules/world/World.js +231 -0
- package/modules/world/cells.js +42 -0
- package/modules/world/index.js +64 -0
- package/modules/world/persist.js +107 -0
- package/modules/world/pos.js +20 -0
- package/modules/world/records.js +89 -0
- package/modules/world/sim.js +175 -0
- package/modules/world/simFar.js +82 -0
- package/modules/world/state.js +115 -0
- package/modules/world/views.js +182 -0
- package/package.json +66 -4
- package/presets.js +96 -0
- package/render/PostFX.js +243 -0
- package/render/detail.js +105 -0
- package/render/effects.js +142 -0
- package/render/engineUniforms.js +23 -0
- package/render/fuse.js +72 -0
- package/render/lighting.js +100 -0
- package/render/lights.js +16 -0
- package/render/materials.js +203 -0
- package/render/patches.js +252 -0
- package/render/surface.js +67 -0
- package/render/uniformDecl.js +29 -0
- package/types/common.d.ts +34 -0
- package/types/core.d.ts +1773 -0
- package/types/gameplay.d.ts +1812 -0
- package/types/generated/core/Audio.d.ts +200 -0
- package/types/generated/core/Batching.d.ts +47 -0
- package/types/generated/core/Budget.d.ts +90 -0
- package/types/generated/core/Commits.d.ts +31 -0
- package/types/generated/core/Events.d.ts +46 -0
- package/types/generated/core/I18n.d.ts +30 -0
- package/types/generated/core/Input.d.ts +118 -0
- package/types/generated/core/Jobs.d.ts +41 -0
- package/types/generated/core/Ops.d.ts +162 -0
- package/types/generated/core/Random.d.ts +49 -0
- package/types/generated/core/Rays.d.ts +49 -0
- package/types/generated/core/Saves.d.ts +161 -0
- package/types/generated/core/Stream.d.ts +93 -0
- package/types/generated/core/Threads.d.ts +82 -0
- package/types/generated/core/audioVoice.d.ts +47 -0
- package/types/generated/core/page.d.ts +18 -0
- package/types/generated/core/session.d.ts +48 -0
- package/types/generated/modules/ambience/Ambience.d.ts +48 -0
- package/types/generated/modules/debug/DebugPanel.d.ts +24 -0
- package/types/generated/modules/flow/index.d.ts +10 -0
- package/types/generated/modules/grid/Grid.d.ts +151 -0
- package/types/generated/modules/grid/Layer.d.ts +64 -0
- package/types/generated/modules/grid/index.d.ts +86 -0
- package/types/generated/modules/hlod/index.d.ts +11 -0
- package/types/generated/modules/hud/index.d.ts +10 -0
- package/types/generated/modules/lights/index.d.ts +13 -0
- package/types/generated/modules/music/Music.d.ts +111 -0
- package/types/generated/modules/net/Net.d.ts +34 -0
- package/types/generated/modules/net/index.d.ts +53 -0
- package/types/generated/modules/net/transports.d.ts +58 -0
- package/types/generated/modules/particles/Particles.d.ts +69 -0
- package/types/generated/modules/sky/Sky.d.ts +152 -0
- package/types/generated/modules/sky/skyModule.d.ts +10 -0
- package/types/generated/modules/timeline/Timeline.d.ts +51 -0
- package/types/generated/modules/water/Water.d.ts +29 -0
- package/types/generated/modules/weather/Weather.d.ts +72 -0
- package/types/generated/modules/world/World.d.ts +242 -0
- package/types/generated/modules/world/index.d.ts +15 -0
- package/types/generated/render/PostFX.d.ts +128 -0
- package/types/generated/render/materials.d.ts +90 -0
- package/types/generated/render/patches.d.ts +41 -0
- package/types/generated/ui/Focus.d.ts +11 -0
- package/types/generated/ui/LoadingScreen.d.ts +2 -0
- package/types/generated/ui/UI.d.ts +57 -0
- package/types/nav.d.ts +52 -0
- package/types/physics.d.ts +584 -0
- package/types/style.d.ts +628 -0
- package/types/worker.d.ts +11 -0
- package/types/world.d.ts +772 -0
- package/ui/Focus.js +51 -0
- package/ui/LoadingScreen.js +42 -0
- package/ui/Parts.js +195 -0
- package/ui/UI.js +167 -0
- package/ui/defaults.js +85 -0
- package/ui/theme.js +124 -0
- package/ui/touchPart.js +49 -0
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
// Characters module: player (keyboard/stick control, camera follow, footsteps, enter/exit vehicles) and NPCs (schedule, pathfinding, dialogue).
|
|
2
|
+
// The only pathfinding entry is engine.characters.findPath: uses the navmesh if nav is installed and ready, else A* (astar.js is an internal fallback, not
|
|
3
|
+
// exported).
|
|
4
|
+
// NPC facts live in engine.world (kind 'npc'), the model is just a presentation when near (see the top of NPC.js): NPCs need world() installed (openWorld
|
|
5
|
+
// already does).
|
|
6
|
+
// The player is also a world record (id / kind both 'player'): position, facing, motion state and current vehicle live in the record and are saved with world;
|
|
7
|
+
// world splits near / far by it by default.
|
|
8
|
+
// Only the mover changes the player's position (Character.move / placeAt / enter / exit), then writes back to the record; loading places the player back by the
|
|
9
|
+
// record. So install world() before creating the player.
|
|
10
|
+
// Vehicles are used through an interface (the { object, speed, drive(), seatPosition(), exitPosition() } returned by rigid.addVehicle); rigid is not imported
|
|
11
|
+
// here.
|
|
12
|
+
import { Character, CHARACTER_KEYS } from './Character.js';
|
|
13
|
+
import { NPCManager, NPC } from './NPC.js';
|
|
14
|
+
import { findPath } from './astar.js';
|
|
15
|
+
import { findSpawn, moveInput } from './moveHelpers.js';
|
|
16
|
+
import { AsyncPaths } from './pathAsync.js';
|
|
17
|
+
import { checkOptions, warnOnce, DEV } from '../../core/validate.js';
|
|
18
|
+
import { codedError, coded } from '../../core/errorHints.js';
|
|
19
|
+
import { DEV_STRINGS, STRINGS, validControl } from './playerStrings.js';
|
|
20
|
+
import { footstepSynth, stepSound } from './footsteps.js';
|
|
21
|
+
import { xzOf } from '../../core/math.js';
|
|
22
|
+
export { Character, NPC };
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Characters module. Once installed:
|
|
26
|
+
* engine.characters.createPlayer({ spawn: {x, z}, colors, model, clips }) → player
|
|
27
|
+
* engine.npcs.add({ id, name, schedule, talk, ... }) → NPC handle (needs npcs: true, on by default; data lives in engine.world)
|
|
28
|
+
* engine.npcs.remove(npc or name); engine.characters.removePlayer()
|
|
29
|
+
* three.js object of player and NPC: .object (= .root, Group), position .position (Vector3); spawn / position accept a Vector3 directly
|
|
30
|
+
* When an NPC is far it has no model: npc.root is null, npc.position is the data position
|
|
31
|
+
*/
|
|
32
|
+
const PLAYER = 'player';
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
/** Navmesh when ready, else A* (characters.findPath; the one synchronous A* entry, see R20) */
|
|
37
|
+
function solvePath(e, from, to, o) {
|
|
38
|
+
const { detailed, ...rest } = o;
|
|
39
|
+
let res;
|
|
40
|
+
if (e.nav?.ready) res = e.nav.findPath(from, to, { ...rest, detailed: true });
|
|
41
|
+
else if (!e.collision) res = { status: 'notReady', path: null };
|
|
42
|
+
else {
|
|
43
|
+
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
|
+
// nav installed but not ready: A* is only a stand-in, tell the caller honestly
|
|
46
|
+
res = { status: e.nav ? 'notReady' : path ? 'ok' : 'noPath', path };
|
|
47
|
+
}
|
|
48
|
+
return detailed ? res : res.path;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function characters(opts = {}) {
|
|
52
|
+
const { npcs = true, brakeKeys, brakePad } = opts; // no brake key by default: characters({ ...presets.keys.brake }) or the game's own
|
|
53
|
+
let mgr = null, paths = null, disposePlayer = null;
|
|
54
|
+
return {
|
|
55
|
+
name: 'characters', label: 'Characters', optional: ['cameraRig', 'sky', 'interactions', 'dialogue', 'nav', 'collision', 'rigid', 'world'],
|
|
56
|
+
install(e) {
|
|
57
|
+
checkOptions('characters()', opts, ['npcs', 'brakeKeys', 'brakePad']);
|
|
58
|
+
e.i18n.add(STRINGS);
|
|
59
|
+
e.audio.register('footstep', footstepSynth, { builtIn: true });
|
|
60
|
+
if (npcs) { mgr = new NPCManager(e); e.npcs = mgr; }
|
|
61
|
+
paths = new AsyncPaths(e);
|
|
62
|
+
e.events.on('ground:change', b => paths.dropTiles(b)); // dug or raised ground: resample the path rasters there
|
|
63
|
+
e.events.on('level:loaded', () => paths.tiles.clear()); // another level: none of the cached rasters describe it
|
|
64
|
+
const api = {
|
|
65
|
+
/**
|
|
66
|
+
* Find a spawn point: spiral outward from position (default origin) for walkable ground (no obstacles, gentle slope) that is not in water. Returns a
|
|
67
|
+
* Vector3 (y is ground height).
|
|
68
|
+
* Assumes no terrain: height range minH / maxH is unbounded by default (open worlds pass their own to avoid beaches and peaks); waterMargin minimum
|
|
69
|
+
* height above water in meters (default 0.5)
|
|
70
|
+
*/
|
|
71
|
+
findSpawn(position = { x: 0, z: 0 }, opts = {}) { return findSpawn(e, position, opts); },
|
|
72
|
+
/**
|
|
73
|
+
* Pathfinding (the only entry): navmesh if nav is ready, else A* (needs the collision module). Returns [{ x, z }…], null if unreachable.
|
|
74
|
+
* Pass { detailed: true } to get { status, path }: 'ok' found | 'noPath' unreachable | 'notReady' nav installed but mesh not generated yet (path is the
|
|
75
|
+
* A* fallback, may be inaccurate; null without collision)
|
|
76
|
+
*/
|
|
77
|
+
findPath(from, to, o = {}) { return solvePath(e, from, to, o); },
|
|
78
|
+
/**
|
|
79
|
+
* findPath for many callers (NPC crowds, AI squads): solved in engine.threads workers, done(path, status) runs on a fixed step ~4 steps later
|
|
80
|
+
* 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
|
|
81
|
+
* section 4.
|
|
82
|
+
* @param {any} from
|
|
83
|
+
* @param {any} to
|
|
84
|
+
* @param {(path: { x: number, z: number }[] | null, status: 'ok' | 'noPath' | 'notReady') => void} done
|
|
85
|
+
* @param {{ radius?: number, step?: number, maxNodes?: number }} [opts]
|
|
86
|
+
* @returns {{ cancel: () => void }}
|
|
87
|
+
* @example const req = engine.characters.findPathAsync(guard.position, target, (path, status) => { guard.path = path; });
|
|
88
|
+
* req.remove(); // target changed before the answer came
|
|
89
|
+
*/
|
|
90
|
+
findPathAsync(from, to, done, opts) { return paths.request(from, to, done, opts); },
|
|
91
|
+
/** How many findPathAsync requests leave per fixed step (default 32); the rest wait for the next steps */
|
|
92
|
+
get pathsPerStep() { return paths.perStep; },
|
|
93
|
+
set pathsPerStep(n) { paths.perStep = Math.max(1, n | 0); },
|
|
94
|
+
/**
|
|
95
|
+
* 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
|
|
96
|
+
* when the game bound one, input.autopilot.
|
|
97
|
+
* Returns a reused { x, z, run, speed } (do not keep it). Call it from your own control function to wrap the default instead of rewriting it
|
|
98
|
+
* @example createPlayer({ ...presets.player.thirdPerson, control: (p, input) => busy ? null : engine.characters.moveInput() }) // no movement while
|
|
99
|
+
* attacking
|
|
100
|
+
*/
|
|
101
|
+
moveInput() { return moveInput(e); },
|
|
102
|
+
/**
|
|
103
|
+
* Remove the current player (exit the vehicle first, stop responding to keys, dispose the model: animation, geometry, materials; the 'player' record in
|
|
104
|
+
* world is removed too)
|
|
105
|
+
*/
|
|
106
|
+
removePlayer() { disposePlayer?.(); disposePlayer = null; },
|
|
107
|
+
/**
|
|
108
|
+
* Create the player. The engine assumes no feel: control is required, keys and camera follow come only from options (presets.player.* bundle them).
|
|
109
|
+
* The player is also the world record with id 'player' (needs the world module).
|
|
110
|
+
* Without spawn and with an existing player record in world (loaded before the player was created) it continues from the record's position; move the
|
|
111
|
+
* player with player.placeAt(position)
|
|
112
|
+
* control (required; also the plain property player.control, switch it at any time) decides who moves the player each fixed step:
|
|
113
|
+
* 'camera' moveInput(): movement keys relative to the camera, plus the jump key and vehicle driving
|
|
114
|
+
* function (player, input, dt) => ({ x, z, run?, speed? }) | null: you decide direction and speed (null = stand still); jump key and vehicles stay.
|
|
115
|
+
* Side-scroller: return { x: input.axis.x, z: 0 }
|
|
116
|
+
* 'none': the engine never moves the player; call player.move(x, z, run, dt) yourself once per fixed step (rolls, attack lunges, hit stun)
|
|
117
|
+
* runKeys / jumpKeys bind the 'run' / 'jump' actions (no keys are bound otherwise; player.jump() still works); cameraFollow: true points the camera
|
|
118
|
+
* module at the player (and back after a vehicle)
|
|
119
|
+
* The world record, saving and describe().player work the same for every control
|
|
120
|
+
* @example const player = engine.characters.createPlayer({ ...presets.player.thirdPerson, spawn: engine.characters.findSpawn() })
|
|
121
|
+
* @example const player = engine.characters.createPlayer({ ...presets.player.none, cameraFollow: true }); engine.onFixed(dt => player.move(0, 0, false,
|
|
122
|
+
* dt))
|
|
123
|
+
*/
|
|
124
|
+
createPlayer(opts = {}) {
|
|
125
|
+
checkOptions('characters.createPlayer()', opts, [...CHARACTER_KEYS, 'spawn', 'jumpKeys', 'runKeys', 'control', 'cameraFollow']);
|
|
126
|
+
const control = opts.control;
|
|
127
|
+
if (control === undefined) throw codedError('player-control', DEV_STRINGS.noControl);
|
|
128
|
+
if (!validControl(control)) throw codedError('player-control', DEV_STRINGS.badControl.replace('{got}', JSON.stringify(control) ?? String(control)));
|
|
129
|
+
const W = e.world;
|
|
130
|
+
if (!W) throw new Error(DEV_STRINGS.noWorld);
|
|
131
|
+
// vehicle id saved in the player record; a number is a save from before vehicles had ids (the index in rigid.vehicles)
|
|
132
|
+
const vehicleOf = v => v == null ? null : typeof v === 'number' ? (v >= 0 ? e.rigid?.vehicles[v] ?? null : null) : e.rigid?.vehicles.find(c => c.id === v) ?? null;
|
|
133
|
+
disposePlayer?.(); // existing player: dispose the old one first (else two characters respond to keys)
|
|
134
|
+
const p = new Character(e, opts), had = W.get(PLAYER);
|
|
135
|
+
p.control = control;
|
|
136
|
+
p.cameraFollow = !!opts.cameraFollow; // read again on vehicle exit and a new session (Character.js, camera/common.js)
|
|
137
|
+
if (DEV && opts.cameraFollow === undefined && e.cameraRig) warnOnce(coded('player-control', DEV_STRINGS.noFollow));
|
|
138
|
+
if (!had) W.add({ id: PLAYER, kind: PLAYER, position: [0, 0, 0], vehicle: null });
|
|
139
|
+
// place the player by the record (loading, reusing an existing record): do not write back to the record while placing, write once afterwards so
|
|
140
|
+
// record and character agree
|
|
141
|
+
const apply = rec => {
|
|
142
|
+
const car = vehicleOf(rec.vehicle), { x, y, z } = rec.position;
|
|
143
|
+
p.recordId = null;
|
|
144
|
+
if (p.vehicle && p.vehicle !== car) p.exit(); // when loading a walking save, exit the vehicle first, else every step pulls it back to the seat
|
|
145
|
+
p.root.position.set(x, y, z); p.loadMotion(rec);
|
|
146
|
+
if (car && p.vehicle !== car) p.enter(car);
|
|
147
|
+
p.recordId = PLAYER; p._store();
|
|
148
|
+
};
|
|
149
|
+
if (had && !opts.spawn) apply(had);
|
|
150
|
+
else { p.recordId = PLAYER; p.placeAt(opts.spawn || api.findSpawn()); }
|
|
151
|
+
p.addTo();
|
|
152
|
+
p.onStep = type => e.audio.sfx(stepSound(e, type));
|
|
153
|
+
p.onLand = impact => { if (impact > 3) e.audio.sfx(stepSound(e, p.groundType()), { volume: Math.min(2, impact / 6) }); };
|
|
154
|
+
// the game's keys only: no Space-to-jump or Shift-to-run unless it (or a preset it picked) asked
|
|
155
|
+
if (p.canJump && opts.jumpKeys) { e.input.define('jump', opts.jumpKeys, 'input.jump'); e.input.touchButton('jump', 'input.jump'); }
|
|
156
|
+
if (opts.runKeys) e.input.define('run', opts.runKeys, 'input.run');
|
|
157
|
+
// brake: a separate action, only when the game gives keys (characters({ brakeKeys, brakePad }) or presets.keys.brake: B / gamepad LT), does not
|
|
158
|
+
// compete with jump on space. Registered only when driving is possible (rigid installed)
|
|
159
|
+
if (e.rigid && (brakeKeys || brakePad)) e.input.define('brake', brakeKeys ?? [], 'input.brake', { pad: brakePad, context: 'vehicle' });
|
|
160
|
+
e.player = p;
|
|
161
|
+
if (p.cameraFollow) e.cameraRig?.follow(p.root);
|
|
162
|
+
// gameplay keys are read in the fixed step (input snapshot, frame-rate independent); frame only plays animation
|
|
163
|
+
const fixedHook = e.onFixed(dt => {
|
|
164
|
+
const c = p.control;
|
|
165
|
+
if (c === 'none') return; // the game drives the player itself: no key reads, no move
|
|
166
|
+
// player.control set to a bad value at runtime
|
|
167
|
+
if (!validControl(c)) { warnOnce(coded('player-control', DEV_STRINGS.badControl.replace('{got}', JSON.stringify(c) ?? String(c)))); return; }
|
|
168
|
+
const has = a => e.input.actions.has(a); // keys the game bound; an unbound action is simply not used
|
|
169
|
+
// when the interactions module is installed, the vehicle's "exit" interaction handles it
|
|
170
|
+
if (p.vehicle) { if (!e.interactions && has('interact') && e.input.pressed('interact')) p.exit(); }
|
|
171
|
+
else if (p.canJump && has('jump') && e.input.pressed('jump')) p.jump();
|
|
172
|
+
if (p.vehicle) { const a = e.input.autopilot || e.input.axis; p.vehicle.drive(a.y, a.x, e.input.actions.has('brake') && e.input.down('brake') ? 1 : 0); }
|
|
173
|
+
const m = c === 'camera' ? api.moveInput() : c(p, e.input, dt);
|
|
174
|
+
p.move(m?.x ?? 0, m?.z ?? 0, !!m?.run, dt, m?.speed);
|
|
175
|
+
});
|
|
176
|
+
const frameHook = e.onFrame(dt => p.animate(dt));
|
|
177
|
+
// record the stable id of the vehicle the player is in (world.set: world:change fires; it follows an enter / exit that already happened)
|
|
178
|
+
const setCar = id => e.ops.allow(() => W.set(PLAYER, { vehicle: id }));
|
|
179
|
+
const onCar = e.events.on('vehicle:enter', ({ character }) => { if (character === p) setCar(p.vehicle?.id ?? null); });
|
|
180
|
+
const offCar = e.events.on('vehicle:exit', ({ character }) => { if (character === p) setCar(null); });
|
|
181
|
+
// loading: after world is replaced wholesale, place the player back by the record; if the save has no player record (saved before the player was
|
|
182
|
+
// created), add one from the current state
|
|
183
|
+
const onLoad = e.events.on('world:load', () => {
|
|
184
|
+
const rec = W.get(PLAYER);
|
|
185
|
+
if (rec) apply(rec);
|
|
186
|
+
else { W.add({ id: PLAYER, kind: PLAYER, position: p.position, vehicle: null }); p._store(); }
|
|
187
|
+
});
|
|
188
|
+
disposePlayer = () => {
|
|
189
|
+
fixedHook.remove(); frameHook.remove(); onCar.remove(); offCar.remove(); onLoad.remove();
|
|
190
|
+
p.recordId = null; p.dispose(); W.remove(PLAYER);
|
|
191
|
+
if (e.player === p) e.player = null;
|
|
192
|
+
};
|
|
193
|
+
return p;
|
|
194
|
+
},
|
|
195
|
+
};
|
|
196
|
+
return api;
|
|
197
|
+
},
|
|
198
|
+
// NPC simulation and animation are driven by world (simulate / present update); here we only register with world at start; without world, wait for the
|
|
199
|
+
// first npcs.add and then report the error
|
|
200
|
+
init(e) { if (mgr && e.world) mgr.setup(); },
|
|
201
|
+
fixed() { paths.flush(); },
|
|
202
|
+
describe(e, ctx) {
|
|
203
|
+
// with a model report by the model (merged with interaction points and world's own report for the same object into one), without a model report by data
|
|
204
|
+
// position
|
|
205
|
+
for (const r of mgr && e.world ? e.world.query({ kind: 'npc', near: ctx.center, radius: ctx.radius, where: r => e.world.zone == null || r.zone == null || r.zone === e.world.zone }) : []) {
|
|
206
|
+
ctx.near(e.world.view(r.id) ?? r.position, { id: r.id, name: r.name, kind: 'npc', state: r.state });
|
|
207
|
+
}
|
|
208
|
+
if (ctx.out.player) Object.assign(ctx.out.player, { swimming: e.player.swimming, grounded: e.player.grounded, facing: Math.round(e.player.facing * 100) / 100,
|
|
209
|
+
control: typeof e.player.control === 'function' ? 'custom' : e.player.control, faceMode: e.player.faceMode, mover: e.player.mover.name, ...(e.player.anim && { anim: e.player.anim.describe() }), ...(e.player.vehicle && { vehicle: { speed: Math.round(e.player.vehicle.speed * 10) / 10 } }) });
|
|
210
|
+
},
|
|
211
|
+
};
|
|
212
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Spawn search and the camera-relative move input (split out of index.js; the characters API calls these with its engine)
|
|
2
|
+
import * as THREE from 'three';
|
|
3
|
+
import { xzOf } from '../../core/math.js';
|
|
4
|
+
import { checkOptionsArg } from '../../core/validate.js';
|
|
5
|
+
|
|
6
|
+
const REQ = { x: 0, z: 0, run: false, speed: undefined }; // moveInput() result, reused every step (no allocation)
|
|
7
|
+
|
|
8
|
+
/** Spiral outward from position for walkable dry ground (characters.findSpawn) */
|
|
9
|
+
export function findSpawn(e, position, opts) {
|
|
10
|
+
const [x, z] = xzOf(position);
|
|
11
|
+
checkOptionsArg('characters.findSpawn()', opts, ['minH', 'maxH', 'maxSlope', 'waterMargin']);
|
|
12
|
+
const { minH = -Infinity, maxH = Infinity, maxSlope = 0.3, waterMargin = 0.5 } = opts;
|
|
13
|
+
for (let r = 0; r < 4000; r += 6) {
|
|
14
|
+
const a = r * 0.37, px = x + Math.cos(a) * r, pz = z + Math.sin(a) * r, h = e.surface(px, pz);
|
|
15
|
+
const dry = h > e.waterAt(px, pz) + waterMargin, walk = !e.collision || e.collision.walkableAt(px, pz);
|
|
16
|
+
if (dry && h > minH && h < maxH && e.slope(px, pz) < maxSlope && walk) return new THREE.Vector3(px, h, pz);
|
|
17
|
+
}
|
|
18
|
+
return new THREE.Vector3(x, e.surface(x, z), z);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The 'camera' player control as a value (characters.moveInput); returns the reused REQ */
|
|
22
|
+
export function moveInput(e) {
|
|
23
|
+
const inp = e.input, auto = inp.autopilot, a = auto || inp.axis; // autopilot (stress tests, recordings): input.autopilot = { x, y, speed }
|
|
24
|
+
const f = e.cameraRig ? e.cameraRig.forward() : { x: 0, z: -1 }, rt = e.cameraRig ? e.cameraRig.right() : { x: 1, z: 0 };
|
|
25
|
+
// run is the game's key, not a core default
|
|
26
|
+
REQ.x = f.x * a.y + rt.x * a.x; REQ.z = f.z * a.y + rt.z * a.x; REQ.run = inp.actions.has('run') && inp.down('run');
|
|
27
|
+
REQ.speed = auto?.speed; // autopilot can set a speed; without autopilot undefined = the character's own speed
|
|
28
|
+
return REQ;
|
|
29
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// Shared by all movers: horizontal velocity smoothing, swim check, jump buffer and coyote time, landing, facing and action state.
|
|
2
|
+
// Used by simple.js (built-in) and rapier.js (Rapier character controller), so feel parameters (acceleration, air control, jump) match.
|
|
3
|
+
import { xzOf } from '../../../core/math.js';
|
|
4
|
+
|
|
5
|
+
/** Smooth horizontal velocity toward the target velocity (c.velocity x/y map to world x/z) */
|
|
6
|
+
export function steer(c, dirX, dirZ, run, dt, speedOverride) {
|
|
7
|
+
// push() overrides the requested direction for its duration (knockback, dodge displacement)
|
|
8
|
+
if (c._push > 0) { c._push -= dt; c.velocity.set(c._pushX, c._pushZ); return; }
|
|
9
|
+
const len = Math.hypot(dirX, dirZ);
|
|
10
|
+
let speed = speedOverride ?? (run ? c.runSpeed : c.speed);
|
|
11
|
+
if (c.swimming) speed *= c.swimSpeedFactor;
|
|
12
|
+
const tvx = len > 0.01 ? dirX * speed : 0, tvz = len > 0.01 ? dirZ * speed : 0;
|
|
13
|
+
const k = 1 - Math.exp(-dt * c.acceleration * (c.grounded || c.swimming ? 1 : c.airControl));
|
|
14
|
+
c.velocity.x += (tvx - c.velocity.x) * k; c.velocity.y += (tvz - c.velocity.y) * k;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Water: decide whether swimming (sets c.swimming); a non-swimmer is put back at (ox, oz). Returns { ground: ground height under the feet, swimY: body height when swimming } */
|
|
18
|
+
export function water(c, ox, oz) {
|
|
19
|
+
const e = c.engine, p = c.root.position;
|
|
20
|
+
let ground = e.surface(p.x, p.z, p.y); // pass the current height: walk the ground under a bridge, the deck on top
|
|
21
|
+
const swimY = e.waterAt(p.x, p.z) - c.swimDepth;
|
|
22
|
+
if (!c.canSwim && ground < swimY) { p.x = ox; p.z = oz; c.velocity.set(0, 0); ground = e.surface(ox, oz, p.y); } // cannot swim: no deep water
|
|
23
|
+
c.swimming = c.canSwim && ground < swimY && p.y <= swimY + 0.3;
|
|
24
|
+
return { ground, swimY };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Float on the water surface when swimming (gentle bob) */
|
|
28
|
+
export function float(c, swimY) { c.vy = 0; c.grounded = false; c.root.position.y = swimY + Math.sin(c.engine.elapsed * 2) * 0.05; }
|
|
29
|
+
|
|
30
|
+
/** Jump if requested and on the ground (or within coyote time after walking off an edge) */
|
|
31
|
+
export function tryJump(c) {
|
|
32
|
+
if (c._jumpBuffer > 0 && (c.grounded || c._coyote > 0)) {
|
|
33
|
+
c.vy = c.jumpSpeed; c.grounded = false; c._jumpBuffer = 0; c._coyote = 0;
|
|
34
|
+
c.engine.events.emit('character:jump', { character: c });
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Landing: impact is the landing speed */
|
|
39
|
+
export function land(c, impact) {
|
|
40
|
+
c.vy = 0; c.grounded = true;
|
|
41
|
+
c.onLand?.(impact); c.engine.events.emit('character:land', { character: c, impact });
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Angle the character wants to face by its faceMode; null = keep the current facing. While pushed it never turns (a knockback must not spin it round) */
|
|
45
|
+
function faceAngle(c, sp) {
|
|
46
|
+
if (c._push > 0 || c.faceMode === 'manual') return null;
|
|
47
|
+
if (c.faceMode === 'camera') { const f = c.engine.cameraRig?.forward(); if (f) return Math.atan2(f.x, f.z); }
|
|
48
|
+
else if (c.faceMode === 'target' && c.faceTarget) { const [x, z] = xzOf(c.faceTarget), p = c.root.position; return Math.atan2(x - p.x, z - p.z); }
|
|
49
|
+
return sp > 0.3 ? Math.atan2(c.velocity.x, c.velocity.y) : null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Turn by faceMode (default: toward the move direction), update moveAmount and action state */
|
|
53
|
+
export function finish(c, dt) {
|
|
54
|
+
const sp = c.velocity.length(), want = faceAngle(c, sp);
|
|
55
|
+
if (want != null) {
|
|
56
|
+
let d = want - c.facing; d = Math.atan2(Math.sin(d), Math.cos(d));
|
|
57
|
+
c.facing += d * Math.min(1, dt * c.turnSpeed);
|
|
58
|
+
c.root.rotation.y = c.facing;
|
|
59
|
+
}
|
|
60
|
+
c.moveAmount = sp;
|
|
61
|
+
c.state = c.swimming ? 'swim' : !c.grounded ? (c.vy > 0 ? 'jump' : 'fall') : sp > c.speed * 1.3 ? 'run' : sp > 0.4 ? 'walk' : 'idle';
|
|
62
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// Rapier character-controller mover (mover: 'rapier', needs the rigid module): real collision shapes, auto step-up, slope snapping.
|
|
2
|
+
// Feel parameters (speed, acceleration, jump, air control, swimming) match simple; while physics is not ready or the collision under the feet is not built, simple is used temporarily.
|
|
3
|
+
// Native objects: mover.controller (KinematicCharacterController), mover.body, mover.collider.
|
|
4
|
+
// The player uses rigid.playerBody / playerCollider (rigid syncs it to the player position each step); each NPC builds its own kinematic capsule.
|
|
5
|
+
import { steer, water, float, tryJump, land, finish } from './common.js';
|
|
6
|
+
|
|
7
|
+
/** Create the 'rapier' mover (c is the character, fallback is the simple mover used when not ready) */
|
|
8
|
+
export function rapierMover(c, fallback) {
|
|
9
|
+
const m = {
|
|
10
|
+
name: 'rapier', controller: null, body: null, collider: null,
|
|
11
|
+
move(dirX, dirZ, run, dt, speedOverride) {
|
|
12
|
+
const e = c.engine, r = e.rigid, p = c.root.position;
|
|
13
|
+
if (!r?.ready || !r.groundReady(p)) return fallback.move(dirX, dirZ, run, dt, speedOverride);
|
|
14
|
+
if (!m.controller) setup(e, r);
|
|
15
|
+
const col = m.collider, body = m.body.translation();
|
|
16
|
+
// teleported (placeAt, load, leaving a vehicle): first move the collider to the current position
|
|
17
|
+
if (Math.abs(body.x - p.x) + Math.abs(body.y - p.y) + Math.abs(body.z - p.z) > 0.3) {
|
|
18
|
+
m.body.setTranslation({ x: p.x, y: p.y, z: p.z }, true); r.world.propagateModifiedBodyPositionsToColliders();
|
|
19
|
+
}
|
|
20
|
+
steer(c, dirX, dirZ, run, dt, speedOverride);
|
|
21
|
+
const ox = p.x, oz = p.z;
|
|
22
|
+
|
|
23
|
+
// vertical intent: float to the surface when swimming, otherwise gravity + jump
|
|
24
|
+
c._jumpBuffer -= dt; c._coyote -= dt;
|
|
25
|
+
let dy;
|
|
26
|
+
if (c.swimming) dy = e.waterAt(p.x, p.z) - c.swimDepth - p.y;
|
|
27
|
+
else {
|
|
28
|
+
tryJump(c);
|
|
29
|
+
if (c.grounded && c.vy <= 0) { c.vy = 0; dy = 0; } // do not press down while standing (it would break auto step-up); downhill relies on ground snapping
|
|
30
|
+
else { c.vy += c.gravity * dt; dy = c.vy * dt; }
|
|
31
|
+
}
|
|
32
|
+
const wasGrounded = c.grounded;
|
|
33
|
+
m.controller.computeColliderMovement(col, { x: c.velocity.x * dt, y: dy, z: c.velocity.y * dt }, r.R.QueryFilterFlags.EXCLUDE_DYNAMIC | r.R.QueryFilterFlags.EXCLUDE_SENSORS);
|
|
34
|
+
const mv = m.controller.computedMovement();
|
|
35
|
+
p.x += mv.x; p.y += mv.y; p.z += mv.z;
|
|
36
|
+
// hit a wall (not stepping up): velocity becomes the wall-sliding velocity, so standing at a wall does not keep walking
|
|
37
|
+
const want = Math.hypot(c.velocity.x, c.velocity.y) * dt, got = Math.hypot(mv.x, mv.z);
|
|
38
|
+
if (wasGrounded && mv.y <= 1e-3 && got < want * 0.5) c.velocity.set(mv.x / dt, mv.z / dt);
|
|
39
|
+
const grounded = m.controller.computedGrounded();
|
|
40
|
+
if (c.vy > 0 && mv.y < dy * 0.5) c.vy = 0; // hit the ceiling
|
|
41
|
+
|
|
42
|
+
const { swimY } = water(c, ox, oz);
|
|
43
|
+
if (c.swimming) float(c, swimY);
|
|
44
|
+
else if (grounded && !wasGrounded && c.vy <= 0) land(c, -c.vy);
|
|
45
|
+
else if (!grounded && wasGrounded && c.vy <= 0) { c.grounded = false; c._coyote = c.coyoteTime; } // walked off an edge
|
|
46
|
+
else c.grounded = grounded;
|
|
47
|
+
if (m.body !== r.playerBody) m.body.setNextKinematicTranslation({ x: p.x, y: p.y, z: p.z });
|
|
48
|
+
finish(c, dt);
|
|
49
|
+
},
|
|
50
|
+
/** Called when the character is deleted: release the NPC's own capsule and controller */
|
|
51
|
+
dispose() {
|
|
52
|
+
const r = c.engine.rigid;
|
|
53
|
+
if (!m.controller) return;
|
|
54
|
+
r.world.removeCharacterController(m.controller);
|
|
55
|
+
if (m.body !== r.playerBody) r.world.removeRigidBody(m.body);
|
|
56
|
+
m.controller = m.body = m.collider = null;
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
function setup(e, r) {
|
|
61
|
+
const R = r.R, w = r.world, p = c.root.position;
|
|
62
|
+
if (c === e.player) { m.body = r.playerBody; m.collider = r.playerCollider; }
|
|
63
|
+
else {
|
|
64
|
+
const hh = r.playerCapsule.halfHeight;
|
|
65
|
+
m.body = w.createRigidBody(R.RigidBodyDesc.kinematicPositionBased().setTranslation(p.x, p.y, p.z));
|
|
66
|
+
m.collider = w.createCollider(R.ColliderDesc.capsule(hh, c.radius).setTranslation(0, hh + c.radius, 0), m.body);
|
|
67
|
+
}
|
|
68
|
+
const k = m.controller = w.createCharacterController(0.02);
|
|
69
|
+
k.enableAutostep(c.stepHeight, 0.15, false);
|
|
70
|
+
k.setMaxSlopeClimbAngle(Math.atan(e.collision?.maxClimb ?? e.movement.slopeRatio));
|
|
71
|
+
k.enableSnapToGround(c.stepHeight);
|
|
72
|
+
}
|
|
73
|
+
return m;
|
|
74
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// Built-in mover (default): snap to ground height, step up within step height, back off slopes that are too steep, light collision push-out, swimming, jumping.
|
|
2
|
+
// Needs no physics engine, cheap on large maps.
|
|
3
|
+
import { steer, water, float, tryJump, land, finish } from './common.js';
|
|
4
|
+
|
|
5
|
+
/** Create the 'simple' mover (c is the character) */
|
|
6
|
+
export function simpleMover(c) {
|
|
7
|
+
return {
|
|
8
|
+
name: 'simple',
|
|
9
|
+
move(dirX, dirZ, run, dt, speedOverride) {
|
|
10
|
+
const e = c.engine, p = c.root.position;
|
|
11
|
+
steer(c, dirX, dirZ, run, dt, speedOverride);
|
|
12
|
+
|
|
13
|
+
const ox = p.x, oz = p.z, oh = e.surface(ox, oz, p.y);
|
|
14
|
+
p.x += c.velocity.x * dt; p.z += c.velocity.y * dt;
|
|
15
|
+
// back to the old position where it cannot climb: step up directly within step height; above that check the slope; hitting ground higher than itself in the air counts as a wall
|
|
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
|
+
const blocked = c.grounded ? (rise > c.stepHeight && step > 1e-4 && (nh - oh) / step > maxClimb) : nh > p.y + c.stepHeight;
|
|
18
|
+
if (blocked) { p.x = ox; p.z = oz; c.velocity.set(0, 0); }
|
|
19
|
+
e.collision?.resolve(p, c.radius);
|
|
20
|
+
|
|
21
|
+
const { ground, swimY } = water(c, ox, oz);
|
|
22
|
+
|
|
23
|
+
// vertical: gravity, jump, walking off an edge, landing
|
|
24
|
+
c._jumpBuffer -= dt; c._coyote -= dt;
|
|
25
|
+
if (c.swimming) float(c, swimY);
|
|
26
|
+
else {
|
|
27
|
+
if (c.grounded && ground < p.y - c.stepHeight) { c.grounded = false; c._coyote = c.coyoteTime; } // walked off an edge
|
|
28
|
+
tryJump(c);
|
|
29
|
+
if (c.grounded) { p.y = ground; c.vy = 0; }
|
|
30
|
+
else {
|
|
31
|
+
c.vy += c.gravity * dt; p.y += c.vy * dt;
|
|
32
|
+
if (p.y <= ground) { const impact = -c.vy; p.y = ground; land(c, impact); }
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
finish(c, dt);
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// NPC-vs-NPC avoidance (near NPCs, every fixed step, called from goTo): nearby NPCs push each other apart to at least the sum of their radii; the player is an
|
|
2
|
+
// obstacle (NPCs yield, the player is never pushed).
|
|
3
|
+
// Why it is written this way: a continuous run and a save-then-load of the same scenario must give bit-identical positions:
|
|
4
|
+
// 1. Each NPC pushes only itself and reads neighbours' positions as of the start of this step (stamped), so a neighbour that already moved this step does not
|
|
5
|
+
// matter and order is irrelevant;
|
|
6
|
+
// 2. Neighbour pushes are rounded before summing (neighbour iteration order changes after load; float addition order would differ in the last bit, integer
|
|
7
|
+
// addition does not);
|
|
8
|
+
// 3. No randomness, no state kept in data (start is a per-step scratch value, cleared on load).
|
|
9
|
+
// Push is capped (strength m/s * dt), stronger with more overlap, then constrained by engine.collision (if installed) so NPCs are not pushed into walls.
|
|
10
|
+
// With nav({ crowd: true }) the Recast agents decide and this adds nothing. Only near NPCs with a model; far NPCs are simulated from data without per-NPC
|
|
11
|
+
// avoidance (too costly).
|
|
12
|
+
import { checkOptions } from '../../core/validate.js';
|
|
13
|
+
|
|
14
|
+
const KEYS = ['on', 'radius', 'strength'];
|
|
15
|
+
// push direction is rotated ~25° to the right: two NPCs meeting head-on each swerve to their own right instead of deadlocking in a line
|
|
16
|
+
const COS = 0.906, SIN = 0.423;
|
|
17
|
+
const Q = 1048576; // rounding scale before summing (2^20)
|
|
18
|
+
|
|
19
|
+
const cellKey = (x, z) => (x + 1048576) * 2097152 + z + 1048576;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Push from one neighbour (offset (dx, dz) from me, distance d, wanted separation min), rounded and added to acc; exactly overlapping picks the direction by
|
|
23
|
+
* tie (±1)
|
|
24
|
+
*/
|
|
25
|
+
function shove(acc, dx, dz, d, min, tie) {
|
|
26
|
+
// more overlap pushes harder, a light touch pushes gently: smooth
|
|
27
|
+
const w = Math.min(1, (min - d) / (0.5 * min)), ux = d > 1e-6 ? dx / d : tie, uz = d > 1e-6 ? dz / d : 0;
|
|
28
|
+
acc.x += Math.round((ux * COS - uz * SIN) * w * Q); acc.z += Math.round((ux * SIN + uz * COS) * w * Q);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** @internal @internal Mounted on engine.npcs: engine.npcs.avoid = false | { radius, strength } */
|
|
32
|
+
export class NpcAvoid {
|
|
33
|
+
constructor(engine) {
|
|
34
|
+
this.engine = engine;
|
|
35
|
+
this.on = true; // switch (default on)
|
|
36
|
+
this.radius = null; // avoid radius per NPC (m); null = engine.movement.radius
|
|
37
|
+
this.strength = 3; // max push speed (m/s)
|
|
38
|
+
this._acc = { x: 0, z: 0 };
|
|
39
|
+
/** @internal ids of NPCs that have a model now (NPCManager keeps it): only they take part, so far NPCs cost nothing per step */ this.built = new Set();
|
|
40
|
+
this._ids = [];
|
|
41
|
+
this._start = new Map(); // id → { k: simulation step count, x, z }: position at the start of this step
|
|
42
|
+
// fine grid index for this step (cell size = min distance of two NPCs, query 3x3 cells): the world grid is 32 m per cell, so hundreds of NPCs in one or two
|
|
43
|
+
// cells would make per-pair distance checks too costly
|
|
44
|
+
this._gridN = -1; this._head = new Map(); this._next = new Int32Array(64); this._items = []; this._gx = new Float64Array(64); this._gz = new Float64Array(64);
|
|
45
|
+
engine.events.on('world:remove', ({ id }) => this._start.delete(id));
|
|
46
|
+
// after load the simulation step count returns to the saved value, so the old grid is stale
|
|
47
|
+
engine.events.on('world:load', () => { this._start.clear(); this._gridN = -1; });
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Change settings: set(false) off, set(true) on, set({ radius, strength }) tune (pass only what changes; passing it means on). Read current values from on /
|
|
52
|
+
* radius / strength.
|
|
53
|
+
* @example engine.npcs.avoid.set({ radius: 0.6, strength: 2 }); // a bit sparser, pushed more slowly
|
|
54
|
+
* @param {boolean | { on?: boolean, radius?: number | null, strength?: number }} opts radius per-NPC avoid radius (m, null = engine.movement.radius),
|
|
55
|
+
* strength max push speed (m/s, default 3)
|
|
56
|
+
* @returns {this}
|
|
57
|
+
*/
|
|
58
|
+
set(opts) {
|
|
59
|
+
this._gridN = -1;
|
|
60
|
+
if (typeof opts === 'boolean') { this.on = opts; return this; }
|
|
61
|
+
checkOptions('engine.npcs.avoid.set()', opts, KEYS);
|
|
62
|
+
this.on = opts.on ?? true;
|
|
63
|
+
if (opts.radius !== undefined) this.radius = opts.radius;
|
|
64
|
+
if (opts.strength !== undefined) this.strength = opts.strength;
|
|
65
|
+
return this;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** This NPC's simulation step starts: record the start position (called from the near entry in NPC.js, before behaviours change the position) */
|
|
69
|
+
stamp(rec) {
|
|
70
|
+
if (!this.on) return;
|
|
71
|
+
const n = this.engine.world.steps, p = rec.position;
|
|
72
|
+
let s = this._start.get(rec.id);
|
|
73
|
+
if (!s) this._start.set(rec.id, s = { k: n, x: p.x, z: p.z });
|
|
74
|
+
else { s.k = n; s.x = p.x; s.z = p.z; }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* On the first avoid of this step, put model-bearing NPCs into the fine grid by their step-start positions (each NPC then queries only the surrounding 3x3
|
|
79
|
+
* cells)
|
|
80
|
+
*/
|
|
81
|
+
_build(W, n, min) {
|
|
82
|
+
const head = this._head, items = this._items, ids = this._ids;
|
|
83
|
+
ids.length = 0; for (const id of this.built) ids.push(id);
|
|
84
|
+
ids.sort(); // by id: model build order depends on frames, the push order must not
|
|
85
|
+
items.length = 0;
|
|
86
|
+
for (const id of ids) { const o = W.get(id); if (o && W.view(id)) items.push(o); }
|
|
87
|
+
head.clear(); this._gridN = n;
|
|
88
|
+
if (items.length > this._next.length) { this._next = new Int32Array(items.length * 2); this._gx = new Float64Array(items.length * 2); this._gz = new Float64Array(items.length * 2); }
|
|
89
|
+
for (let i = 0; i < items.length; i++) {
|
|
90
|
+
const o = items[i], s = this._start.get(o.id), q = s && s.k === n ? s : o.position, c = cellKey(Math.floor(q.x / min), Math.floor(q.z / min));
|
|
91
|
+
this._gx[i] = q.x; this._gz[i] = q.z;
|
|
92
|
+
this._next[i] = head.get(c) ?? -1; head.set(c, i);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Push ch (the rec's model) apart; call after ch.move, edits ch.root.position x, z directly */
|
|
97
|
+
push(rec, ch, dt) {
|
|
98
|
+
const e = this.engine, W = e.world;
|
|
99
|
+
if (!this.on || e.nav?.crowd) return;
|
|
100
|
+
const n = W.steps, own = this._start.get(rec.id), r = this.radius ?? e.movement.radius, min = 2 * r;
|
|
101
|
+
if (!own || own.k !== n) return; // did not enter via NPC.js (goTo called directly): no avoidance
|
|
102
|
+
if (this._gridN !== n) this._build(W, n, min);
|
|
103
|
+
const head = this._head, nx = this._next, items = this._items, gx = this._gx, gz = this._gz, min2 = min * min;
|
|
104
|
+
// accumulate integers: float addition depends on order and neighbour order changes after load; rounded integer addition is exact and order-independent
|
|
105
|
+
const acc = this._acc; acc.x = acc.z = 0;
|
|
106
|
+
const cx = Math.floor(own.x / min), cz = Math.floor(own.z / min);
|
|
107
|
+
for (let x = cx - 1; x <= cx + 1; x++) for (let z = cz - 1; z <= cz + 1; z++) {
|
|
108
|
+
for (let i = head.get(cellKey(x, z)) ?? -1; i >= 0; i = nx[i]) {
|
|
109
|
+
const o = items[i], dx = own.x - gx[i], dz = own.z - gz[i], d2 = dx * dx + dz * dz;
|
|
110
|
+
if (o === rec || d2 >= min2 || (o.zone != null && rec.zone != null && o.zone !== rec.zone)) continue;
|
|
111
|
+
shove(acc, dx, dz, Math.sqrt(d2), min, rec.id < o.id ? 1 : -1);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
const pl = e.player;
|
|
115
|
+
if (pl?.root) { // the player is an obstacle: only the NPC yields, the player position belongs to the mover
|
|
116
|
+
const q = pl.root.position, m = r + (pl.radius ?? r), dx = own.x - q.x, dz = own.z - q.z, d = Math.hypot(dx, dz);
|
|
117
|
+
if (d < m) shove(acc, dx, dz, d, m, 1);
|
|
118
|
+
}
|
|
119
|
+
const ax = acc.x / Q, az = acc.z / Q;
|
|
120
|
+
const len = Math.sqrt(ax * ax + az * az);
|
|
121
|
+
if (!len) return;
|
|
122
|
+
const k = this.strength * dt / Math.max(1, len), p = ch.root.position;
|
|
123
|
+
const mx = ax * k, mz = az * k;
|
|
124
|
+
p.x += mx; p.z += mz;
|
|
125
|
+
// skip collision for pushes under half a centimetre (the mover keeps it out of walls next step); in a crowd every NPC is nudged every step, so this saves
|
|
126
|
+
// most collision queries
|
|
127
|
+
if (mx * mx + mz * mz > 2.5e-5) e.collision?.resolve(p, ch.radius);
|
|
128
|
+
}
|
|
129
|
+
}
|