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,231 @@
|
|
|
1
|
+
// World data, engine.world: anything the game must remember or keep changing while far away is a plain record here (stable id, kind, position, your own
|
|
2
|
+
// fields);
|
|
3
|
+
// a model is only what gets built while the record is near the camera. It knows nothing about NPCs, zombies or crops: the game (or a larger module) tells them
|
|
4
|
+
// apart by kind and writes its own present / simulate.
|
|
5
|
+
// Usage, examples, the update convention (set / move), saves, near / far and zone: see packages/engine/docs/recipes/18-world.md; the save rules are at the top
|
|
6
|
+
// of persist.js.
|
|
7
|
+
// Data must be plain values (putting a three.js object or a function in it throws in dev); position is a plain { x, y, z }. Don't hold on to rec: loading a
|
|
8
|
+
// save swaps in new objects, so keep the id and use world.get(id).
|
|
9
|
+
import { DEV, fmt } from '../../core/validate.js';
|
|
10
|
+
import { addRecord, setRecord, removeRecord, queryRecords } from './records.js';
|
|
11
|
+
import { Views } from './views.js';
|
|
12
|
+
import { Sim } from './sim.js';
|
|
13
|
+
import { initState, mixInternals } from './state.js';
|
|
14
|
+
import { putPos, centerOf } from './pos.js';
|
|
15
|
+
|
|
16
|
+
const STRINGS = {
|
|
17
|
+
anchor: 'world.anchor must be null, an Object3D, a Vector3 / { x, z } or [x, y, z]; got {got}',
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/** World data (see the top of the file) */
|
|
21
|
+
export class World {
|
|
22
|
+
/**
|
|
23
|
+
* @param {any} engine
|
|
24
|
+
* @param {{ cellSize?: number, radius?: number, farEvery?: number, farMaxPerTick?: number, buildPerFrame?: number }} [opts]
|
|
25
|
+
*/
|
|
26
|
+
constructor(engine, opts = {}) {
|
|
27
|
+
const { cellSize = 32, radius = 60, farEvery = 1, farMaxPerTick = 500, buildPerFrame = 8 } = opts;
|
|
28
|
+
/** @internal */ this.engine = engine;
|
|
29
|
+
initState(this, cellSize);
|
|
30
|
+
/** All records: id → record (read-only; use set to change fields, move to change position) @type {Map<string, WorldRecord>} */
|
|
31
|
+
this.records = new Map();
|
|
32
|
+
/**
|
|
33
|
+
* Default distance (meters) for building models and counting as near; present / simulate can override it. Changing it at runtime affects those without
|
|
34
|
+
* their own radius @type {number}
|
|
35
|
+
*/
|
|
36
|
+
this.radius = radius;
|
|
37
|
+
/** Default interval (seconds) between far simulations, same unit as dt @type {number} */
|
|
38
|
+
this.farEvery = farEvery;
|
|
39
|
+
/**
|
|
40
|
+
* Max far simulations per fixed step; the rest queue for the next step (dt accumulates, no time is lost). Counted by records, not milliseconds, so results
|
|
41
|
+
* do not depend on machine speed @type {number}
|
|
42
|
+
*/
|
|
43
|
+
this.farMaxPerTick = farMaxPerTick;
|
|
44
|
+
/** Max models built per frame; the rest continue next frame (ready waits for all of them; loading is not limited) @type {number} */
|
|
45
|
+
this.buildPerFrame = buildPerFrame;
|
|
46
|
+
/** @internal */ this._v = new Views(this);
|
|
47
|
+
/** @internal */ this._s = new Sim(this);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Gameplay simulation center (near / far is measured from it): null (default) = where engine.actor is (engine.actorPosition(): the player, or engine.focus
|
|
52
|
+
* when there is no player). The built-in stream source engine.stream.player follows the player too (models and colliders around it); the camera source
|
|
53
|
+
* engine.stream.camera adds models only.
|
|
54
|
+
* For another center (a strategy game's base) set a Vector3 / object / { x, z } / [x, y, z]; set null to restore. Read once at the start of each fixed step
|
|
55
|
+
* @example engine.world.anchor = baseObject
|
|
56
|
+
* @type {any}
|
|
57
|
+
*/
|
|
58
|
+
get anchor() { return this._anchor; }
|
|
59
|
+
set anchor(a) {
|
|
60
|
+
const ok = a == null || a.isObject3D || (Array.isArray(a) ? a.length === 3 && a.every(Number.isFinite) : Number.isFinite(a.x) && Number.isFinite(a.z));
|
|
61
|
+
if (!ok) throw new Error(fmt(STRINGS.anchor, { got: JSON.stringify(a) }));
|
|
62
|
+
this._anchor = a ?? null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Current zone (e.g. level name, set by the level module on level change): once set, records of another zone get no model and no near simulation; null = no
|
|
67
|
+
* zoning @type {string | null}
|
|
68
|
+
*/
|
|
69
|
+
get zone() { return this._zone; }
|
|
70
|
+
// a zone change must re-decide which models to build (otherwise nothing refreshes while the focus stays still)
|
|
71
|
+
set zone(z) { if (z !== this._zone) { this._zone = z; this._v.dirty = true; } }
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Add a record and return it (a plain object). kind is required; without id one is numbered automatically (kind#1, kind#2…, saved; `#` never appears in an
|
|
75
|
+
* authored id, so the two can never collide).
|
|
76
|
+
* opts.initial: initial record written in content (needs an id); saves only keep its changes and removal; if the id already exists the existing one is
|
|
77
|
+
* returned (content may load twice);
|
|
78
|
+
* returns null if the save removed it (it is not added back). opts.save: false: not saved (temporary things).
|
|
79
|
+
* @example engine.world.add({ id: 'shop_owner', kind: 'npc', position: [12, 0, -30], name: '店主', mood: 'calm' }, { initial: true })
|
|
80
|
+
* @param {{ kind: string, id?: string, position?: any, [field: string]: any }} def
|
|
81
|
+
* @param {{ initial?: boolean, save?: boolean }} [opts]
|
|
82
|
+
* @returns {WorldRecord | null}
|
|
83
|
+
*/
|
|
84
|
+
add(def, opts) { return addRecord(this, def, opts); }
|
|
85
|
+
/**
|
|
86
|
+
* Where a record comes from (filled in dev and test builds; null in release): { definedAt: 'content/props.js:14' } for a content entry,
|
|
87
|
+
* { level, node } for a level-model node, { template } when it is a template instance, { spawned: { op, tick } } for a record created during play.
|
|
88
|
+
* engine.inspect(id) and engine.pick(...).thing show it, so you know which file to edit to change the level for good.
|
|
89
|
+
* @example engine.world.origin('chest-home') // { definedAt: 'content/props.js:14', template: 'chest' }
|
|
90
|
+
* @param {string} id
|
|
91
|
+
* @returns {{ definedAt?: string, level?: string, node?: string, template?: string, spawned?: { op: string | null, tick: number } } | null}
|
|
92
|
+
*/
|
|
93
|
+
origin(id) { return this._origin.get(id) ?? null; }
|
|
94
|
+
/**
|
|
95
|
+
* The id of the record whose model contains obj (obj itself or one of its parents is a built model), else null. A ray hit on a model names its record this
|
|
96
|
+
* way.
|
|
97
|
+
* @example const h = engine.pick(0, 0); const id = h && engine.world.idOf(h.object);
|
|
98
|
+
* @param {any} obj a THREE.Object3D (a mesh of the model is fine)
|
|
99
|
+
* @returns {string | null}
|
|
100
|
+
*/
|
|
101
|
+
idOf(obj) {
|
|
102
|
+
for (let o = obj; o; o = o.parent) { const id = this._v.byObj.get(o); if (id !== undefined) return id; }
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Get a record by id (undefined if missing, like a Map)
|
|
107
|
+
* @param {string} id
|
|
108
|
+
* @returns {WorldRecord | undefined}
|
|
109
|
+
*/
|
|
110
|
+
get(id) { return this.records.get(id); }
|
|
111
|
+
/**
|
|
112
|
+
* Merge fields into a record and emit the world:change event; a position in patch also moves it. Returns the record.
|
|
113
|
+
* For discrete changes (chest opened, growth stage, picked up); if present has show, it is re-evaluated after the change. id / kind cannot be changed
|
|
114
|
+
* @example engine.world.set('crate_1', { opened: true })
|
|
115
|
+
* @param {string} id
|
|
116
|
+
* @param {Record<string, any>} patch
|
|
117
|
+
* @returns {WorldRecord}
|
|
118
|
+
*/
|
|
119
|
+
set(id, patch) { return setRecord(this, id, patch); }
|
|
120
|
+
/**
|
|
121
|
+
* Move a record (no event; use it in simulate for things that move every step); still saved (saves diff against content).
|
|
122
|
+
* The model of a positionFrom 'record' (default) record follows this frame; to do something else with the position in presentation, compare in update
|
|
123
|
+
* @example engine.world.move(rec.id, { x: rec.position.x + 1, z: rec.position.z })
|
|
124
|
+
* @param {string} id
|
|
125
|
+
* @param {any} position Vector3 / object / [x, y, z] / { x, z } (y stays unchanged if omitted)
|
|
126
|
+
* @returns {void}
|
|
127
|
+
*/
|
|
128
|
+
move(id, position) {
|
|
129
|
+
DEV && this.engine.ops.guard('world.move');
|
|
130
|
+
const rec = this._need(id, 'move');
|
|
131
|
+
putPos(`world.move("${id}")`, position, rec.position);
|
|
132
|
+
this._index(rec);
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Remove a record (its model is torn down too) and emit the world:remove event. Does nothing if the id does not exist. Removing an initial record is saved,
|
|
136
|
+
* so it stays gone after loading
|
|
137
|
+
* @param {string} id
|
|
138
|
+
* @returns {void}
|
|
139
|
+
*/
|
|
140
|
+
remove(id) { removeRecord(this, id); }
|
|
141
|
+
/**
|
|
142
|
+
* Query records; returns an array. With near only nearby cells are scanned and results are sorted nearest first (radius defaults to 30 m); where filters
|
|
143
|
+
* further. For neighbor queries every step use forEachNear
|
|
144
|
+
* @example engine.world.query({ kind: 'zombie', near: engine.player, radius: 30, where: z => !z.dead })
|
|
145
|
+
* @param {{ kind?: string, near?: any, radius?: number, where?: (rec: WorldRecord) => boolean, zone?: string | null }} [opts]
|
|
146
|
+
* @returns {WorldRecord[]}
|
|
147
|
+
*/
|
|
148
|
+
query(opts = {}) { return queryRecords(this, opts); }
|
|
149
|
+
/**
|
|
150
|
+
* Call fn(rec, d2) for each record within radius meters (horizontal distance) of center; d2 is the squared distance. Unsorted, no allocation: use it for
|
|
151
|
+
* per-step neighbor queries (hundreds of zombies avoiding each other).
|
|
152
|
+
* Don't add / remove / move in the callback (moving into a cell not yet visited visits it again): record the change and apply it after the loop
|
|
153
|
+
* @example engine.world.forEachNear(rec.position, 5, (o, d2) => { if (o !== rec && o.kind === 'zombie') n++; })
|
|
154
|
+
* @param {any} center Vector3 / object / { x, z }
|
|
155
|
+
* @param {number} radius
|
|
156
|
+
* @param {(rec: WorldRecord, d2: number) => void} fn
|
|
157
|
+
* @returns {void}
|
|
158
|
+
*/
|
|
159
|
+
forEachNear(center, radius, fn) { this._cells.forEach(centerOf(center), radius, fn); }
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Register how a kind of thing looks: models are built automatically within radius meters of any full-detail stream source (engine.stream: player, camera
|
|
163
|
+
* focus, teleport destination) and torn down when far from all of them (radius × 1.25); tearing down never touches the record. Callbacks:
|
|
164
|
+
* build(rec) → three.js object (may be async). world adds it to the scene and places it at rec.position; if it throws / fails / returns a non-object:
|
|
165
|
+
* reported once, does not block ready, retried when you leave and come back.
|
|
166
|
+
* update(rec, obj, dt): called every frame for records that have a model (change the look from the data, e.g. an opened chest swaps texture).
|
|
167
|
+
* dispose(rec, obj): called on teardown (record first, model second); if omitted, engine.remove(obj).
|
|
168
|
+
* show(rec) → false: this record has no model right now (picked up, waiting to respawn); re-evaluated when world.set changes records of this kind.
|
|
169
|
+
* radius: meters, or a function (for distances that change, like terrain view distance); defaults to world.radius. Registering the same kind again: old
|
|
170
|
+
* models are torn down with the old dispose and rebuilt with the new one.
|
|
171
|
+
* positionFrom: 'record' (default, the model follows the record every frame) or 'view' (the model moves itself, e.g. driven by a character mover; model
|
|
172
|
+
* position is copied back to the record at the end of each fixed step).
|
|
173
|
+
* @example engine.world.present('chest', { build: rec => new THREE.Mesh(boxGeo, makeMaterial('prop')), dispose: (rec, obj) => engine.remove(obj), show: rec
|
|
174
|
+
* => !rec.looted })
|
|
175
|
+
* @param {string} kind
|
|
176
|
+
* @param {{ build: (rec: WorldRecord) => any, update?: (rec: WorldRecord, obj: any, dt: number) => void, dispose?: (rec: WorldRecord, obj: any) => void,
|
|
177
|
+
* show?: (rec: WorldRecord) => boolean, radius?: number | (() => number), positionFrom?: 'record' | 'view' }} opts
|
|
178
|
+
* @returns {{ remove(): void }}
|
|
179
|
+
*/
|
|
180
|
+
present(kind, opts) { return this._v.present(kind, opts); }
|
|
181
|
+
/**
|
|
182
|
+
* The current model of this record (only exists nearby; null if not built yet or far away)
|
|
183
|
+
* @param {string} id
|
|
184
|
+
* @returns {any}
|
|
185
|
+
*/
|
|
186
|
+
view(id) { return this._v.map.get(id)?.obj ?? null; }
|
|
187
|
+
/**
|
|
188
|
+
* All models that should exist near the stream sources are built (async ones too; failed builds do not count as pending). The loading screen waits for it; to
|
|
189
|
+
* wait yourself, await world.whenReady @type {boolean}
|
|
190
|
+
*/
|
|
191
|
+
get ready() { return this._v.ready; }
|
|
192
|
+
/** Promise that resolves when ready becomes true @type {Promise<void>} */
|
|
193
|
+
get whenReady() { return this._v.whenReady; }
|
|
194
|
+
/**
|
|
195
|
+
* Build / tear down models for the stream sources right now (normally automatic every frame, with a per-frame limit). Use it right after add when you need
|
|
196
|
+
* the model: sync builds are available via view(id) after the call, for async ones also await world.whenReady
|
|
197
|
+
* @example engine.world.add({ id: 'gate', kind: 'gate', position: p }); engine.world.refresh(); engine.world.view('gate')
|
|
198
|
+
* @returns {void}
|
|
199
|
+
*/
|
|
200
|
+
refresh() { this._v.refresh(); }
|
|
201
|
+
/**
|
|
202
|
+
* Register how a kind of thing changes (gameplay logic goes here, runs in the fixed step); near / far is split by distance from world.anchor (default: the
|
|
203
|
+
* player):
|
|
204
|
+
* near(rec, dt, obj): within radius, once per fixed step (obj is the model, may be null if not built yet; gameplay must not depend on it);
|
|
205
|
+
* far(rec, dt): farther away, once every farEvery seconds; dt is the seconds accumulated since the last simulation (can catch up a long time at once); on the
|
|
206
|
+
* far → near step, far runs first to pay back the owed time.
|
|
207
|
+
* With only far (crops), near also advances via far; with only near, far records are not simulated and owed time is not made up.
|
|
208
|
+
* Both dt are accumulated fixed-step seconds (not multiplied by clock.timeScale). For things measured in game clock (grows over days) store engine.clock.now
|
|
209
|
+
* and compare.
|
|
210
|
+
* radius defaults to the present radius ('view' widened by 1.25), or world.radius without present; may also be a function.
|
|
211
|
+
* worker: true (experimental) runs far in engine.threads workers (batched per step, written back 4 steps later, bit-identical with threads off). far must
|
|
212
|
+
* then be self-contained:
|
|
213
|
+
* it is recompiled from source and sees only (rec, dt) and globals like Math; an outside variable throws naming it (threads on or off alike).
|
|
214
|
+
* @example engine.world.simulate('zombie', { near: (rec, dt) => chase(rec, dt), far: (rec, dt) => wander(rec, dt), farEvery: 2 })
|
|
215
|
+
* @example engine.world.simulate('crop', { far: (rec, dt) => { rec.growth = Math.min(1, rec.growth + dt / 600); }, worker: true })
|
|
216
|
+
* @param {string} kind
|
|
217
|
+
* @param {{ near?: (rec: WorldRecord, dt: number, obj: any) => void, far?: (rec: WorldRecord, dt: number) => void, farEvery?: number, radius?: number | (()
|
|
218
|
+
* => number), worker?: boolean }} opts
|
|
219
|
+
* @returns {{ remove(): void }}
|
|
220
|
+
*/
|
|
221
|
+
simulate(kind, opts) { return this._s.simulate(kind, opts); }
|
|
222
|
+
/** Number of fixed steps simulated */ get steps() { return this._s.n; }
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* One world record: id, kind and position are fixed fields, the rest are yours (plain values only)
|
|
229
|
+
* @typedef {{ id: string, kind: string, position: { x: number, y: number, z: number }, zone?: string, [field: string]: any }} WorldRecord
|
|
230
|
+
*/
|
|
231
|
+
mixInternals(World);
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Spatial index for world: the xz plane is cut into fixed-size cells (default 32 m) and each record is filed under its cell. Distance queries and focus-based model building both pre-filter by cell.
|
|
2
|
+
// Cell keys are numbers and cells hold record objects directly: there are hundreds to thousands of moves and neighbor queries per step, and string keys plus id lookups would only add garbage and cost.
|
|
3
|
+
|
|
4
|
+
const OFF = 2 ** 20, SPAN = 2 ** 21; // ±1 million cells in each direction (±30,000 km at 32 m per cell); keys stay safe integers
|
|
5
|
+
|
|
6
|
+
/** @internal */
|
|
7
|
+
export class Cells {
|
|
8
|
+
/** @param {number} size cell edge length (meters) */
|
|
9
|
+
constructor(size) {
|
|
10
|
+
this.size = size;
|
|
11
|
+
this.map = new Map(); // cell key → Set<record> (deleted when empty, so walked-through areas leave no empty cells)
|
|
12
|
+
this.of = new Map(); // id → cell key
|
|
13
|
+
}
|
|
14
|
+
key(x, z) { return (Math.floor(x / this.size) + OFF) * SPAN + Math.floor(z / this.size) + OFF; }
|
|
15
|
+
/** Put into / move to the cell containing the position; returns true if the cell changed */
|
|
16
|
+
put(rec) {
|
|
17
|
+
const k = this.key(rec.position.x, rec.position.z), old = this.of.get(rec.id);
|
|
18
|
+
if (old === k) return false;
|
|
19
|
+
if (old !== undefined) this.out(old, rec);
|
|
20
|
+
let set = this.map.get(k); if (!set) this.map.set(k, set = new Set());
|
|
21
|
+
set.add(rec); this.of.set(rec.id, k);
|
|
22
|
+
return true;
|
|
23
|
+
}
|
|
24
|
+
delete(rec) { const k = this.of.get(rec.id); if (k !== undefined) this.out(k, rec); this.of.delete(rec.id); }
|
|
25
|
+
out(k, rec) { const set = this.map.get(k); set.delete(rec); if (!set.size) this.map.delete(k); }
|
|
26
|
+
clear() { this.map.clear(); this.of.clear(); }
|
|
27
|
+
/** Call fn(rec, squared distance) for each record within radius of c. No allocation, no sorting.
|
|
28
|
+
* When the circle covers more cells than exist (huge radius, even Infinity) scan all cells instead, so it cannot hang */
|
|
29
|
+
forEach(c, radius, fn) {
|
|
30
|
+
const s = this.size, r2 = radius * radius, cx = c.x, cz = c.z;
|
|
31
|
+
const x0 = Math.floor((cx - radius) / s), x1 = Math.floor((cx + radius) / s), z0 = Math.floor((cz - radius) / s), z1 = Math.floor((cz + radius) / s);
|
|
32
|
+
if ((x1 - x0 + 1) * (z1 - z0 + 1) > this.map.size) { for (const set of this.map.values()) visit(set, cx, cz, r2, fn); return; }
|
|
33
|
+
for (let x = x0; x <= x1; x++) for (let z = z0; z <= z1; z++) {
|
|
34
|
+
const set = this.map.get((x + OFF) * SPAN + z + OFF);
|
|
35
|
+
if (set) visit(set, cx, cz, r2, fn);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function visit(set, cx, cz, r2, fn) {
|
|
41
|
+
for (const rec of set) { const dx = rec.position.x - cx, dz = rec.position.z - cz, d2 = dx * dx + dz * dz; if (d2 <= r2) fn(rec, d2); }
|
|
42
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// World's contribution to thing.explain() (core/thingExplain.js): the record's fields as `state`, and the record's own collision / picking rules.
|
|
2
|
+
// Template rules come from the content module's explainer (content/explain.js), which runs after this and overrides these.
|
|
3
|
+
|
|
4
|
+
/** @internal Fill state and rules for a thing that has a world record */
|
|
5
|
+
export function worldExplain(e, t, out) {
|
|
6
|
+
const rec = e.world?.get(t.id);
|
|
7
|
+
if (!rec) return;
|
|
8
|
+
out.state = { ...t.fields, position: t.position };
|
|
9
|
+
Object.assign(out.rules, { blocksMovement: rec.collide ?? false, pickable: rec.static !== false, interact: null, note: RULES_NOTE });
|
|
10
|
+
}
|
|
11
|
+
export const RULES_NOTE = 'blocksMovement = the collision shape (box / circle) walkers stop at; blocking sight is not modelled by the engine';
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// world() module: installed as engine.world (world data, see World.js). Models load around engine.stream sources; records stay when models unload. Independent of game type: slow-life NPCs, shooter enemies, survival zombies and containers all use it.
|
|
2
|
+
// engine.use(world()) // the openWorld() preset installs it by default
|
|
3
|
+
// engine.use(world({ radius: 80 })) // distance (meters) for building models and counting as near, default 60
|
|
4
|
+
// Save key world (runtime records whole, initial records only changes and removals, see the top of World.js); emits world:load after loading. The loading screen waits for world.ready (nearby models all built). describe() reports world.total / byKind / presented, and nearby records with a name go into nearby.
|
|
5
|
+
import { recordSource } from './thingSource.js';
|
|
6
|
+
import { World } from './World.js';
|
|
7
|
+
import { WORLD_MIGRATE } from './persist.js';
|
|
8
|
+
import { worldExplain } from './explain.js';
|
|
9
|
+
import { closest, warnOnce, DEV } from '../../core/validate.js';
|
|
10
|
+
import { readParams, keysSchema } from '../../core/params.js';
|
|
11
|
+
|
|
12
|
+
const ORPHAN = '[world] the save has changes for {n} id(s) that the content no longer defines: {list}. They are kept in the save (restoring the entry brings them back); '
|
|
13
|
+
+ "if an entry was renamed, add the pair to content/renames.js (export default { 'oldId': 'newId' }) and the saved state follows it; 'oldId': null drops it";
|
|
14
|
+
const RENAME_TARGET = '[world] content/renames.js moves saved state to {list}, which no content entry defines: fix the new id (did you mean {near}?)';
|
|
15
|
+
|
|
16
|
+
const WORLD_PARAMS = keysSchema(['cellSize', 'radius', 'farEvery', 'farMaxPerTick', 'buildPerFrame']);
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* World data module: installed as engine.world. Put things here that must be saved, survive level changes and keep changing while far away; models are only built while nearby
|
|
20
|
+
* @example engine.use(world())
|
|
21
|
+
* @param {{ cellSize?: number, radius?: number, farEvery?: number, farMaxPerTick?: number, buildPerFrame?: number }} [opts]
|
|
22
|
+
* @returns {import('../../types/core').ModuleDef<World>}
|
|
23
|
+
*/
|
|
24
|
+
export function world(opts = {}) {
|
|
25
|
+
readParams('world', WORLD_PARAMS, opts);
|
|
26
|
+
let w = null;
|
|
27
|
+
return {
|
|
28
|
+
name: 'world', label: 'World data', params: WORLD_PARAMS, options: opts, stage: 'world',
|
|
29
|
+
install(e) {
|
|
30
|
+
w = new World(e, opts);
|
|
31
|
+
e.stream.player.at(() => w.center); // the default stream source sits where gameplay is simulated (world.anchor, else the player)
|
|
32
|
+
e.stream.readyCheck('world', s => s.detail !== 'full' || w.ready);
|
|
33
|
+
e.saves.register('world', { atomic: true, version: 3, migrate: WORLD_MIGRATE, save: () => w.toJSON(), load: d => w.fromJSON(d) });
|
|
34
|
+
e._things.addSource(recordSource(w)); // engine.thing / thing.set / the shared id space reach the records through this
|
|
35
|
+
e.explainWith(worldExplain);
|
|
36
|
+
e.budget.metric('worldRecords', () => w.records.size);
|
|
37
|
+
if (DEV) { // orphans are known once content loaded (engine:ready), after a load, and per level for `<level>/<node>` ids
|
|
38
|
+
const warn = () => {
|
|
39
|
+
targets();
|
|
40
|
+
const o = w.orphans(); if (!o.length) return;
|
|
41
|
+
const ids = [...w._base.keys()];
|
|
42
|
+
// a near id the save has no data for is the likely new name: suggest the exact renames.js pair
|
|
43
|
+
const list = o.slice(0, 8).map(id => { const c = closest(id, ids); return c ? `${id} (did you mean ${c}? renames: { '${id}': '${c}' })` : id; });
|
|
44
|
+
warnOnce(ORPHAN.replace('{n}', String(o.length)).replace('{list}', list.join(', ') + (o.length > 8 ? ', …' : '')));
|
|
45
|
+
};
|
|
46
|
+
const targets = () => { // a rename target nothing defines moves the player's state into a void: name it (level-node targets once that level loaded)
|
|
47
|
+
const due = id => { const i = id.indexOf('/'); return i < 0 || w._levels.has(id.slice(0, i)); };
|
|
48
|
+
const bad = [...w._renames].filter(([, b]) => b != null && !w._base.has(b) && due(b));
|
|
49
|
+
if (bad.length) warnOnce(RENAME_TARGET.replace('{list}', bad.map(([a, b]) => `${b} (from ${a})`).join(', ')).replace('{near}', closest(bad[0][1], [...w._base.keys()]) ?? '-'));
|
|
50
|
+
};
|
|
51
|
+
for (const ev of ['engine:ready', 'save:loaded', 'level:loaded']) e.events.on(ev, () => { if (e.ready) warn(); });
|
|
52
|
+
}
|
|
53
|
+
return w;
|
|
54
|
+
},
|
|
55
|
+
isReady() { return w.ready; },
|
|
56
|
+
afterLoad(e) { if (e.paused) w.refresh(); return w.whenReady; }, // a paused engine has no frames to build in: build now
|
|
57
|
+
counts() { let views = 0; for (const id of w.records.keys()) if (w.view(id)) views++; return { records: w.records.size, views }; }, // engine.counts().world
|
|
58
|
+
fixed(dt) { w.fixed(dt); },
|
|
59
|
+
skip(dt, e, done) { w._s.skip(dt, done); },
|
|
60
|
+
frame(dt) { w.frame(dt); },
|
|
61
|
+
describe(e, ctx) {
|
|
62
|
+
const byKind = {};
|
|
63
|
+
for (const r of w.records.values()) byKind[r.kind] = (byKind[r.kind] || 0) + 1;
|
|
64
|
+
// with a model, report by the model (merged with the interaction and other modules' reports on the same object into one entry); skip records of another zone (level)
|
|
65
|
+
for (const r of w.query({ near: ctx.center, radius: ctx.radius })) if (r.name != null && w._inZone(r)) ctx.near(w.view(r.id) ?? r.position, { id: r.id, name: r.name, kind: r.kind }, true);
|
|
66
|
+
const orphans = w.orphans();
|
|
67
|
+
return { total: w.records.size, byKind, presented: w._v.map.size, zone: w.zone, ...(orphans.length && { orphans: orphans.slice(0, 20) }) };
|
|
68
|
+
},
|
|
69
|
+
dispose() { w.dispose(); },
|
|
70
|
+
};
|
|
71
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// World saves and initial records. Rules (independent of the order of content.load):
|
|
2
|
+
// Things written in content (props, pickups, NPCs…) are initial records: add(def, { initial: true }), which needs a stable id.
|
|
3
|
+
// A save only keeps "which fields changed" and "which were removed" (tombstones) for them; runtime-created ones (a tree the player planted, a spawned monster) are saved whole.
|
|
4
|
+
// Load: runtime records are replaced wholesale by the save's; initial records first go back to their original content, then the save's changes are applied; records removed in the save do not reappear.
|
|
5
|
+
// Orphans: a change or removal in the save whose id the content no longer produces (renamed / deleted entry) is kept in _pending / _removed and
|
|
6
|
+
// written back by the next save, never dropped, so reverting the content change gets the player's data back; dev warns once (world.orphans()).
|
|
7
|
+
// Loading before content is loaded works too: changes and removals are remembered and applied / skipped when content is added. Things newly added to content after a game update still show up with an old save.
|
|
8
|
+
// Temporary things (data for effects, one-off spawns): add(def, { save: false }) — not saved, cleared on load.
|
|
9
|
+
// Changes are found by comparing JSON against the original content, not by events: fields changed directly inside simulate are saved too.
|
|
10
|
+
// Save format (part 'world', version 3): every record is keyed by its stable id, and only what play changed is stored:
|
|
11
|
+
// { seq, step, time, records: { id: whole runtime record without id }, changed: { id: { set?: changed fields, del?: [removed fields] } },
|
|
12
|
+
// removed: [ids of removed initial records], owed: { id: simulation seconds owed, only for kinds simulated with far } }
|
|
13
|
+
// Version 1 kept records as an array: migrate step 1 (WORLD_MIGRATE) turns it into the id-keyed object.
|
|
14
|
+
// Version 2 numbered runtime records `<kind>-<n>`; version 3 uses `<kind>#<n>`, so a runtime id can never equal an authored one (authored ids may not
|
|
15
|
+
// contain `#`, content/ids.js). Step 2 renames them (legacyRuntimeIds says which), and the containers part follows with the same map (a template
|
|
16
|
+
// instance's container is keyed by the record id).
|
|
17
|
+
// Removed fields are recorded separately (not saved as null): after loading it is "no such field", same as in a live run; a field that was null stays null.
|
|
18
|
+
// step / time are the simulation step count and accumulated seconds: far simulation takes turns by step-count buckets, so one save advances the same way every time (see sim.js).
|
|
19
|
+
|
|
20
|
+
import { legacyRuntimeIds, renameIdKeys, renameIdValues } from '../../core/saveIds.js';
|
|
21
|
+
|
|
22
|
+
const PLAIN_STRINGS = {
|
|
23
|
+
msg: 'world data must be plain values (number, string, boolean, array, plain object): {path} is {what}. Put models in world.present() and logic in world.simulate()',
|
|
24
|
+
fn: 'a function', obj: 'a three.js object', asset: 'a three.js asset', dom: 'a DOM element',
|
|
25
|
+
};
|
|
26
|
+
/** Dev-time check: data must not contain three.js objects, functions or DOM elements (saves can only store plain values) @internal */
|
|
27
|
+
export function checkPlain(v, path, depth = 0) {
|
|
28
|
+
const fail = what => { throw new Error(PLAIN_STRINGS.msg.replace('{path}', path).replace('{what}', what)); };
|
|
29
|
+
if (v == null || typeof v !== 'object') { if (typeof v === 'function') fail(PLAIN_STRINGS.fn); return; }
|
|
30
|
+
const what = v.isObject3D ? PLAIN_STRINGS.obj : v.isMaterial || v.isBufferGeometry || v.isTexture ? PLAIN_STRINGS.asset : typeof Element !== 'undefined' && v instanceof Element ? PLAIN_STRINGS.dom : null;
|
|
31
|
+
if (what) fail(what);
|
|
32
|
+
if (depth > 6) return;
|
|
33
|
+
for (const k in v) checkPlain(v[k], `${path}.${k}`, depth + 1);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Compare an initial record with its original: which top-level fields changed, which were removed (null if neither) */
|
|
37
|
+
function diff(rec, base) {
|
|
38
|
+
let set = null, del = null;
|
|
39
|
+
for (const k in rec) {
|
|
40
|
+
if (rec[k] === undefined) { if (k in base) (del ||= []).push(k); continue; } // set to undefined = removed
|
|
41
|
+
if (JSON.stringify(rec[k]) !== JSON.stringify(base[k])) (set ||= {})[k] = rec[k];
|
|
42
|
+
}
|
|
43
|
+
for (const k in base) if (!(k in rec)) (del ||= []).push(k);
|
|
44
|
+
return set || del ? { set: set ?? undefined, del: del ?? undefined } : null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Upgrade steps of the world save part (saves.register version 3) @internal */
|
|
48
|
+
export const WORLD_MIGRATE = {
|
|
49
|
+
1: d => ({ ...d, records: Object.fromEntries((d?.records || []).map(({ id, ...r }) => [id, r])) }), // array of records -> keyed by id
|
|
50
|
+
2: d => { // runtime ids `<kind>-<n>` -> `<kind>#<n>`: record keys, owed keys, and field values that name a renamed record
|
|
51
|
+
const map = legacyRuntimeIds(d);
|
|
52
|
+
if (!map.size) return d;
|
|
53
|
+
return { ...d, records: renameIdValues(renameIdKeys(d.records, map), map), changed: renameIdValues(d.changed, map), owed: renameIdKeys(d.owed, map) };
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
/** @param {import('./World.js').World} w @internal */
|
|
60
|
+
export function saveWorld(w) {
|
|
61
|
+
const records = {}, changed = {};
|
|
62
|
+
for (const rec of w.records.values()) {
|
|
63
|
+
if (w._unsaved.has(rec.id)) continue;
|
|
64
|
+
const base = w._base.get(rec.id);
|
|
65
|
+
if (!base) { const { id, ...r } = rec; records[id] = r; continue; }
|
|
66
|
+
const d = diff(rec, base);
|
|
67
|
+
if (d) changed[rec.id] = d;
|
|
68
|
+
}
|
|
69
|
+
for (const [id, d] of w._pending) changed[id] = d; // from a save, content not loaded yet this time (e.g. another level): keep as is
|
|
70
|
+
return { seq: w._seq, ...w._s.toJSON(), records, changed, removed: [...w._removed] };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Load: replace runtime records wholesale; loaded initial records go back to the original then get the save's changes; unloaded content waits for its add. Independent of the order of content.load @internal */
|
|
74
|
+
export function loadWorld(w, d) {
|
|
75
|
+
w._v.clear();
|
|
76
|
+
w.records.clear(); w._cells.clear(); w._unsaved.clear();
|
|
77
|
+
for (const id of [...w._origin.keys()]) if (!w._base.has(id)) w._origin.delete(id); // runtime records come from the save now (no op to name)
|
|
78
|
+
w._seq = d?.seq ?? 0;
|
|
79
|
+
w._removed = new Set(d?.removed);
|
|
80
|
+
w._pending = new Map(Object.entries(d?.changed || {}));
|
|
81
|
+
w._s.fromJSON(d);
|
|
82
|
+
renamePending(w); // content/renames.js, before initial records take their diffs
|
|
83
|
+
for (const [id, base] of w._base) if (!w._removed.has(id)) w._insert(w._fromBase(id, base));
|
|
84
|
+
for (const [id, r] of Object.entries(d?.records || {})) w._insert({ id, ...r });
|
|
85
|
+
w.engine.events.emit('world:load', { count: w.records.size });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Apply content/renames.js to the save data waiting for content: changed fields (_pending), removals (_removed) and owed simulation time move from the old
|
|
90
|
+
* id to the new one; a null target drops them (deleted on purpose, so they are no orphans). Skipped, and returned as 'old (why)', when the old id is still
|
|
91
|
+
* authored (the rename would steal its data) or the new id already has saved data (two saves' worth of state cannot merge): those stay orphans. @internal
|
|
92
|
+
* @param {import('./World.js').World} w
|
|
93
|
+
* @returns {string[]}
|
|
94
|
+
*/
|
|
95
|
+
export function renamePending(w) {
|
|
96
|
+
const stuck = [], owed = w._s.owed;
|
|
97
|
+
for (const [a, b] of w._renames) {
|
|
98
|
+
const has = w._pending.has(a) || w._removed.has(a) || owed.has(a);
|
|
99
|
+
if (!has) continue;
|
|
100
|
+
if (w._base.has(a)) { stuck.push(`${a} (still defined by content)`); continue; }
|
|
101
|
+
if (b != null && (w._pending.has(b) || w._removed.has(b) || owed.has(b))) { stuck.push(`${a} (${b} already has saved changes)`); continue; }
|
|
102
|
+
if (w._pending.has(a)) { if (b != null) w._pending.set(b, w._pending.get(a)); w._pending.delete(a); }
|
|
103
|
+
if (w._removed.delete(a) && b != null) w._removed.add(b);
|
|
104
|
+
if (owed.has(a)) { if (b != null) owed.set(b, owed.get(a)); owed.delete(a); }
|
|
105
|
+
}
|
|
106
|
+
return stuck;
|
|
107
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Position read / write for world: shared by add / move / query. A wrong position (a Vector3 used as an array, [x, z] with only two numbers) silently becomes NaN and null in the save,
|
|
2
|
+
// so dev builds throw on the spot and say how to fix it.
|
|
3
|
+
import { DEV } from '../../core/validate.js';
|
|
4
|
+
|
|
5
|
+
const STRINGS = {
|
|
6
|
+
arr: '{fn}: an array position must be [x, y, z] (three numbers); for a horizontal position only, write { x, z }',
|
|
7
|
+
nan: '{fn}: position is not a valid number (got {got}). Common cause: a Vector3 used as an array (v[0] is undefined); write v.x / v.z, or pass the Vector3 itself',
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
/** Write position v (Vector3 / object / [x, y, z] / { x, z }) into p; y stays unchanged if omitted @internal */
|
|
11
|
+
export function putPos(fn, v, p) {
|
|
12
|
+
const arr = Array.isArray(v), o = v.isObject3D ? v.position : v;
|
|
13
|
+
if (DEV && arr && v.length !== 3) throw new Error(STRINGS.arr.replace('{fn}', fn));
|
|
14
|
+
const x = arr ? v[0] : o.x, y = arr ? v[1] : o.y ?? p.y, z = arr ? v[2] : o.z;
|
|
15
|
+
// check before writing: a bad position leaves no half-written NaN in the data
|
|
16
|
+
if (DEV && !(Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z))) throw new Error(STRINGS.nan.replace('{fn}', fn).replace('{got}', JSON.stringify(v)));
|
|
17
|
+
p.x = x; p.y = y; p.z = z;
|
|
18
|
+
}
|
|
19
|
+
/** Query center: objects use position, arrays are [x, y, z], others (Vector3 / { x, z }) are used as is, no allocation @internal */
|
|
20
|
+
export const centerOf = c => c.isObject3D ? c.position : Array.isArray(c) ? { x: c[0], z: c[2] } : c;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// World record mutations (add / rest / orphans / set / remove): the bodies behind the World methods of the same names. World.js keeps the public
|
|
2
|
+
// JSDoc and signatures; these functions take the world as `w` and reach its internals the same way sim.js / views.js / persist.js do.
|
|
3
|
+
import { DEV, checkOptionsArg, fmt } from '../../core/validate.js';
|
|
4
|
+
import { checkPlain } from './persist.js';
|
|
5
|
+
import { putPos, centerOf } from './pos.js';
|
|
6
|
+
import { claimId } from '../../core/things.js';
|
|
7
|
+
|
|
8
|
+
export const STRINGS = {
|
|
9
|
+
noKind: 'world.add() needs a kind (what sort of thing this is), e.g. world.add({ kind: "crate", position: [0, 0, 0] })',
|
|
10
|
+
dupId: 'world.add(): id "{id}" already exists. Omit id to auto-number; to change an existing record use world.set("{id}", { … })',
|
|
11
|
+
initialId: 'world.add(def, { initial: true }) needs a stable id (saves match content by id), e.g. world.add({ id: "chest_1", kind: "{kind}", … }, { initial: true })',
|
|
12
|
+
noId: 'world.{fn}(): no record with id "{id}" (world.query({ kind }) lists what exists)',
|
|
13
|
+
setKey: 'world.set("{id}", patch): patch must not contain id / kind (they are the identity of the record). To change the kind, remove then add',
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export function addRecord(w, def, opts) {
|
|
17
|
+
DEV && w.engine.ops.guard('world.add');
|
|
18
|
+
if (!def?.kind) throw new Error(STRINGS.noKind);
|
|
19
|
+
if (DEV) { checkOptionsArg('world.add(def, opts)', opts, ['initial', 'save']); checkPlain({ ...def, position: undefined }, def.kind); }
|
|
20
|
+
const { id: given, kind, position, ...rest } = def, initial = !!opts?.initial;
|
|
21
|
+
if (initial && given == null) throw new Error(fmt(STRINGS.initialId, { kind }));
|
|
22
|
+
const id = given ?? `${kind}#${++w._seq}`, have = w.records.get(id), p = { x: 0, y: 0, z: 0 };
|
|
23
|
+
if (position) putPos('world.add()', position, p);
|
|
24
|
+
const rec = { id, kind, position: p, ...rest };
|
|
25
|
+
if (initial) {
|
|
26
|
+
if (!w._base.has(id)) w._base.set(id, structuredClone(rec));
|
|
27
|
+
if (have) return have;
|
|
28
|
+
claimId(w.engine, id);
|
|
29
|
+
if (w._removed.has(id)) return null;
|
|
30
|
+
return w._insert(w._fromBase(id, w._base.get(id)), true);
|
|
31
|
+
}
|
|
32
|
+
if (have) throw new Error(fmt(STRINGS.dupId, { id }));
|
|
33
|
+
claimId(w.engine, id);
|
|
34
|
+
if (opts?.save === false) w._unsaved.add(id);
|
|
35
|
+
if (DEV) w._origin.set(id, { spawned: { op: w.engine.ops.running, tick: w.engine.tick } }); // who made it (inspect / pick)
|
|
36
|
+
return w._insert(rec, true);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function restRecord(w, id, position, tolerance) {
|
|
40
|
+
const rec = w.records.get(id), base = w._base.get(id); if (!rec) return;
|
|
41
|
+
const a = rec.position, b = base?.position;
|
|
42
|
+
const same = !!b && Math.abs(a.x - b.x) <= tolerance && Math.abs(a.y - b.y) <= tolerance && Math.abs(a.z - b.z) <= tolerance;
|
|
43
|
+
putPos(`world.rest("${id}")`, position, rec.position); w._index(rec);
|
|
44
|
+
if (same) base.position = { ...rec.position };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function orphanIds(w) {
|
|
48
|
+
const out = [], known = id => w._base.has(id) || w.records.has(id);
|
|
49
|
+
const due = id => { const i = id.indexOf('/'); return i < 0 || w._levels.has(id.slice(0, i)); };
|
|
50
|
+
for (const id of w._pending.keys()) if (!known(id) && due(id)) out.push(id);
|
|
51
|
+
for (const id of w._removed) if (!known(id) && !w._base.has(id) && due(id)) out.push(id);
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function setRecord(w, id, patch) {
|
|
56
|
+
DEV && w.engine.ops.guard('world.set');
|
|
57
|
+
const rec = w._need(id, 'set');
|
|
58
|
+
if (DEV) { if ('id' in patch || 'kind' in patch) throw new Error(fmt(STRINGS.setKey, { id })); checkPlain({ ...patch, position: undefined }, id); }
|
|
59
|
+
const { position, ...rest } = patch;
|
|
60
|
+
Object.assign(rec, rest);
|
|
61
|
+
if (position) w.move(id, position);
|
|
62
|
+
if (w._v.presenters.get(rec.kind)?.show) w._v.dirty = true;
|
|
63
|
+
w.engine.events.emit('world:change', { id, kind: rec.kind, keys: Object.keys(patch) });
|
|
64
|
+
return rec;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function removeRecord(w, id) {
|
|
68
|
+
DEV && w.engine.ops.guard('world.remove');
|
|
69
|
+
const rec = w.records.get(id); if (!rec) return;
|
|
70
|
+
w._v.unview(id);
|
|
71
|
+
w._cells.delete(rec);
|
|
72
|
+
w.records.delete(id);
|
|
73
|
+
w._s.removed(id);
|
|
74
|
+
w._unsaved.delete(id);
|
|
75
|
+
if (w._base.has(id)) w._removed.add(id); else w._origin.delete(id);
|
|
76
|
+
w.engine.events.emit('world:remove', { id, kind: rec.kind });
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function queryRecords(w, opts) {
|
|
80
|
+
const { kind, near, radius = 30, where, zone } = opts, out = [];
|
|
81
|
+
const ok = r => (!kind || r.kind === kind) && (zone === undefined || (r.zone ?? null) === zone) && (!where || where(r));
|
|
82
|
+
if (near) {
|
|
83
|
+
w._cells.forEach(centerOf(near), radius, (r, d2) => { if (ok(r)) out.push([d2, r]); });
|
|
84
|
+
return out.sort((a, b) => a[0] - b[0]).map(a => a[1]);
|
|
85
|
+
}
|
|
86
|
+
if (!kind) return [...w.records.values()].filter(ok);
|
|
87
|
+
for (const e of w._s.kinds.get(kind)?.set ?? []) if (ok(e.rec)) out.push(e.rec); // table grouped by kind: no full scan
|
|
88
|
+
return out;
|
|
89
|
+
}
|