threedog 0.0.0-stage → 0.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 +5 -0
- package/LICENSE +21 -0
- package/README.md +39 -2
- package/core/Animator.js +268 -0
- package/core/Assets.js +256 -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/DebugOverrides.js +143 -0
- package/core/Describe.js +145 -0
- package/core/Engine.js +184 -0
- package/core/Events.js +153 -0
- package/core/I18n.js +94 -0
- package/core/Input.js +245 -0
- package/core/Inspect.js +77 -0
- package/core/InspectScene.js +191 -0
- package/core/Jobs.js +146 -0
- package/core/Loading.js +149 -0
- package/core/MaterialInfo.js +32 -0
- package/core/Ops.js +256 -0
- package/core/Random.js +52 -0
- package/core/Rays.js +160 -0
- package/core/SaveStore.js +85 -0
- package/core/Saves.js +254 -0
- package/core/Stream.js +279 -0
- package/core/Threads.js +158 -0
- package/core/UrlState.js +94 -0
- package/core/Vars.js +35 -0
- package/core/Views.js +49 -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/assetReport.js +83 -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/catalog.js +169 -0
- package/core/checks.js +67 -0
- package/core/claims.js +51 -0
- package/core/dayTime.js +15 -0
- package/core/debugView.js +76 -0
- package/core/describeRender.js +45 -0
- package/core/describeText.js +143 -0
- package/core/easing.js +34 -0
- package/core/errorCodes.js +205 -0
- package/core/errorHints.js +208 -0
- package/core/errors.js +40 -0
- package/core/events.generated.js +84 -0
- package/core/ground.js +102 -0
- package/core/holds.js +106 -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 +69 -0
- package/core/lightWatch.js +56 -0
- package/core/look/coreParts.js +112 -0
- package/core/look/layers.js +136 -0
- package/core/look/part.js +173 -0
- package/core/look/report.js +79 -0
- package/core/look/write.js +86 -0
- package/core/loop.js +200 -0
- package/core/math.js +33 -0
- package/core/modules.js +196 -0
- package/core/movement.js +19 -0
- package/core/mulberry32.js +14 -0
- package/core/opsAtomic.js +31 -0
- package/core/opsCheck.js +97 -0
- package/core/opsFail.js +20 -0
- package/core/opsGuard.js +26 -0
- package/core/opsHistory.js +27 -0
- package/core/opsRun.js +77 -0
- package/core/page.js +78 -0
- package/core/params.js +132 -0
- package/core/pureWorker.js +5 -0
- package/core/renamed.js +21 -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 +100 -0
- package/core/screenToGround.js +39 -0
- package/core/services.js +73 -0
- package/core/session.js +171 -0
- package/core/shadowTypes.js +15 -0
- package/core/skip.js +104 -0
- package/core/startup.js +135 -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/thingExplain.js +68 -0
- package/core/thingOps.js +168 -0
- package/core/things.js +212 -0
- package/core/threadPure.js +120 -0
- package/core/threadServe.js +25 -0
- package/core/tier.js +11 -0
- package/core/util.js +11 -0
- package/core/validate.js +204 -0
- package/docs/AI.md +123 -0
- package/docs/API.md +83 -0
- package/docs/CODEMAP.md +347 -0
- package/docs/COMMANDS.md +108 -0
- package/docs/CONVENTIONS.md +145 -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 +62 -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 +144 -0
- package/docs/api/clock.md +7 -0
- package/docs/api/collision.md +39 -0
- package/docs/api/content.md +64 -0
- package/docs/api/dialogue.md +39 -0
- package/docs/api/engine.md +199 -0
- package/docs/api/entities.md +61 -0
- package/docs/api/events.md +95 -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 +10 -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 +32 -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 +57 -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 +167 -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 +117 -0
- package/docs/recipes/07-flow-scenes-pause.md +132 -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 +79 -0
- package/docs/recipes/13-animation.md +149 -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 +180 -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 +153 -0
- package/docs/recipes/22-shop-gold.md +107 -0
- package/docs/recipes/23-ops.md +175 -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 +36 -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 +83 -0
- package/docs/recipes/40-scene.md +108 -0
- package/docs/recipes/41-thing-registry.md +93 -0
- package/docs/recipes/42-terrain-shape.md +64 -0
- package/docs/recipes/43-shader-patches-surface-looks.md +120 -0
- package/docs/recipes/44-water-weather-look-hooks.md +135 -0
- package/docs/recipes/45-cascaded-shadows.md +51 -0
- package/docs/recipes/46-blender-art-route.md +114 -0
- package/docs/recipes/47-island-snow-backdrop.md +44 -0
- package/docs/recipes/48-make-material.md +70 -0
- package/docs/recipes/49-game-module-contract.md +71 -0
- package/docs/recipes/50-own-renderer.md +12 -0
- package/docs/recipes/51-capability-catalog.md +63 -0
- package/docs/recipes/52-look.md +108 -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 +10 -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/content/views.js +6 -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 +107 -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 +306 -0
- package/index.js +122 -0
- package/llms.txt +61 -0
- package/modules/ambience/Ambience.js +186 -0
- package/modules/camera/FirstPersonCamera.js +131 -0
- package/modules/camera/FixedCamera.js +162 -0
- package/modules/camera/FollowCamera.js +91 -0
- package/modules/camera/RtsCamera.js +132 -0
- package/modules/camera/common.js +182 -0
- package/modules/camera/index.js +11 -0
- package/modules/camera/projection.js +34 -0
- package/modules/characters/Character.js +235 -0
- package/modules/characters/NPC.js +242 -0
- package/modules/characters/assetModel.js +42 -0
- package/modules/characters/astar.js +66 -0
- package/modules/characters/behaviors.js +72 -0
- package/modules/characters/footsteps.js +13 -0
- package/modules/characters/index.js +215 -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 +43 -0
- package/modules/characters/npcAvoid.js +129 -0
- package/modules/characters/npcSim.js +150 -0
- package/modules/characters/npcView.js +42 -0
- package/modules/characters/pathAsync.js +113 -0
- package/modules/characters/pathJob.js +62 -0
- package/modules/characters/pathWorker.js +7 -0
- package/modules/characters/playerStrings.js +12 -0
- package/modules/characters/proceduralRig.js +58 -0
- package/modules/characters/useModel.js +22 -0
- package/modules/characters/walkTo.js +58 -0
- package/modules/collision/Collision.js +274 -0
- package/modules/collision/grid.js +63 -0
- package/modules/content/explain.js +13 -0
- package/modules/content/ids.js +95 -0
- package/modules/content/index.js +154 -0
- package/modules/content/loader.js +190 -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 +134 -0
- package/modules/content/templates.js +189 -0
- package/modules/debug/DebugPanel.js +174 -0
- package/modules/entities/Entities.js +243 -0
- package/modules/entities/build.js +25 -0
- package/modules/entities/index.js +4 -0
- package/modules/flow/index.js +101 -0
- package/modules/gameplay/Container.js +227 -0
- package/modules/gameplay/Containers.js +89 -0
- package/modules/gameplay/Dialogue.js +219 -0
- package/modules/gameplay/Interactions.js +253 -0
- package/modules/gameplay/Inventory.js +224 -0
- package/modules/gameplay/Quests.js +205 -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 +115 -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 +79 -0
- package/modules/hlod/index.js +167 -0
- package/modules/hud/index.js +167 -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 +233 -0
- package/modules/level/nodes.js +84 -0
- package/modules/lights/index.js +227 -0
- package/modules/music/Music.js +294 -0
- package/modules/music/index.js +2 -0
- package/modules/music/rules.js +28 -0
- package/modules/nav/index.js +156 -0
- package/modules/nav/navPath.js +17 -0
- package/modules/net/Client.js +137 -0
- package/modules/net/Host.js +117 -0
- package/modules/net/Net.js +49 -0
- package/modules/net/index.js +77 -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 +146 -0
- package/modules/rigid/RigidBodies.js +265 -0
- package/modules/rigid/Vehicles.js +97 -0
- package/modules/rigid/sync.js +158 -0
- package/modules/settings/Settings.js +297 -0
- package/modules/settings/apply.js +21 -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 +259 -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 +141 -0
- package/modules/sky/fog.js +139 -0
- package/modules/sky/frame.js +77 -0
- package/modules/sky/layers.js +69 -0
- package/modules/sky/look.js +51 -0
- package/modules/sky/lookFog.js +80 -0
- package/modules/sky/lookShadow.js +50 -0
- package/modules/sky/lookSky.js +108 -0
- package/modules/sky/schedule.js +80 -0
- package/modules/sky/shader.js +96 -0
- package/modules/sky/shadow.js +74 -0
- package/modules/sky/skyModule.js +60 -0
- package/modules/terrain/ChunkManager.js +260 -0
- package/modules/terrain/chunkJob.js +19 -0
- package/modules/terrain/chunkLevels.js +40 -0
- package/modules/terrain/chunkQueries.js +42 -0
- package/modules/terrain/chunkWorker.js +5 -0
- package/modules/terrain/index.js +118 -0
- package/modules/terrain/lookGround.js +61 -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 +253 -0
- package/modules/timeline/Tween.js +114 -0
- package/modules/timeline/letterbox.js +24 -0
- package/modules/timeline/shots.js +90 -0
- package/modules/triggers/index.js +268 -0
- package/modules/vegetation/Vegetation.js +256 -0
- package/modules/vegetation/groundChunks.js +177 -0
- package/modules/vegetation/index.js +43 -0
- package/modules/vegetation/lookWind.js +37 -0
- package/modules/vegetation/modelGeometry.js +21 -0
- package/modules/water/Water.js +160 -0
- package/modules/water/look.js +80 -0
- package/modules/water/surface.js +88 -0
- package/modules/weather/Weather.js +242 -0
- package/modules/weather/look.js +75 -0
- package/modules/weather/particles.js +92 -0
- package/modules/weather/shaders.js +49 -0
- package/modules/weather/strings.js +15 -0
- package/modules/world/World.js +231 -0
- package/modules/world/cells.js +42 -0
- package/modules/world/explain.js +11 -0
- package/modules/world/index.js +71 -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/thingSource.js +44 -0
- package/modules/world/views.js +182 -0
- package/package.json +66 -4
- package/presets.js +96 -0
- package/render/PostFX.js +240 -0
- package/render/detail.js +105 -0
- package/render/effects.js +144 -0
- package/render/engineUniforms.js +23 -0
- package/render/fuse.js +84 -0
- package/render/lighting.js +100 -0
- package/render/lights.js +18 -0
- package/render/lookSurface.js +161 -0
- package/render/materials.js +220 -0
- package/render/patches.js +252 -0
- package/render/postLook.js +86 -0
- package/render/surface.js +69 -0
- package/render/uniformDecl.js +29 -0
- package/types/common.d.ts +34 -0
- package/types/core.d.ts +1965 -0
- package/types/gameplay.d.ts +1822 -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/DebugOverrides.d.ts +52 -0
- package/types/generated/core/Events.d.ts +89 -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 +203 -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 +162 -0
- package/types/generated/core/Stream.d.ts +93 -0
- package/types/generated/core/Threads.d.ts +82 -0
- package/types/generated/core/Views.d.ts +33 -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 +65 -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 +145 -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 +62 -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 +125 -0
- package/types/generated/render/materials.d.ts +100 -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 +592 -0
- package/types/style.d.ts +638 -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 +199 -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,243 @@
|
|
|
1
|
+
// Entities: the few stateful, changing, interactive, saved objects in a game - planted saplings, campfires, chests, traps, placed furniture.
|
|
2
|
+
// Unlike vegetation (thousands of seed-derived instances, never saved individually), each entity is its own object (tens to hundreds).
|
|
3
|
+
//
|
|
4
|
+
// engine.use(entities()); // needs the world module (included by openWorld)
|
|
5
|
+
// engine.entities.define('sapling', {
|
|
6
|
+
// create: (engine, data) => makeSaplingMesh(), // returns a THREE.Object3D (the model comes from the game / style pack)
|
|
7
|
+
// state: { watered: false }, // default state (merged with data.state at spawn)
|
|
8
|
+
// stages: [ // optional: growth stages (seed -> sapling -> tree)
|
|
9
|
+
// { name: 'seed', duration: 60, scale: 0.2 }, // duration: game seconds spent in this stage
|
|
10
|
+
// { name: 'sapling', duration: 120, scale: 0.5 },
|
|
11
|
+
// { name: 'tree', model: (engine, ent) => makeTree() }, // no duration on the last stage = stays there forever; model swaps the model
|
|
12
|
+
// ],
|
|
13
|
+
// update(dt, ent, engine) {}, // optional: per fixed step (runs only near the player; far entities just catch up on growth)
|
|
14
|
+
// interact: { label: 'entities.water', action: 'interact', radius: 2.5, enabled: ent => true, onUse: ent => ent.set('watered', true) },
|
|
15
|
+
// collider: 0.4, // optional: circular collision radius (needs the collision module; built with the model, so near only)
|
|
16
|
+
// save: false, // optional: exclude from saves (temporary things, cleared on load); default true
|
|
17
|
+
// });
|
|
18
|
+
// const ent = engine.entities.spawn('sapling', { position: [10, 0, 5], rotation: 0 }); // position as { x, z } (no y) snaps to ground
|
|
19
|
+
// ent.object // three.js root (Group) with the model ent.visual under it; exists only when near, null when far. Built the frame after spawn; call
|
|
20
|
+
// engine.world.refresh() to get it immediately.
|
|
21
|
+
// ent.state.stage // current stage index; ent.stageName // 'seed'
|
|
22
|
+
// ent.set('watered', true); ent.remove();
|
|
23
|
+
// engine.entities.get(ent.id); engine.entities.byType('sapling'); engine.entities.remove(id); // ids without spawn({ id }) look like 'entity:sapling-3'
|
|
24
|
+
// engine.entities.nearest(position, { radius, type }) // nearest entity
|
|
25
|
+
//
|
|
26
|
+
// Data and presentation are separate (see modules/world): an entity's facts (position, rotation, state, extra, stage) are a plain record in engine.world,
|
|
27
|
+
// with kind 'entity:<type>' (one kind per type, usable by world.query / present / simulate); the id is the entity id; saved with world.
|
|
28
|
+
// Model, interaction and collision are built only near the player (world.radius, default 60 m) and torn down when far (def.dispose is called then); rebuilt for
|
|
29
|
+
// the current stage on return.
|
|
30
|
+
// ent is a wrapper "view": x / y / z / rotation / state / data read world data by id (still valid after a load swaps the data); ent.object / ent.visual exist
|
|
31
|
+
// only when near.
|
|
32
|
+
// Changing state: ent.set, setStage and stage changes go through world.set (emits world:change, see world's mutation rules); fields changed every step in
|
|
33
|
+
// update can be written to ent.state directly and are still saved.
|
|
34
|
+
// Growth and update are world.simulate: every fixed step when near, caught up in game seconds when far (grows without a model, may cross several stages at
|
|
35
|
+
// once; canGrow is asked both near and far).
|
|
36
|
+
//
|
|
37
|
+
// Events: entity:spawn / entity:remove / entity:state { ent, key, value, prev } / entity:stage { ent, stage, name }
|
|
38
|
+
// Clock: growth uses engine.clock.now (game seconds, follows clock.timeScale and saves).
|
|
39
|
+
// Interaction text: interact.label may be an i18n key (translated if it exists), plain text, or a function ent => text.
|
|
40
|
+
// Appearance: the engine ships no default models - the game supplies create(), usually from an asset pack (engine.assets.model / cached).
|
|
41
|
+
import { xzOf } from '../../core/math.js';
|
|
42
|
+
import { checkOptions, checkOptionsArg, missingText, warnOnce, freezeDef } from '../../core/validate.js';
|
|
43
|
+
import { readParams, keysSchema } from '../../core/params.js';
|
|
44
|
+
import { buildEntity } from './build.js';
|
|
45
|
+
|
|
46
|
+
const DEF_KEYS = ['create', 'state', 'stages', 'update', 'interact', 'collider', 'colliderHeight', 'save', 'dispose', 'canGrow'];
|
|
47
|
+
const SPAWN_KEYS = ['id', 'position', 'rotation', 'state', 'extra'];
|
|
48
|
+
const KIND = 'entity:'; // kind prefix of world data: one kind per type, so present / simulate can register per type
|
|
49
|
+
|
|
50
|
+
// Developer message: data uses a feature of a module that is not installed (optional dependencies must not be skipped silently, see core/modules.js)
|
|
51
|
+
const DEV_STRINGS = { noInteract: 'Entity "{id}" sets interact but the interactions() module is not installed: the entity cannot be interacted with. Install interactions().' };
|
|
52
|
+
const STRINGS = {
|
|
53
|
+
'zh-CN': { 'entities.use': '使用' },
|
|
54
|
+
en: { 'entities.use': 'Use' },
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
export class Entities {
|
|
58
|
+
constructor(engine) {
|
|
59
|
+
this.engine = engine;
|
|
60
|
+
this.types = new Map();
|
|
61
|
+
this._views = new Map(); // id -> ent view (just a shell: getters read data by id, plus presentation state while a model exists; holds no facts)
|
|
62
|
+
this._hooks = new Map(); // type -> world.present / simulate registrations; the old ones are removed on re-define
|
|
63
|
+
engine.i18n.add(STRINGS);
|
|
64
|
+
// data gone, view dropped with it (not in the save after a load, or deleted directly by world.remove)
|
|
65
|
+
engine.events.on('world:remove', ({ id }) => this._views.delete(id));
|
|
66
|
+
engine.events.on('world:load', () => { for (const id of this._views.keys()) if (!this.world.get(id)) this._views.delete(id); });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
get now() { return this.engine.clock.now; }
|
|
70
|
+
get world() { return this.engine.world; }
|
|
71
|
+
|
|
72
|
+
define(type, def) {
|
|
73
|
+
checkOptions(`entities.define('${type}')`, def, DEF_KEYS, { loose: true }); // games may add their own fields; only warn on near-miss spellings
|
|
74
|
+
for (const s of def.stages || []) checkOptions(`entities.define('${type}') stages`, s, ['name', 'duration', 'scale', 'model']);
|
|
75
|
+
checkOptions(`entities.define('${type}') interact`, def.interact, ['label', 'action', 'radius', 'height', 'enabled', 'onUse']);
|
|
76
|
+
this._hooks.get(type)?.forEach(h => h.remove());
|
|
77
|
+
const full = freezeDef({ state: {}, ...def }), kind = KIND + type, w = this.world, hooks = [];
|
|
78
|
+
this.types.set(type, full);
|
|
79
|
+
hooks.push(w.present(kind, {
|
|
80
|
+
build: rec => this._build(this._ent(rec)),
|
|
81
|
+
update: rec => this._refresh(this._ent(rec)),
|
|
82
|
+
dispose: (rec, obj) => this._unbuild(this._ent(rec), obj),
|
|
83
|
+
}));
|
|
84
|
+
if (full.stages || full.update) {
|
|
85
|
+
hooks.push(w.simulate(kind, {
|
|
86
|
+
near: (rec, dt) => { const ent = this._ent(rec); this._grow(ent); full.update?.(dt, ent, this.engine); },
|
|
87
|
+
far: rec => this._grow(this._ent(rec)), // far: only catch up on growth (in game seconds); update is near-only logic
|
|
88
|
+
}));
|
|
89
|
+
}
|
|
90
|
+
this._hooks.set(type, hooks);
|
|
91
|
+
return this;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
spawn(type, data = {}) {
|
|
95
|
+
const e = this.engine, def = this.types.get(type);
|
|
96
|
+
if (!def) { console.error(missingText('entityType', type, [...this.types.keys()])); return null; }
|
|
97
|
+
checkOptions(`entities.spawn('${type}')`, data, SPAWN_KEYS);
|
|
98
|
+
// none given: world numbers it (entity:<type>#<n>); the counter is saved with world, so a removed entity's id is never handed out again
|
|
99
|
+
const id = data.id;
|
|
100
|
+
if (id != null && this.world.get(id)) this.remove(id);
|
|
101
|
+
const pos = data.position ?? { x: 0, z: 0 }, [x, z] = xzOf(pos);
|
|
102
|
+
const y = pos.isObject3D ? pos.position.y : Array.isArray(pos) ? (pos[1] ?? null) : (pos.y ?? null); // no y given = snap to ground
|
|
103
|
+
const state = { ...structuredClone(def.state || {}), ...(data.state || {}) };
|
|
104
|
+
if (def.stages) { state.stage ??= 0; state.stageAt ??= this.now; } // stage without stageAt starts from now, otherwise NaN and it never grows
|
|
105
|
+
const rec = this.world.add({ id, kind: KIND + type, position: { x, y: y ?? e.surface(x, z), z }, rotation: data.rotation ?? 0, state, extra: data.extra || {} }, { save: def.save ?? true });
|
|
106
|
+
if (def.interact && !e.interactions) warnOnce(DEV_STRINGS.noInteract.replace('{id}', id));
|
|
107
|
+
const ent = this._ent(rec);
|
|
108
|
+
e.events.emit('entity:spawn', ent);
|
|
109
|
+
return ent;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
get(id) { const rec = this.world.get(id); return rec?.kind.startsWith(KIND) ? this._ent(rec) : null; }
|
|
113
|
+
byType(type) { return this.world.query({ kind: KIND + type }).map(r => this._ent(r)); }
|
|
114
|
+
list() { return this.world.query({ where: r => r.kind.startsWith(KIND) }).map(r => this._ent(r)); }
|
|
115
|
+
/** Nearest entity within radius meters (default 3) of position; type restricts to one type. */
|
|
116
|
+
nearest(position, opts = {}) {
|
|
117
|
+
checkOptionsArg('entities.nearest()', opts, ['radius', 'type']);
|
|
118
|
+
const [x, z] = xzOf(position), { radius = 3, type = null } = typeof opts === 'object' && opts ? opts : {};
|
|
119
|
+
const rec = this.world.query({ near: position, radius, where: r => type ? r.kind === KIND + type : r.kind.startsWith(KIND) })
|
|
120
|
+
.find(r => (r.position.x - x) ** 2 + (r.position.z - z) ** 2 < radius * radius); // query includes the boundary; keep the original strict less-than here
|
|
121
|
+
return rec ? this._ent(rec) : null;
|
|
122
|
+
}
|
|
123
|
+
remove(id) {
|
|
124
|
+
const ent = this.get(id);
|
|
125
|
+
if (!ent) return false;
|
|
126
|
+
this.engine.events.emit('entity:remove', ent); // emit first: ent.x / ent.state are still readable and the model still exists
|
|
127
|
+
this.world.remove(id); // data removed, model torn down with it (def.dispose runs in _unbuild)
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
/** Remove every entity (records and models). Loading a save does not need it: world replaces its records itself. */
|
|
131
|
+
clear() { for (const ent of this.list()) this.remove(ent.id); }
|
|
132
|
+
|
|
133
|
+
/** Jump straight to a growth stage. */
|
|
134
|
+
setStage(ent, i) {
|
|
135
|
+
const st = ent.def.stages; if (!st) return;
|
|
136
|
+
i = Math.max(0, Math.min(st.length - 1, i));
|
|
137
|
+
const s = ent.state; s.stage = i; s.stageAt = this.now;
|
|
138
|
+
this.world.set(ent.id, { state: s });
|
|
139
|
+
this.engine.events.emit('entity:stage', { ent, stage: i, name: st[i].name }); // with a model, _refresh updates the look next frame
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// ---------- internals ----------
|
|
143
|
+
/**
|
|
144
|
+
* data -> ent view (same id is always the same view). Getters read data by id (never hold rec: a load swaps in new objects); _root / visual / _handles exist
|
|
145
|
+
* only while a model exists.
|
|
146
|
+
*/
|
|
147
|
+
_ent(rec) {
|
|
148
|
+
let ent = this._views.get(rec.id);
|
|
149
|
+
if (ent) return ent;
|
|
150
|
+
const self = this, id = rec.id, type = rec.kind.slice(KIND.length), W = this.world;
|
|
151
|
+
ent = {
|
|
152
|
+
id, type,
|
|
153
|
+
get def() { return self.types.get(type); }, // follows re-define
|
|
154
|
+
get x() { return W.get(id)?.position.x; }, get y() { return W.get(id)?.position.y; }, get z() { return W.get(id)?.position.z; },
|
|
155
|
+
get rotation() { return W.get(id)?.rotation; },
|
|
156
|
+
get state() { return W.get(id)?.state; },
|
|
157
|
+
get data() { return W.get(id)?.extra; },
|
|
158
|
+
get object() { return this._root; },
|
|
159
|
+
get stageName() { return this.def?.stages?.[W.get(id)?.state.stage]?.name ?? null; },
|
|
160
|
+
set: (k, v) => self._set(ent, k, v),
|
|
161
|
+
remove: () => self.remove(id),
|
|
162
|
+
_root: null, visual: null, _baseScale: 1, _modelStage: -1, _shownStage: -1, _handles: [],
|
|
163
|
+
};
|
|
164
|
+
this._views.set(id, ent);
|
|
165
|
+
return ent;
|
|
166
|
+
}
|
|
167
|
+
_label(label, ent) {
|
|
168
|
+
if (typeof label === 'function') return label(ent, this.engine);
|
|
169
|
+
if (!label) return this.engine.t('entities.use');
|
|
170
|
+
return this.engine.i18n.has(label) ? this.engine.t(label, { name: ent.stageName ?? ent.type }) : label;
|
|
171
|
+
}
|
|
172
|
+
_set(ent, k, v) {
|
|
173
|
+
const prev = ent.state[k];
|
|
174
|
+
if (prev === v) return;
|
|
175
|
+
const s = ent.state; s[k] = v;
|
|
176
|
+
this.world.set(ent.id, { state: s }); // via world.set: emits world:change and, in dev, checks the value is plain data
|
|
177
|
+
this.engine.events.emit('entity:state', { ent, key: k, value: v, prev });
|
|
178
|
+
}
|
|
179
|
+
// ent.object is an empty root (rotation and interactions hang on it; position is set by world each frame); the model ent.visual is its child, so a stage
|
|
180
|
+
// model swap replaces only the child
|
|
181
|
+
_build(ent) { return buildEntity(this, ent); }
|
|
182
|
+
// going far / removed: interaction, collision and model torn down together (geometry and materials disposed); data untouched
|
|
183
|
+
_unbuild(ent, obj) {
|
|
184
|
+
for (const h of ent._handles) h.remove();
|
|
185
|
+
ent._handles = [];
|
|
186
|
+
this.engine.remove(obj);
|
|
187
|
+
ent._root = null; ent.visual = null;
|
|
188
|
+
ent.def.dispose?.(ent, this.engine);
|
|
189
|
+
}
|
|
190
|
+
_setVisual(ent, obj) {
|
|
191
|
+
if (ent.visual) this.engine.remove(ent.visual); // stage model swap: old model fully removed (geometry/materials shared via assets are skipped)
|
|
192
|
+
ent.visual = obj || null;
|
|
193
|
+
if (obj) { ent._baseScale = obj.scale.x; ent._root.add(obj); }
|
|
194
|
+
}
|
|
195
|
+
// Per frame (with a model): update the look when the stage changed. scale multiplies the model's original size; model swaps the model (once per stage).
|
|
196
|
+
_refresh(ent) {
|
|
197
|
+
const stage = this.world.get(ent.id)?.state.stage;
|
|
198
|
+
if (!ent._root || stage === ent._shownStage) return;
|
|
199
|
+
ent._shownStage = stage;
|
|
200
|
+
const s = ent.def.stages?.[stage];
|
|
201
|
+
if (!s) return;
|
|
202
|
+
if (s.model && ent._modelStage !== stage) { this._setVisual(ent, s.model(this.engine, ent)); ent._modelStage = stage; }
|
|
203
|
+
ent.visual?.scale.setScalar(ent._baseScale * (s.scale ?? 1));
|
|
204
|
+
}
|
|
205
|
+
// Growth: caught up from clock.now, may cross several stages at once (load, return from far, long fast-forward); near and far both come through here
|
|
206
|
+
_grow(ent) {
|
|
207
|
+
const st = ent.def.stages; if (!st) return;
|
|
208
|
+
const s = ent.state, now = this.now;
|
|
209
|
+
const from = s.stage;
|
|
210
|
+
while (s.stage < st.length - 1 && st[s.stage].duration != null && now - s.stageAt >= st[s.stage].duration) {
|
|
211
|
+
if (ent.def.canGrow && !ent.def.canGrow(ent, this.engine)) break; // ask canGrow first; if not, stay in the current stage
|
|
212
|
+
s.stageAt += st[s.stage].duration; s.stage++;
|
|
213
|
+
}
|
|
214
|
+
if (s.stage === from) return; // asked every step: stage unchanged means no set and no event
|
|
215
|
+
this.world.set(ent.id, { state: s });
|
|
216
|
+
this.engine.events.emit('entity:stage', { ent, stage: s.stage, name: st[s.stage].name });
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const ENTITIES_PARAMS = keysSchema([]);
|
|
221
|
+
|
|
222
|
+
/** Entities module. Installs engine.entities. Data lives in engine.world (needs the world module, included by openWorld). */
|
|
223
|
+
export function entities(opts = {}) {
|
|
224
|
+
readParams('entities', ENTITIES_PARAMS, opts);
|
|
225
|
+
// takes no options: what an entity is and does goes in entities.define(type, {...})
|
|
226
|
+
let ents = null;
|
|
227
|
+
return {
|
|
228
|
+
name: 'entities', params: ENTITIES_PARAMS, options: opts, label: 'Entities', requires: ['world'], optional: ['sky', 'interactions', 'collision'], stage: 'gameplay', after: ['interactions', 'dialogue', 'triggers'],
|
|
229
|
+
install(e) {
|
|
230
|
+
ents = new Entities(e);
|
|
231
|
+
return ents;
|
|
232
|
+
},
|
|
233
|
+
describe(e, ctx) {
|
|
234
|
+
// Report only nearby ones: far entities have data but do not show up in "what's around". Uses the model as the locator so it merges with what the
|
|
235
|
+
// interactions module reports for the same object
|
|
236
|
+
for (const rec of ents.world.query({ near: ctx.center, radius: ctx.radius, where: r => r.kind.startsWith(KIND) })) {
|
|
237
|
+
const ent = ents._ent(rec);
|
|
238
|
+
ctx.near(ent.object ?? rec.position, { name: ent.id, kind: 'entity', type: ent.type, stage: ent.stageName });
|
|
239
|
+
}
|
|
240
|
+
return { count: ents.list().length };
|
|
241
|
+
},
|
|
242
|
+
};
|
|
243
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Building an entity's model side (helper of Entities.js): the empty root that carries rotation and interactions, its model, interaction and collider.
|
|
2
|
+
// `m` is the Entities instance.
|
|
3
|
+
|
|
4
|
+
export function buildEntity(m, ent) {
|
|
5
|
+
const e = m.engine, def = ent.def, rec = m.world.get(ent.id), root = new e.THREE.Group();
|
|
6
|
+
rec.position.y ??= e.surface(rec.position.x, rec.position.z); // initial world records may omit y (snap to ground); computed when the model is first built
|
|
7
|
+
root.position.set(rec.position.x, rec.position.y, rec.position.z);
|
|
8
|
+
root.rotation.y = rec.rotation;
|
|
9
|
+
root.userData.entity = ent.id;
|
|
10
|
+
root.userData.budgetTag = 'entities';
|
|
11
|
+
ent._root = root; ent.visual = null; ent._modelStage = -1; ent._shownStage = -1;
|
|
12
|
+
m._setVisual(ent, def.create(e, ent));
|
|
13
|
+
m._refresh(ent);
|
|
14
|
+
if (def.interact && e.interactions) {
|
|
15
|
+
const it = def.interact;
|
|
16
|
+
ent._handles.push(e.interactions.add(root, {
|
|
17
|
+
id: ent.id, // the interaction.use op names it the same in every run (an async create would otherwise get a load-order number)
|
|
18
|
+
label: () => m._label(it.label, ent), radius: it.radius ?? 2.5, action: it.action, height: it.height,
|
|
19
|
+
enabled: () => !!m.world.get(ent.id) && (it.enabled ? it.enabled(ent, e) : true),
|
|
20
|
+
onUse: () => it.onUse?.(ent, e),
|
|
21
|
+
}));
|
|
22
|
+
}
|
|
23
|
+
if (def.collider && e.collision) ent._handles.push(e.collision.addCircle({ x: rec.position.x, z: rec.position.z }, { radius: def.collider, height: def.colliderHeight ?? 3 }));
|
|
24
|
+
return root;
|
|
25
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// Game flow: states (title, playing, paused, game over...) and scene transitions (fade out → swap scene → fade in).
|
|
2
|
+
// engine.use(flow()); // built-in 'playing' (default) and 'paused' (freezes gameplay + locks input)
|
|
3
|
+
// engine.flow.define('title', { enter: e => showTitle(), exit: e => hideTitle(), freeze: true, lockInput: true, music: 'title' });
|
|
4
|
+
// engine.flow.go('paused'); engine.flow.state // 'paused'
|
|
5
|
+
// await engine.flow.transition(async () => engine.level.load('/models/town2.glb')); // lock input, fade out, load level, wait for ready, fade in
|
|
6
|
+
// Pause has one entry point: flow's 'paused' (internally engine.freeze('flow'); rendering continues); settings({ freezeWorld: true }) switches to it when the menu opens.
|
|
7
|
+
// Don't use engine.pause() (it stops rendering too; tests only). While frozen: fixed step, module fixed hooks, game clock, quest checks, timeline wait/tween all stop.
|
|
8
|
+
// engine.session.newGame / load / quit move flow too: back to the start state when a playthrough ends, then 'playing' when the next starts.
|
|
9
|
+
// Esc is not handled here: back goes through the UI focus stack (ui/Focus.js), and opens the settings menu when the stack is empty. Events: flow:change { from, to }, flow:transition { phase: 'start' | 'end' }.
|
|
10
|
+
import { checkOptions, warnMissing } from '../../core/validate.js';
|
|
11
|
+
import { readParams, keysSchema } from '../../core/params.js';
|
|
12
|
+
import { fadeScreen } from '../../ui/UI.js';
|
|
13
|
+
/** @import { ModuleDef } from '../../types/core' */
|
|
14
|
+
/** @import { Flow, FlowOptions } from '../../types/gameplay' */
|
|
15
|
+
|
|
16
|
+
const STATE_KEYS = ['enter', 'exit', 'freeze', 'lockInput', 'music'];
|
|
17
|
+
|
|
18
|
+
const FLOW_PARAMS = keysSchema(['start']);
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Game flow and scene transitions → engine.flow
|
|
22
|
+
* @param {FlowOptions} [opts]
|
|
23
|
+
* @returns {ModuleDef<Flow>}
|
|
24
|
+
*/
|
|
25
|
+
export function flow(opts = {}) {
|
|
26
|
+
readParams('flow', FLOW_PARAMS, opts);
|
|
27
|
+
let e = null, chain = Promise.resolve(), held = null;
|
|
28
|
+
const states = new Map([['playing', {}], ['paused', { freeze: true, lockInput: true }]]);
|
|
29
|
+
// turn freeze / input lock on or off for one state
|
|
30
|
+
const hold = (def, on) => {
|
|
31
|
+
if (def.freeze) on ? e.freeze('flow') : e.unfreeze('flow');
|
|
32
|
+
if (def.lockInput) { if (on) held ??= e.input.push('flow'); else { held?.remove(); held = null; } }
|
|
33
|
+
};
|
|
34
|
+
// wait until all modules are isReady() (checked per engine frame, so step() advances it too)
|
|
35
|
+
const allReady = () => [...e.modules.values()].every(m => !m.isReady || m.isReady(e));
|
|
36
|
+
const waitReady = () => allReady() ? Promise.resolve() : new Promise(res => { const h = e.onFrame(() => { if (allReady()) { h.remove(); res(); } }); });
|
|
37
|
+
|
|
38
|
+
const api = {
|
|
39
|
+
/** Current state name */
|
|
40
|
+
state: 'playing',
|
|
41
|
+
/** True while a scene transition is running */
|
|
42
|
+
transitioning: false,
|
|
43
|
+
/** Define a state: { enter(e, from), exit(e, to), freeze, lockInput, music } */
|
|
44
|
+
define(name, def) { checkOptions(`flow.define('${name}')`, def, STATE_KEYS); states.set(name, def); return api; },
|
|
45
|
+
/** Switch state */
|
|
46
|
+
go(name) {
|
|
47
|
+
const to = states.get(name);
|
|
48
|
+
if (!to) { warnMissing('flowState', name, [...states.keys()]); return; }
|
|
49
|
+
const from = api.state, def = states.get(from);
|
|
50
|
+
if (from === name) return;
|
|
51
|
+
def.exit?.(e, name);
|
|
52
|
+
hold(def, false);
|
|
53
|
+
api.state = name;
|
|
54
|
+
hold(to, true);
|
|
55
|
+
if (to.music !== undefined) to.music === null ? e.music?.stop() : e.music?.play(to.music);
|
|
56
|
+
to.enter?.(e, from);
|
|
57
|
+
e.events.emit('flow:change', { from, to: name });
|
|
58
|
+
},
|
|
59
|
+
/** Scene transition: lock input → fade out → fade music → (autosave: 'auto' saves slot 'auto') → fn() → wait for modules ready → fade in → unlock. Repeated calls are queued */
|
|
60
|
+
transition(fn, o = {}) {
|
|
61
|
+
checkOptions('flow.transition()', o, ['fade', 'lockInput', 'music', 'autosave']);
|
|
62
|
+
const { fade = 0.5, lockInput = true, music = 'fade', autosave = false } = o;
|
|
63
|
+
const run = async () => {
|
|
64
|
+
api.transitioning = true;
|
|
65
|
+
e.events.emit('flow:transition', { phase: 'start' });
|
|
66
|
+
const lock = lockInput ? e.input.push('transition') : null;
|
|
67
|
+
let shown = false;
|
|
68
|
+
try {
|
|
69
|
+
await fadeScreen(e, 1, fade);
|
|
70
|
+
const m = music === 'fade' ? e.music : null, prev = m?.current;
|
|
71
|
+
m?.stop(fade);
|
|
72
|
+
if (autosave === 'auto') e.saves.save('auto');
|
|
73
|
+
await e.ops.allow(async () => { await fn?.(); }); // the scene swap is loading: the ops guard lets its writes through
|
|
74
|
+
await waitReady();
|
|
75
|
+
if (m && prev && !m.current && !m.ruled) m.play(prev); // no track rule: resume the previous track after the switch
|
|
76
|
+
await fadeScreen(e, 0, fade);
|
|
77
|
+
shown = true;
|
|
78
|
+
} finally {
|
|
79
|
+
if (!shown) fadeScreen(e, 0, 0); // fn threw: don't leave the screen black, fade back in at once (the error still propagates to the caller)
|
|
80
|
+
lock?.remove();
|
|
81
|
+
api.transitioning = false;
|
|
82
|
+
e.events.emit('flow:transition', { phase: 'end' });
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
return (chain = chain.then(run, run));
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
return {
|
|
89
|
+
name: 'flow', params: FLOW_PARAMS, options: opts, label: 'Game flow', optional: ['music'],
|
|
90
|
+
install(engine) {
|
|
91
|
+
e = engine;
|
|
92
|
+
// initial state (title screen etc.): entered once the world is ready, so the game can define it after use()
|
|
93
|
+
if (opts.start && opts.start !== 'playing') e.events.once('engine:ready', () => api.go(opts.start));
|
|
94
|
+
// a playthrough ends (engine.session): back to the start state, so its enter() runs again; a new one starts in 'playing'
|
|
95
|
+
e.events.on('session:end', () => api.go(opts.start ?? 'playing'));
|
|
96
|
+
e.events.on('session:start', () => api.go('playing'));
|
|
97
|
+
return api;
|
|
98
|
+
},
|
|
99
|
+
describe() { return { state: api.state, transitioning: api.transitioning }; },
|
|
100
|
+
};
|
|
101
|
+
}
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
// Container: inventory, chest, corpse and shelf are all this. The player inventory is the container with id 'player'; get or create others with
|
|
2
|
+
// inventory.container(id, opts).
|
|
3
|
+
// Contents are entries { key, id, count, data }:
|
|
4
|
+
// items without data share one entry per kind, its key is the item id ('arrow');
|
|
5
|
+
// items with data (durability, upgrade level, rounds in the magazine, freshness: a plain object) get their own key ('sword#3'):
|
|
6
|
+
// stackable ones with equal data share an entry, a stack-1 item is one entry per piece. Keys are unique across containers and kept when moved.
|
|
7
|
+
// Every method that takes an item also takes a key: count('sword') counts all swords, count('sword#3') only that one.
|
|
8
|
+
// Limits are optional: capacity (slots; an entry uses ceil(count / stack) slots) and maxWeight (sum of item weight × count). Locks and prices stay game rules.
|
|
9
|
+
import { checkOptionsArg, fmt, DEV } from '../../core/validate.js';
|
|
10
|
+
import { sig, freeze, canTrade, acceptsFrom, putIn, loadEntries } from './boxOps.js';
|
|
11
|
+
|
|
12
|
+
// Developer messages (warned once in DEV): add doesn't throw when full, which an AI would hardly notice
|
|
13
|
+
const STRINGS = {
|
|
14
|
+
badData: "{fn}('{id}', …): data must be a plain object of JSON values, e.g. { durability: 80 }; got {got}",
|
|
15
|
+
noKey: "{fn}('{key}'): no entry with that key in container {box} (keys here: {keys}); keys come from add() or list()[i].key",
|
|
16
|
+
keyToAdd: "add('{key}'): add takes an item id, not an entry key. Move an existing piece with inventory.transfer(from, to, '{key}')",
|
|
17
|
+
};
|
|
18
|
+
const isKey = x => typeof x === 'string' && x.includes('#');
|
|
19
|
+
/** A frozen copy of the data the caller passed (the caller's object stays editable and unshared) @internal */
|
|
20
|
+
export function copyData(fn, id, data) {
|
|
21
|
+
if (data == null) return undefined;
|
|
22
|
+
if (typeof data !== 'object' || Object.getPrototypeOf(data) !== Object.prototype) throw new Error(fmt(STRINGS.badData, { fn, id, got: JSON.stringify(data) ?? typeof data }));
|
|
23
|
+
return freeze(structuredClone(data));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export class Container {
|
|
27
|
+
/** @internal Get it via inventory.container(id, opts); don't use new directly */
|
|
28
|
+
constructor(inv, id, { capacity = Infinity, maxWeight = Infinity, player = false } = {}) {
|
|
29
|
+
this.inv = inv; this.id = id;
|
|
30
|
+
/** Slot limit (Infinity = no limit) */ this.capacity = capacity;
|
|
31
|
+
/** Weight limit, sum of item weight × count (Infinity = no limit) */ this.maxWeight = maxWeight;
|
|
32
|
+
/** @internal { key, id, count, data, sig } in insertion order */ this._entries = [];
|
|
33
|
+
this._player = player; // player inventory: shows toasts, emits item:* events, refreshes the inventory window
|
|
34
|
+
this.seeded = false; // starting contents were placed on creation: still saved when emptied, so a load doesn't treat it as new and place them again
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** How many of an item (all entries of that id) or of one entry (key). @param {string} x @returns {number} */
|
|
38
|
+
count(x) { let n = 0; for (const e of this._entries) if (e.key === x || e.id === x) n += e.count; return n; }
|
|
39
|
+
/** At least n (default 1) of an item or key? @param {string} x @param {number} [n] @returns {boolean} */
|
|
40
|
+
has(x, n = 1) { return this.count(x) >= n; }
|
|
41
|
+
/** One entry by key: { key, id, count, data, def }, or null. @param {string} key */
|
|
42
|
+
get(key) { const e = this._find(key); return e ? this._view(e) : null; }
|
|
43
|
+
/** Every entry: [{ key, id, count, data, def }] (data is undefined for plain items; for custom UI). */
|
|
44
|
+
list() { return this._entries.map(e => this._view(e)); }
|
|
45
|
+
/** Slots used (an entry of 150 arrows with stack 99 uses 2). */
|
|
46
|
+
get slotsUsed() { let n = 0; for (const e of this._entries) n += Math.ceil(e.count / this.inv.item(e.id).stack); return n; }
|
|
47
|
+
/** Total weight (item weight × count; items without weight weigh 0). */
|
|
48
|
+
get weight() { let w = 0; for (const e of this._entries) w += e.count * (this.inv.item(e.id).weight ?? 0); return w; }
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* How many more fit (0 = none, Infinity = no limit): of an item without data, of an item with this data, or of the same kind as an existing entry key.
|
|
52
|
+
* @example chest.room('arrow') · chest.room('tomato', { quality: 2 }) · engine.inventory.container('player').room('sword#3')
|
|
53
|
+
* @param {string} x
|
|
54
|
+
* @param {Record<string, any>} [data]
|
|
55
|
+
* @returns {number}
|
|
56
|
+
*/
|
|
57
|
+
room(x, data) {
|
|
58
|
+
if (!isKey(x)) return this._room(x, data === undefined ? undefined : copyData('room', x, data));
|
|
59
|
+
const src = this.inv._containers.entry(x);
|
|
60
|
+
if (!src) throw new Error(fmt(STRINGS.noKey, { fn: 'room', key: x, box: this.id, keys: this._keys() }));
|
|
61
|
+
return this._room(src.id, src.data);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Add n (default 1) of an item, optionally with data for these pieces. Partial fit places what fits.
|
|
66
|
+
* Returns the key of the entry they went into ('arrow', or 'sword#3' for an item with data), false if none fit. silent suppresses the toast (only the player
|
|
67
|
+
* inventory toasts).
|
|
68
|
+
* @example engine.inventory.container('chest-1').add('bandage', 2)
|
|
69
|
+
* @example const key = engine.inventory.add('sword', 1, { data: { durability: 80, level: 3 } }); // 'sword#7'
|
|
70
|
+
* @param {string} id
|
|
71
|
+
* @param {number} [n]
|
|
72
|
+
* @param {{ data?: Record<string, any>, silent?: boolean }} [opts]
|
|
73
|
+
* @returns {string | false}
|
|
74
|
+
*/
|
|
75
|
+
add(id, n = 1, opts = {}) {
|
|
76
|
+
DEV && this.inv.engine.ops.guard(this._player ? 'inventory.add' : 'container.add');
|
|
77
|
+
checkOptionsArg(`add('${id}')`, opts, ['data', 'silent']);
|
|
78
|
+
if (isKey(id)) throw new Error(fmt(STRINGS.keyToAdd, { key: id }));
|
|
79
|
+
this.inv._known(id);
|
|
80
|
+
return this._put(id, n, copyData('add', id, opts?.data), null, !!opts?.silent);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Remove n (default 1) of an item or of one entry (key); returns false if there aren't enough. By item id, plain pieces go first, then pieces with data,
|
|
85
|
+
* oldest first.
|
|
86
|
+
* @example bag.remove('arrow', 3) · bag.remove('sword#3') // exactly that sword
|
|
87
|
+
* @param {string} x
|
|
88
|
+
* @param {number} [n]
|
|
89
|
+
* @returns {boolean}
|
|
90
|
+
*/
|
|
91
|
+
remove(x, n = 1) {
|
|
92
|
+
DEV && this.inv.engine.ops.guard(this._player ? 'inventory.remove' : 'container.remove');
|
|
93
|
+
if (!this.has(x, n)) return false;
|
|
94
|
+
let rest = n;
|
|
95
|
+
for (const e of this._of(x)) { const k = Math.min(rest, e.count); this._take(e, k); if (!(rest -= k)) break; }
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Trade: take A out and put B in as ONE all-or-nothing step (swap a key for a better key, replace an item when the bag is full).
|
|
101
|
+
* It first checks (on a copy) that A is there and that B fits once A is gone; if either fails nothing changes and you get { ok: false, reason }.
|
|
102
|
+
* reason: 'notEnough' (you do not hold takeN of take) or 'full' (B would not fit even after A is removed).
|
|
103
|
+
* take is an item id or an entry key ('sword#3'); give is an item id (never a key). Removal goes plain pieces first, like remove().
|
|
104
|
+
* On success: { ok: true, took: [{ id, count, data? }], gave: entry key of B, giveId, giveN }. engine.ops.undo('inventory.trade', args, value) reverses it.
|
|
105
|
+
* @example const r = bag.trade('rusty_key', 'gold_key'); if (!r.ok) say(r.reason); // 'full' / 'notEnough'
|
|
106
|
+
* @example engine.inventory.container('chest-1').trade('arrow', 'bolt', { takeN: 10, giveN: 10, data: { tip: 'iron' } })
|
|
107
|
+
* @param {string} take
|
|
108
|
+
* @param {string} give
|
|
109
|
+
* @param {{ takeN?: number, giveN?: number, data?: Record<string, any>, silent?: boolean }} [opts]
|
|
110
|
+
* @returns {{ ok: boolean, reason?: string, took?: { id: string, count: number, data?: any }[], gave?: string, giveId?: string, giveN?: number }}
|
|
111
|
+
*/
|
|
112
|
+
trade(take, give, opts = {}) {
|
|
113
|
+
DEV && this.inv.engine.ops.guard(this._player ? 'inventory.trade' : 'container.trade');
|
|
114
|
+
checkOptionsArg(`trade('${take}', '${give}')`, opts, ['takeN', 'giveN', 'data', 'silent']);
|
|
115
|
+
const { takeN = 1, giveN = 1 } = opts;
|
|
116
|
+
if (!(takeN > 0) || !(giveN > 0)) throw new Error(`trade('${take}', '${give}'): takeN and giveN must be positive numbers, got takeN ${takeN}, giveN ${giveN}. Example: bag.trade('rusty_key', 'gold_key', { takeN: 1, giveN: 1 })`);
|
|
117
|
+
if (isKey(give)) throw new Error(fmt(STRINGS.keyToAdd, { key: give }));
|
|
118
|
+
this.inv._known(give);
|
|
119
|
+
const data = copyData('trade', give, opts.data), why = this._canTrade(take, give, takeN, giveN, data);
|
|
120
|
+
if (why !== true) return { ok: false, reason: why };
|
|
121
|
+
const took = [];
|
|
122
|
+
let rest = takeN;
|
|
123
|
+
for (const en of this._of(take)) {
|
|
124
|
+
const k = Math.min(rest, en.count);
|
|
125
|
+
took.push({ id: en.id, count: k, ...(en.data !== undefined && { data: en.data }) });
|
|
126
|
+
this._take(en, k);
|
|
127
|
+
if (!(rest -= k)) break;
|
|
128
|
+
}
|
|
129
|
+
const gave = this._put(give, giveN, data, null, !!opts.silent);
|
|
130
|
+
return { ok: true, took, gave, giveId: give, giveN };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Replace the data of an entry (null = no data). n pieces (default all of the entry) change; fewer than all splits them into their own entry.
|
|
135
|
+
* Returns the key now holding the changed pieces: the same key when a whole entry changes, a merged or new key otherwise. Limits are not checked (the pieces
|
|
136
|
+
* are already inside).
|
|
137
|
+
* @example
|
|
138
|
+
* const s = bag.get(key); // { key, id, count, data, def }
|
|
139
|
+
* bag.setData(key, { ...s.data, durability: s.data.durability - 1 }); // data objects are frozen: always pass a new one
|
|
140
|
+
* @param {string} key
|
|
141
|
+
* @param {Record<string, any> | null} data
|
|
142
|
+
* @param {number} [n]
|
|
143
|
+
* @returns {string}
|
|
144
|
+
*/
|
|
145
|
+
setData(key, data, n) {
|
|
146
|
+
DEV && this.inv.engine.ops.guard(this._player ? 'inventory.setData' : 'container.setData');
|
|
147
|
+
const e = this._find(key);
|
|
148
|
+
if (!e) throw new Error(fmt(STRINGS.noKey, { fn: 'setData', key, box: this.id, keys: this._keys() }));
|
|
149
|
+
const d = copyData('setData', e.id, data), k = Math.min(n ?? e.count, e.count), at = this._entries.indexOf(e);
|
|
150
|
+
const keep = k === e.count && e.data !== undefined ? e.key : null; // a whole entry keeps its key, so references held by the game stay valid
|
|
151
|
+
e.count -= k;
|
|
152
|
+
if (!e.count) this._entries.splice(at, 1);
|
|
153
|
+
const out = this._place(e.id, k, d, keep, at);
|
|
154
|
+
if (this._player) this.inv._refresh();
|
|
155
|
+
return out;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Listen to changes of this container, returns a handle { remove() }. type 'add' | 'remove', callback gets { id: item, key: entry key, count: change amount,
|
|
160
|
+
* total: current count of the item }
|
|
161
|
+
* @example engine.inventory.container('chest-1').on('remove', ({ id, count }) => console.log('taken', id, count))
|
|
162
|
+
* @param {'add' | 'remove'} type
|
|
163
|
+
* @param {(e: { id: string, key: string, count: number, total: number }) => void} fn
|
|
164
|
+
*/
|
|
165
|
+
on(type, fn) {
|
|
166
|
+
if (type !== 'add' && type !== 'remove') throw new Error(`container.on events are only 'add' and 'remove', got '${type}'. Use one of them.`);
|
|
167
|
+
const ev = this._player ? `item:${type}` : `container:${type}`;
|
|
168
|
+
return this.inv.engine.events.on(ev, e => { if (this._player || e.container === this.id) fn({ id: e.id, key: e.key, count: e.count, total: e.total }); });
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// ---------- internal ----------
|
|
172
|
+
/** Dry run of trade: true, or 'notEnough' / 'full'. Removes A from a copy, then asks that copy whether B fits (the same trick transfer uses) @internal */
|
|
173
|
+
_canTrade(take, give, takeN, giveN, data) { return canTrade(this, take, give, takeN, giveN, data); }
|
|
174
|
+
/** @internal */ _find(key) { return this._entries.find(e => e.key === key) || null; }
|
|
175
|
+
/** @internal */ _keys() { return this._entries.map(e => e.key).join(', ') || 'none'; }
|
|
176
|
+
/** @internal */ _view(e) { return { key: e.key, id: e.id, count: e.count, data: e.data, def: this.inv.item(e.id) }; }
|
|
177
|
+
/** Entries an item id or key refers to; for an id, plain entries first @internal */
|
|
178
|
+
_of(x) {
|
|
179
|
+
if (isKey(x)) return this._entries.filter(e => e.key === x);
|
|
180
|
+
const all = this._entries.filter(e => e.id === x);
|
|
181
|
+
return [...all.filter(e => e.data === undefined), ...all.filter(e => e.data !== undefined)];
|
|
182
|
+
}
|
|
183
|
+
/** Room for an item with this (already copied) data @internal */
|
|
184
|
+
_room(id, data) {
|
|
185
|
+
const def = this.inv.item(id), st = def.stack, s = sig(data);
|
|
186
|
+
const into = (data === undefined || st > 1) && this._entries.find(e => e.id === id && e.sig === s);
|
|
187
|
+
let n = (into ? (st - into.count % st) % st : 0) + Math.max(0, this.capacity - this.slotsUsed) * st;
|
|
188
|
+
if (def.weight > 0) n = Math.min(n, Math.floor((this.maxWeight - this.weight) / def.weight + 1e-9));
|
|
189
|
+
return Math.max(0, n);
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* How many of item (id or key) from src would really move here, up to n: a dry run on a copy, so entries that share free slots are not counted twice
|
|
193
|
+
* @internal
|
|
194
|
+
*/
|
|
195
|
+
_accepts(src, item, n) { return acceptsFrom(this, src, item, n); }
|
|
196
|
+
/** Add without the guard (add and transfer); key = keep this key for a new entry (moved pieces) @internal */
|
|
197
|
+
_put(id, n, data, key, silent) { return putIn(this, id, n, data, key, silent); }
|
|
198
|
+
/** Put k pieces in at index at, merging with an equal entry where the item stacks; returns the key of the last entry used @internal */
|
|
199
|
+
_place(id, k, data, key, at) {
|
|
200
|
+
const s = sig(data), st = this.inv.item(id).stack;
|
|
201
|
+
if (data === undefined || st > 1) {
|
|
202
|
+
let e = this._entries.find(x => x.id === id && x.sig === s);
|
|
203
|
+
if (!e) this._entries.splice(at, 0, e = { key: data === undefined ? id : key ?? this.inv._newKey(id), id, count: 0, data, sig: s });
|
|
204
|
+
e.count += k;
|
|
205
|
+
return e.key;
|
|
206
|
+
}
|
|
207
|
+
let last = '';
|
|
208
|
+
for (let i = 0; i < k; i++) this._entries.splice(at + i, 0, { key: last = i === 0 && key ? key : this.inv._newKey(id), id, count: 1, data, sig: s });
|
|
209
|
+
return last;
|
|
210
|
+
}
|
|
211
|
+
/** Take k out of an entry without the guard @internal */
|
|
212
|
+
_take(e, k) {
|
|
213
|
+
e.count -= k;
|
|
214
|
+
if (!e.count) this._entries.splice(this._entries.indexOf(e), 1);
|
|
215
|
+
this._emit('remove', e.id, k, e.key);
|
|
216
|
+
}
|
|
217
|
+
/** The player inventory emits item:add / item:remove; other containers emit container:add / container:remove (with container = container id). @internal */
|
|
218
|
+
_emit(type, id, count, key) {
|
|
219
|
+
const events = this.inv.engine.events, e = { id, key, count, total: this.count(id) };
|
|
220
|
+
if (this._player) { events.emit(type === 'add' ? 'item:add' : 'item:remove', e); this.inv._refresh(); }
|
|
221
|
+
else events.emit(type === 'add' ? 'container:add' : 'container:remove', { container: this.id, ...e });
|
|
222
|
+
}
|
|
223
|
+
/** Save form: plain { id, count }, with data { id, count, key, data } @internal */
|
|
224
|
+
_save() { return this._entries.map(e => e.data === undefined ? { id: e.id, count: e.count } : { id: e.id, count: e.count, key: e.key, data: e.data }); }
|
|
225
|
+
/** Read a saved list. Saves can come from a file the player imported, so each row is checked; a bad row is dropped with a warning @internal */
|
|
226
|
+
_load(list) { loadEntries(this, list); }
|
|
227
|
+
}
|