threedog 0.7.0 → 1.0.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 +411 -1
- package/README.md +8 -11
- package/core/{Animator.js → assets/Animator.js} +30 -18
- package/core/{Assets.js → assets/Assets.js} +131 -56
- package/core/{Baked.js → assets/Baked.js} +4 -4
- package/core/assets/assetEntry.js +302 -0
- package/core/{assetHot.js → assets/assetHot.js} +9 -7
- package/core/{assetLoad.js → assets/assetLoad.js} +55 -16
- package/core/assets/assetLod.js +113 -0
- package/core/{assetManifest.js → assets/assetManifest.js} +19 -11
- package/core/{assetReport.js → assets/assetReport.js} +7 -14
- package/core/{namedModel.js → assets/namedModel.js} +17 -13
- package/core/{Audio.js → audio/Audio.js} +47 -25
- package/core/{audioRules.js → audio/audioRules.js} +8 -5
- package/core/{audioVoice.js → audio/audioVoice.js} +17 -30
- package/core/{Events.js → base/Events.js} +3 -3
- package/core/{I18n.js → base/I18n.js} +15 -12
- package/core/{Random.js → base/Random.js} +7 -4
- package/core/{Vars.js → base/Vars.js} +14 -4
- package/core/{easing.js → base/easing.js} +1 -1
- package/core/{errorCodes.js → base/errorCodes.js} +151 -125
- package/core/{errorHints.js → base/errorHints.js} +17 -10
- package/core/{errors.js → base/errors.js} +12 -10
- package/core/{events.generated.js → base/events.generated.js} +11 -0
- package/core/base/follows.js +26 -0
- package/core/base/math.js +66 -0
- package/core/{params.js → base/params.js} +5 -6
- package/core/base/saveValues.js +81 -0
- package/core/base/sections.js +97 -0
- package/core/base/spelling.js +32 -0
- package/core/base/util.js +32 -0
- package/core/{validate.js → base/validate.js} +34 -34
- package/core/{Engine.js → engine/Engine.js} +137 -91
- package/core/{Loading.js → engine/Loading.js} +34 -5
- package/core/{copies.js → engine/copies.js} +4 -4
- package/core/{headlessLoad.js → engine/headlessLoad.js} +32 -15
- package/core/{lifecycle.js → engine/lifecycle.js} +41 -34
- package/core/{loop.js → engine/loop.js} +88 -49
- package/core/engine/moduleSlots.js +176 -0
- package/core/{moduleTypes.js → engine/moduleTypes.js} +26 -14
- package/core/engine/modules.js +503 -0
- package/core/{page.js → engine/page.js} +59 -29
- package/core/{plugins.js → engine/plugins.js} +21 -12
- package/core/{services.js → engine/services.js} +50 -40
- package/core/{startup.js → engine/startup.js} +66 -54
- package/core/{Input.js → input/Input.js} +67 -39
- package/core/{inputContext.js → input/inputContext.js} +14 -5
- package/core/input/inputKeyboard.js +39 -0
- package/core/{inputPad.js → input/inputPad.js} +24 -3
- package/core/{inputPointer.js → input/inputPointer.js} +11 -3
- package/core/input/inputSeat.js +66 -0
- package/core/{inputTouch.js → input/inputTouch.js} +24 -7
- package/core/{Budget.js → inspect/Budget.js} +21 -20
- package/core/{DebugOverrides.js → inspect/DebugOverrides.js} +43 -18
- package/core/{Describe.js → inspect/Describe.js} +34 -26
- package/core/{Inspect.js → inspect/Inspect.js} +39 -10
- package/core/{InspectMaterials.js → inspect/InspectMaterials.js} +7 -8
- package/core/{InspectPerf.js → inspect/InspectPerf.js} +19 -13
- package/core/{InspectScene.js → inspect/InspectScene.js} +8 -5
- package/core/{MaterialInfo.js → inspect/MaterialInfo.js} +3 -2
- package/core/{UrlState.js → inspect/UrlState.js} +60 -24
- package/core/{catalog.js → inspect/catalog.js} +15 -8
- package/core/{checks.js → inspect/checks.js} +7 -5
- package/core/{debugView.js → inspect/debugView.js} +4 -4
- package/core/{describeRender.js → inspect/describeRender.js} +24 -22
- package/core/{describeText.js → inspect/describeText.js} +17 -8
- package/core/inspect/geometryWatch.js +38 -0
- package/core/{lightWatch.js → inspect/lightWatch.js} +8 -8
- package/core/inspect/metadata.generated.js +4140 -0
- package/core/{pictureWriters.js → inspect/pictureWriters.js} +130 -47
- package/core/{shaderCost.js → inspect/shaderCost.js} +1 -1
- package/core/inspect/toolDoor.js +21 -0
- package/core/inspect/valueHistory.js +35 -0
- package/core/{Ops.js → ops/Ops.js} +44 -14
- package/core/{control.js → ops/control.js} +57 -31
- package/core/ops/holds.js +140 -0
- package/core/{opsAtomic.js → ops/opsAtomic.js} +18 -5
- package/core/{opsCheck.js → ops/opsCheck.js} +11 -10
- package/core/{opsFail.js → ops/opsFail.js} +5 -7
- package/core/{opsGuard.js → ops/opsGuard.js} +3 -3
- package/core/{opsRun.js → ops/opsRun.js} +9 -6
- package/core/{owned.js → ops/owned.js} +33 -19
- package/core/{sharedPoint.js → ops/sharedPoint.js} +13 -16
- package/core/{stackFrames.js → ops/stackFrames.js} +2 -2
- package/core/{stacks.js → ops/stacks.js} +34 -15
- package/core/{wrap.js → ops/wrap.js} +8 -6
- package/core/{SaveStore.js → saves/SaveStore.js} +53 -27
- package/core/{Saves.js → saves/Saves.js} +171 -54
- package/core/saves/saveApply.js +312 -0
- package/core/{saveFiles.js → saves/saveFiles.js} +45 -38
- package/core/{saveVersions.js → saves/saveVersions.js} +24 -23
- package/core/saves/session.js +231 -0
- package/core/saves/stateReplace.js +184 -0
- package/core/{Rays.js → scene/Rays.js} +44 -30
- package/core/{Views.js → scene/Views.js} +16 -8
- package/core/{adaptive.js → scene/adaptive.js} +19 -9
- package/core/{canvasBox.js → scene/canvasBox.js} +4 -3
- package/core/scene/compositeGround.js +72 -0
- package/core/scene/floor.js +17 -0
- package/core/{gameLights.js → scene/gameLights.js} +17 -7
- package/core/{grayMap.js → scene/grayMap.js} +8 -2
- package/core/{grid.js → scene/grid.js} +6 -4
- package/core/{gridLoad.js → scene/gridLoad.js} +1 -1
- package/core/scene/ground.contract.js +14 -0
- package/core/scene/ground.js +139 -0
- package/core/{movement.js → scene/movement.js} +3 -3
- package/core/{pictureSlots.js → scene/pictureSlots.js} +2 -2
- package/core/scene/pixel.js +154 -0
- package/core/scene/pixelRatio.js +167 -0
- package/core/{sceneDelta.js → scene/sceneDelta.js} +5 -5
- package/core/{sceneMethods.js → scene/sceneMethods.js} +43 -15
- package/core/scene/stepPoses.js +60 -0
- package/core/{targeting.js → scene/targeting.js} +4 -5
- package/core/{thingExplain.js → scene/thingExplain.js} +7 -6
- package/core/{thingOps.js → scene/thingOps.js} +25 -16
- package/core/{things.js → scene/things.js} +18 -5
- package/core/{threePatches.js → scene/threePatches.js} +1 -1
- package/core/{tier.js → scene/tier.js} +10 -0
- package/core/scene/view.js +161 -0
- package/core/{Batching.js → stream/Batching.js} +85 -28
- package/core/{Stream.js → stream/Stream.js} +80 -38
- package/core/{batchGroups.js → stream/batchGroups.js} +11 -9
- package/core/{chunkStream.js → stream/chunkStream.js} +40 -0
- package/core/{scatter.js → stream/scatter.js} +7 -4
- package/core/{streamSources.js → stream/streamSources.js} +14 -8
- package/core/{Commits.js → threads/Commits.js} +17 -11
- package/core/{Jobs.js → threads/Jobs.js} +25 -13
- package/core/{Threads.js → threads/Threads.js} +21 -18
- package/core/{threadPure.js → threads/threadPure.js} +7 -5
- package/core/{threadServe.js → threads/threadServe.js} +3 -3
- package/core/{Clock.js → time/Clock.js} +20 -11
- package/core/{dayTime.js → time/dayTime.js} +5 -1
- package/core/{skip.js → time/skip.js} +28 -21
- package/core/{time.js → time/time.js} +32 -20
- package/core/{uiClock.js → time/uiClock.js} +4 -4
- package/docs/AI.md +92 -72
- package/docs/API.md +33 -28
- package/docs/CODEMAP.md +121 -200
- package/docs/COMMANDS.md +77 -70
- package/docs/CONVENTIONS.md +167 -24
- package/docs/MIGRATING-0.8.md +171 -0
- package/docs/MIGRATING-1.0.md +101 -0
- package/docs/THREE.md +140 -38
- package/docs/api/assets.md +12 -13
- package/docs/api/audio.md +6 -5
- package/docs/api/budget.md +4 -4
- package/docs/api/calendar.md +10 -11
- package/docs/api/cameraRig.md +32 -29
- package/docs/api/characters.md +35 -24
- package/docs/api/clock.md +1 -1
- package/docs/api/collider3d.md +9 -0
- package/docs/api/collision.md +12 -9
- package/docs/api/content.md +18 -17
- package/docs/api/dialogue.md +5 -4
- package/docs/api/engine.md +58 -54
- package/docs/api/events.md +17 -6
- package/docs/api/flow.md +1 -1
- package/docs/api/grids.md +1 -1
- package/docs/api/ground.md +6 -7
- package/docs/api/hud.md +2 -2
- package/docs/api/i18n.md +6 -6
- package/docs/api/input.md +9 -8
- package/docs/api/interactions.md +5 -5
- package/docs/api/inventory.md +10 -10
- package/docs/api/jobs.md +5 -5
- package/docs/api/level.md +10 -9
- package/docs/api/lightPool.md +1 -6
- package/docs/api/music.md +3 -3
- package/docs/api/nav.md +14 -12
- package/docs/api/openWorld.md +1 -1
- package/docs/api/particles.md +10 -7
- package/docs/api/photo.md +4 -2
- package/docs/api/pickups.md +3 -3
- package/docs/api/post.md +21 -5
- package/docs/api/quests.md +7 -5
- package/docs/api/rays.md +7 -7
- package/docs/api/rigid.md +29 -19
- package/docs/api/saves.md +13 -11
- package/docs/api/settings.md +9 -8
- package/docs/api/sky.md +8 -7
- package/docs/api/stream.md +8 -9
- package/docs/api/swarm.md +34 -0
- package/docs/api/terrain.md +6 -8
- package/docs/api/terrainDraw.md +2 -2
- package/docs/api/timeline.md +4 -4
- package/docs/api/tools.md +27 -22
- package/docs/api/triggers.md +2 -0
- package/docs/api/vars.md +1 -1
- package/docs/api/vegetation.md +4 -3
- package/docs/api/vegetationDraw.md +2 -2
- package/docs/api/water.md +7 -3
- package/docs/api/weather.md +27 -12
- package/docs/api/weatherDraw.md +4 -4
- package/docs/api/world.md +6 -6
- package/docs/recipes/01-new-game.md +28 -43
- package/docs/recipes/02-npc.md +21 -23
- package/docs/recipes/03-items-pickups.md +37 -53
- package/docs/recipes/04-quests.md +5 -4
- package/docs/recipes/05-props-bake.md +34 -44
- package/docs/recipes/06-clock-events.md +31 -22
- package/docs/recipes/07-flow-scenes-pause.md +30 -32
- package/docs/recipes/08-weather-sky.md +91 -37
- package/docs/recipes/09-materials-lights-models.md +25 -39
- package/docs/recipes/10-blender-level.md +22 -11
- package/docs/recipes/11-vehicles.md +44 -24
- package/docs/recipes/12-navmesh.md +60 -15
- package/docs/recipes/13-animation.md +70 -22
- package/docs/recipes/14-custom-module.md +33 -20
- package/docs/recipes/15-perf.md +51 -28
- package/docs/recipes/16-dev-bridge.md +39 -58
- package/docs/recipes/18-world.md +49 -28
- package/docs/recipes/19-shooting-picking.md +7 -4
- package/docs/recipes/20-content-actions-save.md +55 -40
- package/docs/recipes/21-camera.md +47 -25
- package/docs/recipes/22-shop-gold.md +21 -16
- package/docs/recipes/23-ops.md +28 -24
- package/docs/recipes/26-ui-parts.md +25 -14
- package/docs/recipes/27-net.md +3 -5
- package/docs/recipes/28-terrain.md +119 -23
- package/docs/recipes/29-grid.md +3 -3
- package/docs/recipes/30-templates.md +63 -30
- package/docs/recipes/31-audio.md +7 -7
- package/docs/recipes/32-action-game.md +21 -11
- package/docs/recipes/33-stream-sources.md +6 -3
- package/docs/recipes/34-environment-lighting.md +72 -25
- package/docs/recipes/35-picture-from-reference.md +20 -23
- package/docs/recipes/36-ground-plants.md +106 -0
- package/docs/recipes/40-scene.md +18 -21
- package/docs/recipes/43-shader-patches-surfaces.md +27 -48
- package/docs/recipes/44-water-weather-hooks.md +56 -50
- package/docs/recipes/45-cascaded-shadows.md +41 -20
- package/docs/recipes/46-blender-art-route.md +9 -10
- package/docs/recipes/49-game-module-contract.md +7 -6
- package/docs/recipes/50-own-renderer.md +3 -2
- package/docs/recipes/51-capability-catalog.md +14 -8
- package/docs/recipes/52-around-the-picture.md +56 -100
- package/docs/recipes/53-ground-up-close.md +61 -24
- package/docs/recipes/55-mods-time-wrap.md +17 -20
- package/docs/recipes/56-webgpu-tsl.md +28 -15
- package/docs/recipes/57-control.md +39 -12
- package/docs/recipes/58-input.md +15 -2
- package/docs/recipes/59-depth-post-effects.md +1 -1
- package/docs/recipes/60-judge-the-picture.md +30 -25
- package/docs/recipes/62-picture-code.md +129 -39
- package/docs/recipes/63-third-person-start.md +19 -5
- package/docs/recipes/64-particles.md +54 -5
- package/docs/recipes/65-swarm.md +140 -0
- package/docs/recipes/66-common-tasks.md +313 -0
- package/examples/action/.threedog/content-index.json +1 -1
- package/examples/action/GAMEMAP.md +5 -5
- package/examples/perf-island/.threedog/content-index.json +1 -0
- package/examples/{sheepisland → perf-island}/GAMEMAP.md +15 -14
- package/examples/{sheepisland → perf-island}/assets.js +1 -1
- package/examples/{sheepisland → perf-island}/main.js +8 -8
- package/examples/{sheepisland → perf-island}/models.js +1 -1
- package/examples/{sheepisland → perf-island}/params.js +1 -1
- package/examples/{sheepisland → perf-island}/picture/index.js +1 -1
- package/examples/{sheepisland → perf-island}/picture/palette.js +2 -2
- package/examples/{sheepisland → perf-island}/views.js +1 -1
- package/examples/plain-picture/GAMEMAP.md +4 -1
- package/examples/rc2d/GAMEMAP.md +4 -3
- package/examples/rc2d/main.js +1 -3
- package/examples/rc2d/rc2d.js +1 -1
- package/examples/styletest/.threedog/content-index.json +1 -1
- package/examples/styletest/GAMEMAP.md +6 -5
- package/examples/techniques/contact-shadows/contactShadows.js +1 -1
- package/examples/techniques/contact-shadows/main.js +1 -1
- package/examples/techniques/interior-light/main.js +1 -1
- package/examples/techniques/modular-building/README.md +7 -6
- package/examples/techniques/outlines-and-rim/picture/post.js +1 -1
- package/examples/techniques/procedural-animation/README.md +1 -1
- package/examples/webgpu-tsl/GAMEMAP.md +2 -1
- package/examples/world/.threedog/content-index.json +1 -1
- package/examples/world/GAMEMAP.md +9 -7
- package/examples/world/main.js +3 -3
- package/examples/world/picture/sky.js +1 -1
- package/index.d.ts +16 -12
- package/index.js +53 -32
- package/llms.txt +11 -14
- package/modules/ambience/Ambience.js +16 -11
- package/modules/calendar/Calendar.js +19 -19
- package/modules/calendar/index.js +18 -16
- package/modules/calendar/schedule.js +11 -6
- package/modules/calendar/seasons.js +7 -7
- package/modules/camera/FirstPersonCamera.js +5 -5
- package/modules/camera/FixedCamera.js +43 -30
- package/modules/camera/FollowCamera.js +24 -15
- package/modules/camera/RtsCamera.js +12 -11
- package/modules/camera/common.js +72 -37
- package/modules/camera/contract.js +1 -0
- package/modules/camera/pixelSnap.js +62 -0
- package/modules/characters/Character.js +166 -70
- package/modules/characters/NPC.js +84 -44
- package/modules/characters/assetModel.js +16 -12
- package/modules/characters/astar.js +48 -27
- package/modules/characters/behaviors.js +4 -5
- package/modules/characters/character.contract.js +21 -0
- package/modules/characters/contract.js +17 -3
- package/modules/characters/index.js +240 -226
- package/modules/characters/moveHelpers.js +88 -12
- package/modules/characters/mover.contract.js +14 -0
- package/modules/characters/movers/common.js +22 -18
- package/modules/characters/movers/manual.js +1 -1
- package/modules/characters/movers/rapier.js +18 -10
- package/modules/characters/movers/simple.js +26 -13
- package/modules/characters/movers/support.js +24 -13
- package/modules/characters/npcAvoid.js +19 -16
- package/modules/characters/npcSim.js +88 -32
- package/modules/characters/npcView.js +19 -11
- package/modules/characters/pathAsync.js +81 -29
- package/modules/characters/pathJob.js +38 -21
- package/modules/characters/pathWorker.js +1 -1
- package/modules/characters/player.js +120 -0
- package/modules/characters/playerStrings.js +2 -2
- package/modules/characters/proceduralRig.js +2 -2
- package/modules/characters/seat.js +56 -0
- package/modules/characters/useModel.js +3 -3
- package/modules/characters/vehicle.contract.js +8 -5
- package/modules/characters/walkTo.js +40 -33
- package/modules/collision/Collision.js +69 -45
- package/modules/collision/contract.js +15 -0
- package/modules/collision/grid.js +6 -1
- package/modules/content/explain.js +2 -3
- package/modules/content/fields.js +24 -3
- package/modules/content/ids.js +5 -3
- package/modules/content/index.js +132 -114
- package/modules/content/loader.js +117 -140
- package/modules/content/markers.js +25 -0
- package/modules/content/models.js +54 -17
- package/modules/content/packs.js +5 -4
- package/modules/content/parts.js +2 -2
- package/modules/content/places.js +36 -0
- package/modules/content/props.js +22 -17
- package/modules/content/rules.js +47 -61
- package/modules/content/stages.js +7 -7
- package/modules/content/templates.js +80 -49
- package/modules/content/words.js +47 -0
- package/modules/debug/DebugPanel.js +14 -45
- package/modules/flow/contract.js +2 -1
- package/modules/flow/index.js +30 -16
- package/modules/gameplay/Container.js +17 -13
- package/modules/gameplay/Containers.js +23 -6
- package/modules/gameplay/Dialogue.js +93 -34
- package/modules/gameplay/Interactions.js +93 -51
- package/modules/gameplay/Inventory.js +64 -22
- package/modules/gameplay/Quests.js +146 -30
- package/modules/gameplay/boxOps.js +8 -1
- package/modules/gameplay/dialogueBubbles.js +16 -12
- package/modules/gameplay/inventoryOps.js +11 -8
- package/modules/gameplay/pickups.js +63 -37
- package/modules/gameplay/questLog.js +4 -2
- package/modules/gameplay/questSave.js +9 -4
- package/modules/gameplay/quests.contract.js +1 -1
- package/modules/grid/Grid.js +2 -2
- package/modules/grid/Layer.js +12 -8
- package/modules/grid/index.js +28 -23
- package/modules/grid/ops.js +43 -46
- package/modules/grid/preview.js +7 -7
- package/modules/grid/tiles.js +6 -6
- package/modules/hlod/index.js +42 -57
- package/modules/hud/index.js +22 -14
- package/modules/hud/parts.js +8 -8
- package/modules/level/contract.js +16 -0
- package/modules/level/heightfield.js +29 -31
- package/modules/level/index.js +113 -161
- package/modules/level/load.js +196 -0
- package/modules/level/meshes.js +65 -0
- package/modules/level/nodes.js +40 -23
- package/modules/lights/index.js +33 -183
- package/modules/lights/slots.js +93 -0
- package/modules/lights/sources.js +90 -0
- package/modules/music/Music.js +34 -28
- package/modules/music/rules.js +1 -1
- package/modules/nav/contract.js +16 -0
- package/modules/nav/index.js +180 -49
- package/modules/nav/navPath.js +45 -10
- package/modules/net/Client.js +7 -7
- package/modules/net/Host.js +7 -7
- package/modules/net/Net.js +1 -1
- package/modules/net/index.js +6 -5
- package/modules/net/sync.js +2 -2
- package/modules/net/transports.js +2 -2
- package/modules/particles/Particles.js +95 -29
- package/modules/particles/effect.js +86 -32
- package/modules/particles/shaders.js +19 -1
- package/modules/photo/Photo.js +23 -23
- package/modules/rigid/RigidBodies.js +255 -89
- package/modules/rigid/Vehicles.js +17 -8
- package/modules/rigid/collider3d.contract.js +26 -0
- package/modules/rigid/ragdoll.js +298 -0
- package/modules/rigid/ragdollBones.js +209 -0
- package/modules/rigid/refresh.js +10 -0
- package/modules/rigid/sync.js +51 -20
- package/modules/settings/Settings.js +177 -61
- package/modules/settings/apply.js +20 -13
- package/modules/settings/sections.js +19 -14
- package/modules/settings/strings.js +2 -2
- package/modules/settings/view.js +3 -3
- package/modules/sky/Sky.js +29 -22
- package/modules/sky/clouds.js +7 -7
- package/modules/sky/dome.js +33 -20
- package/modules/sky/domeLayers.js +9 -9
- package/modules/sky/environment.js +6 -6
- package/modules/sky/frame.js +19 -10
- package/modules/sky/season.js +7 -1
- package/modules/sky/shader.js +24 -25
- package/modules/sky/skyModule.js +17 -28
- package/modules/sky/tint.js +1 -1
- package/modules/swarm/Swarm.js +356 -0
- package/modules/swarm/draw.js +68 -0
- package/modules/swarm/grid.js +63 -0
- package/modules/terrain/ChunkManager.js +71 -59
- package/modules/terrain/chunkQueries.js +7 -24
- package/modules/terrain/chunkWorker.js +1 -1
- package/modules/terrain/draw.js +14 -11
- package/modules/terrain/index.js +42 -42
- package/modules/terrain/terrainColorMap.js +6 -3
- package/modules/terrain/terrainDefaults.js +2 -1
- package/modules/terrain/terrainEdit.js +45 -29
- package/modules/terrain/terrainGen.js +19 -12
- package/modules/terrain/terrainIsland.js +2 -2
- package/modules/terrain/terrainMesh.js +7 -6
- package/modules/terrain/terrainShape.js +8 -10
- package/modules/terrain/terrainShapeMain.js +3 -3
- package/modules/timeline/Timeline.js +83 -43
- package/modules/timeline/Tween.js +25 -19
- package/modules/timeline/shots.js +24 -17
- package/modules/triggers/index.js +95 -28
- package/modules/vegetation/Vegetation.js +34 -26
- package/modules/vegetation/densityMap.js +4 -7
- package/modules/vegetation/draw.js +39 -18
- package/modules/vegetation/groundChunks.js +21 -38
- package/modules/vegetation/index.js +37 -12
- package/modules/vegetation/modelGeometry.js +3 -6
- package/modules/vegetation/nearFade.js +1 -1
- package/modules/water/Water.js +20 -16
- package/modules/water/surface.js +3 -3
- package/modules/weather/Weather.js +52 -40
- package/modules/weather/particles.js +8 -8
- package/modules/weather/weatherDraw.js +28 -23
- package/modules/world/World.js +28 -15
- package/modules/world/explain.js +1 -1
- package/modules/world/index.js +30 -17
- package/modules/world/persist.js +90 -27
- package/modules/world/pos.js +5 -5
- package/modules/world/records.js +37 -11
- package/modules/world/sim.js +78 -27
- package/modules/world/simFar.js +2 -2
- package/modules/world/state.js +43 -11
- package/modules/world/thingSource.js +20 -5
- package/modules/world/views.js +27 -14
- package/package.json +48 -7
- package/presets.js +1 -3
- package/render/PostFX.js +83 -53
- package/render/backend.js +31 -33
- package/render/cascades.js +17 -12
- package/render/cascades.tsl.js +5 -8
- package/render/daylight.js +20 -3
- package/render/detail.js +8 -7
- package/render/effects.js +28 -25
- package/render/fuse.js +3 -3
- package/render/fx/cloudShadow.tsl.js +3 -3
- package/render/fx/detail.tsl.js +1 -1
- package/render/fx/index.js +5 -10
- package/render/fx/library.tsl.js +11 -0
- package/render/fx/lighting.tsl.js +2 -1
- package/render/fx/nodeErrors.tsl.js +2 -2
- package/render/fx/objectOrigin.tsl.js +1 -2
- package/render/fx/particles.tsl.js +8 -6
- package/render/fx/patchNodes.tsl.js +5 -15
- package/render/fx/postWebGPU.tsl.js +30 -26
- package/render/fx/sky.tsl.js +15 -17
- package/render/fx/uniforms.tsl.js +4 -4
- package/render/fx/wind.tsl.js +1 -1
- package/render/fxNumbers.js +3 -0
- package/render/layers.js +2 -2
- package/render/lighting.js +5 -3
- package/render/lightmap.js +41 -21
- package/render/lights.js +6 -6
- package/render/lit.js +24 -0
- package/render/materials.js +8 -7
- package/render/mergeCommon.js +22 -0
- package/render/modeling.js +2 -2
- package/render/occlusion.js +62 -15
- package/render/ownFrame.js +4 -4
- package/render/patches.js +15 -15
- package/render/postWebGL.js +15 -12
- package/render/probes.js +41 -19
- package/render/recordSweep.js +117 -0
- package/render/shaderErrors.js +10 -9
- package/render/shadowCache.tsl.js +107 -0
- package/render/shadowTypes.js +9 -0
- package/{core → render}/shadows.js +59 -13
- package/render/slots.js +7 -7
- package/render/terms.js +22 -24
- package/render/uniformDecl.js +1 -1
- package/types/core.d.ts +336 -202
- package/types/gameplay.d.ts +254 -130
- package/types/generated/core/{Audio.d.ts → audio/Audio.d.ts} +22 -7
- package/types/generated/core/{audioVoice.d.ts → audio/audioVoice.d.ts} +2 -2
- package/types/generated/core/{Events.d.ts → base/Events.d.ts} +4 -4
- package/types/generated/core/{I18n.d.ts → base/I18n.d.ts} +8 -16
- package/types/generated/core/{Random.d.ts → base/Random.d.ts} +4 -3
- package/types/generated/core/{page.d.ts → engine/page.d.ts} +8 -9
- package/types/generated/core/{Input.d.ts → input/Input.d.ts} +28 -10
- package/types/generated/core/input/inputSeat.d.ts +26 -0
- package/types/generated/core/{Budget.d.ts → inspect/Budget.d.ts} +36 -26
- package/types/generated/core/{DebugOverrides.d.ts → inspect/DebugOverrides.d.ts} +17 -3
- package/types/generated/core/{Ops.d.ts → ops/Ops.d.ts} +6 -4
- package/types/generated/core/{control.d.ts → ops/control.d.ts} +14 -10
- package/types/generated/core/{Saves.d.ts → saves/Saves.d.ts} +62 -18
- package/types/generated/core/{session.d.ts → saves/session.d.ts} +3 -2
- package/types/generated/core/{Rays.d.ts → scene/Rays.d.ts} +8 -27
- package/types/generated/core/{Views.d.ts → scene/Views.d.ts} +2 -2
- package/types/generated/core/{Batching.d.ts → stream/Batching.d.ts} +7 -7
- package/types/generated/core/{Stream.d.ts → stream/Stream.d.ts} +22 -18
- package/types/generated/core/{Commits.d.ts → threads/Commits.d.ts} +1 -1
- package/types/generated/core/{Jobs.d.ts → threads/Jobs.d.ts} +6 -6
- package/types/generated/core/{Threads.d.ts → threads/Threads.d.ts} +4 -4
- package/types/generated/modules/calendar/Calendar.d.ts +10 -11
- package/types/generated/modules/debug/DebugPanel.d.ts +1 -9
- package/types/generated/modules/grid/Grid.d.ts +1 -0
- package/types/generated/modules/grid/Layer.d.ts +1 -1
- package/types/generated/modules/grid/index.d.ts +3 -3
- package/types/generated/modules/music/Music.d.ts +7 -5
- package/types/generated/modules/particles/Particles.d.ts +5 -4
- package/types/generated/modules/sky/Sky.d.ts +21 -10
- package/types/generated/modules/swarm/Swarm.d.ts +80 -0
- package/types/generated/modules/timeline/Timeline.d.ts +7 -5
- package/types/generated/modules/water/Water.d.ts +1 -0
- package/types/generated/modules/weather/Weather.d.ts +14 -16
- package/types/generated/modules/weather/weatherDraw.d.ts +3 -3
- package/types/generated/modules/world/World.d.ts +11 -7
- package/types/generated/render/PostFX.d.ts +21 -23
- package/types/generated/render/materials.d.ts +1 -0
- package/types/generated/render/occlusion.d.ts +9 -0
- package/types/generated/render/patches.d.ts +1 -0
- package/types/generated/ui/Focus.d.ts +1 -0
- package/types/generated/ui/UI.d.ts +1 -0
- package/types/nav.d.ts +47 -15
- package/types/physics.d.ts +150 -73
- package/types/pixel.d.ts +75 -0
- package/types/tsl.d.ts +37 -4
- package/types/world.d.ts +48 -75
- package/ui/Focus.js +10 -9
- package/ui/Parts.js +13 -5
- package/ui/UI.js +7 -7
- package/ui/defaults.js +3 -2
- package/ui/theme.js +7 -5
- package/core/assetEntry.js +0 -109
- package/core/engineCamera.js +0 -32
- package/core/ground.js +0 -104
- package/core/holds.js +0 -134
- package/core/math.js +0 -48
- package/core/moduleSlots.js +0 -100
- package/core/modules.js +0 -314
- package/core/saveApply.js +0 -210
- package/core/saveValues.js +0 -46
- package/core/session.js +0 -174
- package/core/shadowTypes.js +0 -16
- package/core/util.js +0 -17
- package/core/view.js +0 -43
- package/docs/MIGRATING-0.3.md +0 -248
- package/docs/MIGRATING-0.4.md +0 -320
- package/docs/MIGRATING-0.5.md +0 -68
- package/docs/MIGRATING-0.6.md +0 -126
- package/docs/PERF.md +0 -245
- package/docs/recipes/36-sky-ground-plants.md +0 -158
- package/docs/recipes/37-terrain-hooks.md +0 -115
- package/docs/recipes/38-environment-hooks.md +0 -67
- package/docs/recipes/42-terrain-shape.md +0 -64
- package/docs/recipes/47-island-snow-backdrop.md +0 -43
- package/docs/recipes/54-three-idioms.md +0 -88
- package/examples/plain-picture/FINDINGS.md +0 -53
- package/examples/sheepisland/.threedog/content-index.json +0 -1
- package/modules/camera/projection.js +0 -21
- /package/core/{mulberry32.js → base/mulberry32.js} +0 -0
- /package/core/{inputDefaults.js → input/inputDefaults.js} +0 -0
- /package/core/{textureBytes.js → inspect/textureBytes.js} +0 -0
- /package/core/{actor.js → ops/actor.js} +0 -0
- /package/core/{opsHistory.js → ops/opsHistory.js} +0 -0
- /package/core/{saveIds.js → saves/saveIds.js} +0 -0
- /package/core/{screenToGround.js → scene/screenToGround.js} +0 -0
- /package/core/{cells.js → stream/cells.js} +0 -0
- /package/core/{streamCells.js → stream/streamCells.js} +0 -0
- /package/core/{pureWorker.js → threads/pureWorker.js} +0 -0
- /package/examples/{sheepisland → perf-island}/content/index.js +0 -0
- /package/examples/{sheepisland → perf-island}/content/props.js +0 -0
- /package/examples/{sheepisland → perf-island}/content/templates.js +0 -0
- /package/examples/{sheepisland → perf-island}/content/vegetation.js +0 -0
- /package/examples/{sheepisland → perf-island}/picture/lights.js +0 -0
- /package/examples/{sheepisland → perf-island}/picture/materials.js +0 -0
- /package/examples/{sheepisland → perf-island}/picture/sky.js +0 -0
|
@@ -0,0 +1,503 @@
|
|
|
1
|
+
// Module installation (part of Engine, mixed into Engine.prototype): engine.use(...) / engine.has(name) / engine.moduleOrder.
|
|
2
|
+
// See CLAUDE.md "writing a module" for the module shape; dispose is called by lifecycle.js in reverse install order.
|
|
3
|
+
//
|
|
4
|
+
// Run order (fixed / frame / afterRender / skip hooks): by stage first, then before / after within a stage, then install order.
|
|
5
|
+
// stage only orders hooks; what a module may own and what happens when it throws come from its type (moduleTypes.js, errors.js).
|
|
6
|
+
// Stages (first to last): control timeline, camera -> ground terrain, level -> environment weather, sky, water
|
|
7
|
+
// -> gameplay interactions, dialogue, trigger zones -> effects particles, settings, objective markers
|
|
8
|
+
// -> late (the default) characters, physics, navigation... -> audio music
|
|
9
|
+
// before / after: lists of module or capability names (not-installed names are ignored; a capability means whichever module provides it now, so the order follows a replaces);
|
|
10
|
+
// they order modules only inside one stage. One that contradicts the stage order (a 'control' module with after: ['sky']) makes use() throw naming both modules and stages;
|
|
11
|
+
// a cycle makes use() throw on the spot, naming the modules on it. A contradiction reached through provides throws the same way: an order must not turn into a hint after a replaces.
|
|
12
|
+
// One change plan: use, unuse, replaces and plugin on / off all go through _planChange (moduleSlots.js), which works out the module graph after the change and checks every
|
|
13
|
+
// consumer, new or kept, before anything is touched. Then install is all-or-nothing per engine.use(...) call: if a module's install() throws, the modules this call already
|
|
14
|
+
// installed are removed again (engine.name, module table, hooks; their dispose() runs) and the error is rethrown.
|
|
15
|
+
// Module state (engine.explain({ module })): registered -> initializing -> running | failed; disposed after engine.dispose(). Modules without init() are
|
|
16
|
+
// running at once. fixed / frame / afterRender / skip hooks run only for running modules, so no module gets a hook before its init() finished
|
|
17
|
+
// (during start() or when installed later).
|
|
18
|
+
// requires is a promise that the provider works, not only that it is installed: a module whose required provider is not running (still initializing, failed, or blocked itself)
|
|
19
|
+
// is 'blocked': its init waits, its hooks do not run, and engine.catalog(name).blockedBy says on what. It starts by itself when a provider comes up (a replaces of a failed one).
|
|
20
|
+
// A critical module blocked by a failure stops start(), or is reported when it happens later. Modules that do not depend on the failed one go on.
|
|
21
|
+
// Installed is not usable: engine.has(name) says a module of that name or a provider of that capability is in the module table; engine.usable(name), internal, says it can be called now
|
|
22
|
+
// (running, not blocked, not disabled). A game waits with loading.settled and asks engine.explain({ module }).
|
|
23
|
+
// A capability binds where provides meets requires: dev checks the provider's API against the capability's contract then, on a module change and never per frame (moduleSlots.js).
|
|
24
|
+
// Ownership: install(e, ctx) and init(e, ctx) get ctx = { name, track(handle), mod(point, o), borrow(obj, values), control.take(character, o) }. A handle passed to ctx.track (events.on, onFixed, onFrame,
|
|
25
|
+
// clock timers, audio.measure... anything with remove()) belongs to the module and is removed with it: when the use() batch rolls back,
|
|
26
|
+
// when its init fails, and on engine.dispose() (before the module's own dispose). Listeners a module adds go through it, so an install
|
|
27
|
+
// that fails halfway leaves no ghost listener behind (review 0.4 A; the rollback spec checks every built-in module).
|
|
28
|
+
// ctx.mod(point, o) = ctx.track(engine.mod(point, { ...o, owner: ctx.name })): a module's changes to shared values go with it too.
|
|
29
|
+
// ctx.rule(name, default, names?) = a replaceable rule on a plain shared point: .decide(id, facts) gives a built-in name, false for manual, or what the game's function answered.
|
|
30
|
+
// ctx.input.action(name, { context }) / ctx.input.bind(name, keys): the module's input declarations and bindings, gone with it too.
|
|
31
|
+
// ctx.ops.define, ctx.saves.register, ctx.ui.define, ctx.stream.addReadyCheck, ctx.budget.metric, ctx.things.addSource / explainWith, ctx.ground.provide / addColliders:
|
|
32
|
+
// the same registrars, recorded in the one scope with kind, id, owner and instance (engine.catalog(name).resources reads it). Built-in modules register only through
|
|
33
|
+
// these (tools/tests/module-boundaries). A save part leaving keeps its data as unattached data of the save (Saves.register), so a module unloaded for a while loses nothing.
|
|
34
|
+
// Every install is its own instance (engine._modInst: name -> token): a ctx belongs to one install, not to a name. An async init that resumes after
|
|
35
|
+
// its module was unloaded (replaces, a plugin removed) and a same-named one installed must not act on the newcomer: a stale ctx verb does nothing and gives a spent handle, because
|
|
36
|
+
// the owner name is shared and doing it first would replace the newcomer's entry (dev warning naming the module); what it tracks is removed at once; its completion or failure
|
|
37
|
+
// changes no state and drops no handle of the newcomer.
|
|
38
|
+
// Exclusive slots: provides: ['inventory'] takes each named slot (a kind 'one' shared point, core/ops/sharedPoint.js) for the module before its install;
|
|
39
|
+
// a second provider is shared-taken. requires may name a slot instead of a module. engine.use(mine(), { replaces: 'inventory' }) unloads the
|
|
40
|
+
// holder first (its handles, slot, drawing parts, dispose), and puts it back if the new install fails, with its save data and content sections (_putBack). Either way the holder now is a fresh install that has none of what
|
|
41
|
+
// others put into the old one, so 'module:restored' tells whoever fed it, once its init is done: they feed it again. The word means "this module is back and holds nothing yet", not that its old state came back; its save data did, its definitions did not.
|
|
42
|
+
// critical: true on a module makes a failed init() stop engine.start() with the reason; without it a failed init is reported (picture / ui: disabled;
|
|
43
|
+
// other types: error tiers in errors.js) and start() goes on.
|
|
44
|
+
// Dependencies: requires must be installed first (throws if missing). optional is a soft dependency: an array is only recorded (for GAMEMAP and rule R16);
|
|
45
|
+
// written as { module: 'what is lost without it' }, start() warns once in dev when it is missing: use this form for optional dependencies
|
|
46
|
+
// that change gameplay results, which must not be skipped silently.
|
|
47
|
+
import { warnOnce, DEV, fmt, closest } from '../base/validate.js';
|
|
48
|
+
import { codedError, coded } from '../base/errorHints.js';
|
|
49
|
+
import { reportError } from '../base/errors.js';
|
|
50
|
+
import { catalog, catalogSnap, catalogClaim } from '../inspect/catalog.js';
|
|
51
|
+
import { readParams } from '../base/params.js';
|
|
52
|
+
import { slotMethods, isUseOpts, checkProvides, slotTaken, giversOf, CORE_SLOTS } from './moduleSlots.js';
|
|
53
|
+
import { checkType, asModule } from './moduleTypes.js';
|
|
54
|
+
|
|
55
|
+
/** Stage -> sort position */
|
|
56
|
+
const STAGES = { control: 100, ground: 200, environment: 300, gameplay: 400, effects: 450, late: 500, audio: 510 };
|
|
57
|
+
const HOOKS = ['fixed', 'frame', 'afterRender', 'skip'];
|
|
58
|
+
const STRINGS = {
|
|
59
|
+
cycle: 'module order forms a cycle: {path} (check before / after on these modules)',
|
|
60
|
+
stage: 'module {name} has stage "{stage}", which is not a stage; available stages: {list}',
|
|
61
|
+
order: 'module {name} sets order, which is not supported; modules do not sort by number. Set stage ({list}) and use before / after within a stage',
|
|
62
|
+
optional: 'optional dependency {dep} of module {name} is not installed: {what} (ignore if not needed; otherwise call engine.use({dep}()))',
|
|
63
|
+
called: 'engine.use received the module function {name} itself; call it: {name}()',
|
|
64
|
+
twice: 'module {name} is already installed; the second engine.use({name}()) is ignored',
|
|
65
|
+
readyHook: 'module {name}: the load-complete hook is named isReady(e) (ready is always a boolean property in the engine); ready(e) will not be called',
|
|
66
|
+
// both ways out: the engine's part of that name, or the game's own provider (requires names a capability, never a particular module)
|
|
67
|
+
needs: "module {name} requires '{dep}', which no installed module provides. Fix: install the engine's part first, engine.use({dep}(), {name}(...)), "
|
|
68
|
+
+ "or your own module with provides: ['{dep}'] (then engine.{dep} is your module's API){typo}",
|
|
69
|
+
typo: " (did you mean '{hint}'? installed: {list})",
|
|
70
|
+
clash: 'module name {name} clashes with an existing engine property; pick another name',
|
|
71
|
+
slotClash: "module {name} provides '{slot}', but engine.{slot} is already an engine property, so dependents could not reach it there. Fix: pick another slot name",
|
|
72
|
+
lateInit: 'init of module {name} (installed after start)',
|
|
73
|
+
groundClaim: "module {name} called ctx.ground.provide, but ground is an exclusive capability it did not claim. Fix: add 'ground' to its provides",
|
|
74
|
+
critical: "critical module {name} cannot run: it requires '{dep}', and {by} is {state}. Fix what stopped {by}, or drop critical from {name}",
|
|
75
|
+
conflict: 'module {a} (stage "{sa}") sets {kind}: ["{said}"], but module {b} is in stage "{sb}", which always runs {kind} stage "{sa}" (stage order: {list}); '
|
|
76
|
+
+ 'before / after only order modules inside one stage. Fix: give both modules the same stage, or remove {kind}: ["{said}"] from {a}',
|
|
77
|
+
capStage: 'module {a} (stage "{sa}") sets {kind}: ["{said}"], but the provider of \'{said}\' is module {b} in stage "{sb}", so this order cannot hold. Fix: give {b} stage: \'{sa}\', or drop the order from {a}',
|
|
78
|
+
};
|
|
79
|
+
const LOST = "engine.use(..., { replaces }): this unloads {gone}, and module {name} requires '{dep}', which nothing would provide afterwards. Fix: add provides: ['{dep}'] to the module that takes over, or unload {name} first";
|
|
80
|
+
const CTX_OWNER = "ctx.mod('{point}', { owner }) in module {name}: ctx.mod names the module as the owner itself; drop owner (use engine.mod for another owner name)";
|
|
81
|
+
const BORROW_HELD = "ctx.borrow in module {name}: '{key}' is already borrowed by module {holder}. A borrow is one holder's temporary use: end that one first, or, when several parties want this value, put it on a shared point (engine.mod)";
|
|
82
|
+
const BAD_BORROW = 'ctx.borrow(obj, values) in module {name}: obj is the object to write on and values the properties to write, like ctx.borrow(e.renderer, { toneMapping: THREE.AgXToneMapping }); got {got}';
|
|
83
|
+
const BAD_HANDLE = 'ctx.track(handle) in module {name}: handle must have remove(), like the result of engine.events.on / onFixed / clock.after; got {got}';
|
|
84
|
+
const STALE = 'module {name} registered something after it was unloaded (its async init or a callback resumed after replaces / unload); nothing of it stays. '
|
|
85
|
+
+ 'The module installed under that name now is not affected';
|
|
86
|
+
const STALE_INIT = 'init of module {name}, which was unloaded before it finished';
|
|
87
|
+
const hookCache = new WeakMap(); // module definition -> { fixed, frame, afterRender, skip } hook entries (reused when re-sorting)
|
|
88
|
+
|
|
89
|
+
/** Every before / after declaration as an ordered pair: first runs before then. said is the name as written, by the module that wrote it. Its own capability orders nothing */
|
|
90
|
+
function orderPairs(list) {
|
|
91
|
+
const out = [];
|
|
92
|
+
for (const m of list) for (const kind of ['before', 'after']) for (const said of m[kind] ?? []) for (const o of giversOf(list, said)) {
|
|
93
|
+
if (o !== m || said === m.name) out.push({ m, o, kind, said, first: kind === 'before' ? m : o, then: kind === 'before' ? o : m });
|
|
94
|
+
}
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
const rankOf = m => STAGES[m.stage] ?? STAGES.late;
|
|
98
|
+
|
|
99
|
+
/** Sort modules by stage, before / after and install order (Kahn topological sort; among the ready ones take the earliest stage,
|
|
100
|
+
* then earliest installed); throws on a cycle. */
|
|
101
|
+
function sortModules(list) {
|
|
102
|
+
const idx = new Map(list.map((m, i) => [m.name, i])), byName = new Map(list.map(m => [m.name, m]));
|
|
103
|
+
const succ = new Map(list.map(m => [m.name, new Set()])), indeg = new Map(list.map(m => [m.name, 0]));
|
|
104
|
+
const edge = (a, b) => { if (!idx.has(a) || !idx.has(b) || succ.get(a).has(b)) return; succ.get(a).add(b); indeg.set(b, indeg.get(b) + 1); };
|
|
105
|
+
for (const { first, then } of orderPairs(list)) edge(first.name, then.name);
|
|
106
|
+
const cmp = (a, b) => rankOf(a) - rankOf(b) || idx.get(a.name) - idx.get(b.name);
|
|
107
|
+
const ready = list.filter(m => !indeg.get(m.name)), out = [];
|
|
108
|
+
while (ready.length) {
|
|
109
|
+
ready.sort(cmp);
|
|
110
|
+
const m = ready.shift(); out.push(m);
|
|
111
|
+
for (const n of succ.get(m.name)) { indeg.set(n, indeg.get(n) - 1); if (!indeg.get(n)) ready.push(byName.get(n)); }
|
|
112
|
+
}
|
|
113
|
+
if (out.length === list.length) return out;
|
|
114
|
+
// What is left is on a cycle or behind one: walk edges from any node; revisiting a node closes the cycle
|
|
115
|
+
// First drop, repeatedly, the nodes with no successor still left: those are only blocked behind a cycle (a walk starting there would dead-end
|
|
116
|
+
// on a node without a next step); every node that remains has a successor in the set, so the walk always ends in a real cycle
|
|
117
|
+
const left = new Set(list.filter(m => !out.includes(m)).map(m => m.name)), path = [];
|
|
118
|
+
for (let drop = true; drop;) { drop = false; for (const n of left) if (![...succ.get(n)].some(x => left.has(x))) { left.delete(n); drop = true; } }
|
|
119
|
+
for (let n = left.values().next().value; !path.includes(n); n = [...succ.get(n)].find(x => left.has(x))) path.push(n);
|
|
120
|
+
const cyc = path.slice(path.indexOf([...succ.get(path.at(-1))].find(x => path.includes(x))));
|
|
121
|
+
throw codedError('module-cycle', fmt(STRINGS.cycle, { path: [...cyc, cyc[0]].join(' -> ') }));
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** before / after across stages must agree with the stage order (the stage always wins), else the declaration would be silently ignored: throw naming both modules */
|
|
125
|
+
function checkStages(list) {
|
|
126
|
+
const stage = m => m.stage ?? 'late', order = Object.keys(STAGES).join(' -> ');
|
|
127
|
+
for (const { m, o, kind, said, first, then } of orderPairs(list)) {
|
|
128
|
+
if (rankOf(first) <= rankOf(then)) continue;
|
|
129
|
+
const v = { a: m.name, sa: stage(m), kind, said, b: o.name, sb: stage(o), list: order };
|
|
130
|
+
throw codedError('module-order', fmt(o.name === said ? STRINGS.conflict : STRINGS.capStage, v));
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export const moduleMethods = {
|
|
135
|
+
...slotMethods, // provides / replaces (moduleSlots.js)
|
|
136
|
+
/**
|
|
137
|
+
* Install one or more modules in order; dependencies must be installed first; hook order is described at the top of this file.
|
|
138
|
+
* All-or-nothing: the batch is validated first, and if an install() throws, the modules this call installed are removed again.
|
|
139
|
+
* A module installed after start() has its init(e) run at once (a task in engine.loading; an error goes through the error tiers) and gets no hooks
|
|
140
|
+
* until it succeeded:
|
|
141
|
+
* `await engine.loading.settled()` waits for it; engine.explain({ module }) shows where each module is.
|
|
142
|
+
*/
|
|
143
|
+
use(...mods) {
|
|
144
|
+
const opts = isUseOpts(mods.at(-1)) ? mods.pop() : null;
|
|
145
|
+
const list = mods.flat(Infinity), gone = this._replaced(list, opts?.replaces);
|
|
146
|
+
this._applyChange(this._planChange(list, gone, { code: 'module-replaces', text: LOST }), gone);
|
|
147
|
+
return this;
|
|
148
|
+
},
|
|
149
|
+
/** @internal A change is finished when queries can trust it: everyone feeding a name these modules answer to (ctx.feeds) has fed the newcomer, so the line after use() reads it whole */
|
|
150
|
+
_feed(plan) {
|
|
151
|
+
const names = new Set(plan.flatMap(m => [m.name, ...(m.provides ?? [])]));
|
|
152
|
+
for (const f of [...(this._feeders ?? [])]) if (names.has(f.name)) f.fn();
|
|
153
|
+
},
|
|
154
|
+
/** @internal carry out a change _planChange accepted: the modules in gone leave, then the plan installs (all or nothing) */
|
|
155
|
+
_applyChange(plan, gone, swapping = plan.length > 0) {
|
|
156
|
+
const done = [], order = [...this.modules.keys()], base = this.session._base;
|
|
157
|
+
// replaces: the holder goes first (its tracked handles, its slot, its drawing parts, its dispose), so the newcomer's install sees a free slot. It cannot wait for the
|
|
158
|
+
// newcomer to prove itself: both would claim the slot, the save key, the ops and engine.<name>, so a failure is undone instead (_putBack).
|
|
159
|
+
// Newest first like dispose; removed ends in install order, so each module comes back after what it requires
|
|
160
|
+
const removed = order.filter(n => gone.has(n)).reverse().map(n => this._unuse(n, swapping)).reverse();
|
|
161
|
+
try {
|
|
162
|
+
for (const m of plan) {
|
|
163
|
+
const had = Object.hasOwn(this, m.name), prev = this[m.name], snap = catalogSnap(this);
|
|
164
|
+
done.push({ m, had, prev }); // before install(): what it tracked before throwing is removed too
|
|
165
|
+
this._modInst.set(m.name, { ac: new AbortController() }); // this install's identity: install and init ctx check it, so a stale async init cannot act on a later install
|
|
166
|
+
const ctx = this._modCtx(m);
|
|
167
|
+
this._picture?.installing(m);
|
|
168
|
+
for (const slot of m.provides ?? []) ctx.track(this._slot(slot, m.name).take({ owner: m.name })); // shared-taken when another module holds it
|
|
169
|
+
const api = asModule(this, m, () => m.install?.(this, ctx)) ?? m; // asModule: the type checks know who is installing (moduleTypes.js)
|
|
170
|
+
catalogClaim(this, m.name, snap); // ops / save parts / describe names it registered show under it in engine.catalog()
|
|
171
|
+
this.modules.set(m.name, m);
|
|
172
|
+
if (m.name) this[m.name] = api;
|
|
173
|
+
// engine.<slot> is the provider's API too, so a module that requires 'inventory' reaches the game's own bag at engine.inventory after
|
|
174
|
+
// a replaces: dependents name the capability, never the module that gives it
|
|
175
|
+
for (const slot of m.provides ?? []) if (slot !== m.name && !CORE_SLOTS.has(slot)) { this[slot] = api; ctx.track(this._aliasSlot(slot, api)); }
|
|
176
|
+
this._modState.set(m.name, m.init ? 'registered' : 'running');
|
|
177
|
+
}
|
|
178
|
+
this._feed(plan); // inside the try: a provider that cannot take what feeds it fails its install
|
|
179
|
+
} catch (err) {
|
|
180
|
+
for (const { m, had, prev } of done.reverse()) { // undo in reverse install order, like dispose
|
|
181
|
+
const installed = this.modules.get(m.name) === m;
|
|
182
|
+
this._modInst.get(m.name)?.ac.abort(); // before the token goes: ctx.signal of a rolled-back install
|
|
183
|
+
this.modules.delete(m.name); this._modState.delete(m.name); this._modInst.delete(m.name);
|
|
184
|
+
if (had) this[m.name] = prev; else delete this[m.name]; // put back what was there (an undefined slot stays undefined), never blank it
|
|
185
|
+
this._dropTracked(m.name);
|
|
186
|
+
if (installed) try { m.dispose?.(this); } catch { /* the install error below is the one to report */ }
|
|
187
|
+
}
|
|
188
|
+
this._sortHooks();
|
|
189
|
+
if (removed.length) this._putBack(removed, order, base);
|
|
190
|
+
throw err;
|
|
191
|
+
}
|
|
192
|
+
this._sortHooks();
|
|
193
|
+
if (removed.length && plan.length) this._tellRestored(plan);
|
|
194
|
+
},
|
|
195
|
+
/**
|
|
196
|
+
* @internal 'module:restored' for these fresh modules, after their init: what is fed then lands as it does on a running game, where content.load comes after init
|
|
197
|
+
* (a level's own url would otherwise overtake the pack's level). Nothing in flight tells at once. One replaced again meanwhile is not told about
|
|
198
|
+
*/
|
|
199
|
+
_tellRestored(modules) {
|
|
200
|
+
const tell = () => {
|
|
201
|
+
const live = modules.filter(m => this.modules.get(m.name) === m);
|
|
202
|
+
if (live.length && !this.disposed) this.events.emit('module:restored', { modules: live });
|
|
203
|
+
};
|
|
204
|
+
if (this.loading._inits.size) this.loading.settled().then(tell); else tell();
|
|
205
|
+
},
|
|
206
|
+
/**
|
|
207
|
+
* @internal a failed swap leaves the game as it was: the replaced modules install fresh (their old handles already went), their save parts take back their data as a part registered
|
|
208
|
+
* late does (Saves.register), and 'module:restored' tells whoever fed them, because a fresh install has no definitions, as after a swap that worked: content sections load again (modules/content).
|
|
209
|
+
* What game code defined by hand it defines again on that event. Colliders of the level and of props need no event: they check the holder themselves.
|
|
210
|
+
* @param {any[]} removed in install order @param {string[]} order the module names to go back to @param {string | null} base the new-game state to go back to
|
|
211
|
+
*/
|
|
212
|
+
_putBack(removed, order, base) {
|
|
213
|
+
this.session._base = base; // a newcomer's save part may have written over a part of the same key (session._late)
|
|
214
|
+
try { this.use(...removed); } catch (e2) { return reportError(this, e2, 'putting back the module a failed replaces removed', { soft: true }); }
|
|
215
|
+
for (const n of order) { const m = this.modules.get(n); this.modules.delete(n); this.modules.set(n, m); } // hooks of one stage run in install order: same places
|
|
216
|
+
this._sortHooks();
|
|
217
|
+
this._tellRestored(removed);
|
|
218
|
+
},
|
|
219
|
+
/** @internal validate a batch without touching the engine (so a failure leaves nothing half-installed);
|
|
220
|
+
* returns the modules to install */
|
|
221
|
+
_planUse(list, gone = new Set()) {
|
|
222
|
+
const names = new Set([...this.modules.keys()].filter(n => !gone.has(n))), plan = [];
|
|
223
|
+
// who holds each exclusive slot after this change: read from the graph, so a clash is refused here, before a replaced module is disposed
|
|
224
|
+
const holders = new Map();
|
|
225
|
+
for (const n of names) for (const s of this.modules.get(n).provides ?? []) holders.set(s, n);
|
|
226
|
+
// requires names a module or a capability: another module's provides (depend on 'inventory', not on whichever module gives it)
|
|
227
|
+
const caps = new Set(names);
|
|
228
|
+
for (const n of names) for (const s of this.modules.get(n).provides ?? []) caps.add(s);
|
|
229
|
+
for (const m of list) {
|
|
230
|
+
if (!m) continue;
|
|
231
|
+
if (typeof m === 'function') throw codedError('module-called', fmt(STRINGS.called, { name: m.name }));
|
|
232
|
+
if (names.has(m.name)) { warnOnce(coded('module-name', fmt(STRINGS.twice, { name: m.name }))); continue; }
|
|
233
|
+
if (typeof m.ready === 'function') warnOnce(coded('engine-misuse', fmt(STRINGS.readyHook, { name: m.name })));
|
|
234
|
+
if (m.order != null) throw codedError('module-stage', fmt(STRINGS.order, { name: m.name, list: Object.keys(STAGES).join(', ') }));
|
|
235
|
+
if (m.stage != null && !(m.stage in STAGES))
|
|
236
|
+
throw codedError('module-stage', fmt(STRINGS.stage, { name: m.name, stage: m.stage, list: Object.keys(STAGES).join(', ') }));
|
|
237
|
+
checkType(m);
|
|
238
|
+
for (const dep of m.requires || []) if (!caps.has(dep)) {
|
|
239
|
+
const hint = closest(dep, [...caps]);
|
|
240
|
+
throw codedError('module-requires', fmt(STRINGS.needs, { name: m.name, dep, typo: hint ? fmt(STRINGS.typo, { hint, list: [...caps].join(', ') }) : '' }));
|
|
241
|
+
}
|
|
242
|
+
checkProvides(m);
|
|
243
|
+
for (const slot of m.provides ?? []) {
|
|
244
|
+
if (holders.has(slot)) throw slotTaken(slot, holders.get(slot), m.name);
|
|
245
|
+
holders.set(slot, m.name);
|
|
246
|
+
if (slot !== m.name && !gone.has(slot) && !names.has(slot) && !CORE_SLOTS.has(slot) && slot in this && this[slot] !== undefined && !this._slotAlias?.has(slot))
|
|
247
|
+
throw codedError('module-provides', fmt(STRINGS.slotClash, { name: m.name, slot }));
|
|
248
|
+
}
|
|
249
|
+
if (DEV && m.params && m.options) readParams(m.name, m.params, m.options); // a definition built by hand still gets its options checked
|
|
250
|
+
if (!gone.has(m.name) && m.name in this && this[m.name] !== undefined) throw codedError('module-name', fmt(STRINGS.clash, { name: m.name }));
|
|
251
|
+
names.add(m.name); caps.add(m.name); for (const s of m.provides ?? []) caps.add(s);
|
|
252
|
+
plan.push(m);
|
|
253
|
+
}
|
|
254
|
+
if (plan.length) { const all = [...[...this.modules.values()].filter(m => !gone.has(m.name)), ...plan]; checkStages(all); sortModules(all); }
|
|
255
|
+
return plan;
|
|
256
|
+
},
|
|
257
|
+
/** @internal after start(): every module whose init has not run and whose providers are up gets it now, in install order */
|
|
258
|
+
_initWaiting() {
|
|
259
|
+
if (!this._initsDone) return;
|
|
260
|
+
const start = [...this.modules.values()].filter(m => m.init && this._modState.get(m.name) === 'registered' && !this._modBlocked.has(m.name));
|
|
261
|
+
for (const m of start) this._lateInit(m);
|
|
262
|
+
if (start.length) this._refreshBlocks(); // what waits on them now reads 'initializing', not 'registered'
|
|
263
|
+
},
|
|
264
|
+
/** @internal init of a module installed after start(): run now, tracked in engine.loading, errors through the error tiers;
|
|
265
|
+
* its hooks join only after it succeeded */
|
|
266
|
+
_lateInit(m) {
|
|
267
|
+
this._modState.set(m.name, 'initializing');
|
|
268
|
+
const L = this.loading, task = L._begin(m.name, 'module');
|
|
269
|
+
task.phase('build');
|
|
270
|
+
const snap = catalogSnap(this);
|
|
271
|
+
// the instance and its ctx are taken now, not when the microtask runs: by then a same-named module may be installed in its place
|
|
272
|
+
const inst = this._modInst.get(m.name), ctx = this._modCtx(m, inst), live = () => this._isLive(m.name, inst);
|
|
273
|
+
L._track(Promise.resolve().then(() => asModule(this, m, () => m.init(this, ctx))).then(
|
|
274
|
+
() => { L._done(task); if (live()) { catalogClaim(this, m.name, snap); this._setModState(m, 'running'); this.session._lateInit([...(this._modTracked.get(m.name) ?? [])].filter(h => h.kind === 'save').map(h => h.id)); } },
|
|
275
|
+
e => {
|
|
276
|
+
L._fail(task, e);
|
|
277
|
+
// unloaded meanwhile: its handles already went with it, and the state / handles under this name belong to the newcomer now
|
|
278
|
+
if (!live()) return reportError(this, e, fmt(STALE_INIT, { name: m.name }), { soft: true });
|
|
279
|
+
this._setModState(m, 'failed'); this._dropTracked(m.name); reportError(this, e, fmt(STRINGS.lateInit, { name: m.name }), { module: m });
|
|
280
|
+
}));
|
|
281
|
+
},
|
|
282
|
+
/** @internal is this install (token from engine._modInst) still the module installed under its name? */
|
|
283
|
+
_isLive(name, inst) { return !this.disposed && inst !== undefined && this._modInst.get(name) === inst; },
|
|
284
|
+
/** @internal the ctx install / init receive: track(handle) ties a handle to the module's life (see the top of this file) */
|
|
285
|
+
_modCtx(m, inst = this._modInst.get(m.name)) {
|
|
286
|
+
const name = m.name;
|
|
287
|
+
const stale = () => { if (this._isLive(name, inst)) return false; if (DEV && !this.disposed) warnOnce(coded('module-handle', fmt(STALE, { name }))); return true; };
|
|
288
|
+
const spent = { owner: name, active: false, remove() {}, change: () => false, move: () => false }; // what a verb of a gone install answers: every handle shape, doing nothing
|
|
289
|
+
const ifLive = fn => (...a) => (stale() ? spent : fn(...a));
|
|
290
|
+
const track = h => {
|
|
291
|
+
if (typeof h?.remove !== 'function') throw codedError('module-handle', fmt(BAD_HANDLE, { name, got: String(h) }));
|
|
292
|
+
// a registration from an install that is gone (replaced / unloaded while its async init awaited, or a dispose): filing it under the name would hand it
|
|
293
|
+
// to the newcomer, which would then own a listener it never made; remove it now instead
|
|
294
|
+
if (stale()) { h.remove(); return h; }
|
|
295
|
+
let set = this._modTracked.get(name);
|
|
296
|
+
if (!set) this._modTracked.set(name, set = new Set());
|
|
297
|
+
set.add(h);
|
|
298
|
+
if (h._timer && this._modState.get(name) !== 'running') this.session._keepTimer(h._timer);
|
|
299
|
+
if (this._curModule === m) this._picture?.learn(m); // the module's own code called this: its file is the part's (core/inspect/pictureWriters.js)
|
|
300
|
+
return h;
|
|
301
|
+
};
|
|
302
|
+
// mod: engine.mod with the module as owner, tracked. Why a ctx verb and not "guess the running module": in an async callback the guess is wrong;
|
|
303
|
+
// and a handle that is not tracked is a weather multiplier still on after the module went
|
|
304
|
+
const mod = ifLive((point, o) => {
|
|
305
|
+
if (o?.owner !== undefined) throw codedError('mod-owner', fmt(CTX_OWNER, { point, name }));
|
|
306
|
+
return track(this.mod(point, { ...o, owner: name }));
|
|
307
|
+
});
|
|
308
|
+
// borrow: write values on an object the module does not own (a renderer setting, scene.fog, the engine dome's visible) and give them back when it goes.
|
|
309
|
+
// Why compare on the way back: a later legal takeover (the game set its own fog meanwhile) must win, so a value goes back only if it is still what this borrow left there.
|
|
310
|
+
// Why read back after writing: a setter may keep something else than it was handed, and that is what "still mine" has to compare with.
|
|
311
|
+
// Why one holder: a borrow is one party's temporary use. Two overlapping ones ended oldest first brought an ended value back, and a value with two parties is what
|
|
312
|
+
// shared points own (engine.mod). A holder whose value the game replaced has lost it, so that property is free again.
|
|
313
|
+
const borrow = ifLive((obj, values) => {
|
|
314
|
+
if (!obj || typeof obj !== 'object' || !values || typeof values !== 'object') throw codedError('module-handle', fmt(BAD_BORROW, { name, got: `${String(obj)}, ${String(values)}` }));
|
|
315
|
+
let lent = this._borrowed.get(obj);
|
|
316
|
+
if (!lent) this._borrowed.set(obj, lent = new Map());
|
|
317
|
+
for (const key of Object.keys(values)) {
|
|
318
|
+
const t = lent.get(key);
|
|
319
|
+
if (t && Object.is(obj[key], t.wrote)) throw codedError('module-handle', fmt(BORROW_HELD, { name, key, holder: t.name }));
|
|
320
|
+
}
|
|
321
|
+
const taken = Object.keys(values).map(key => { const was = obj[key]; obj[key] = values[key]; const t = { key, was, wrote: obj[key], name }; lent.set(key, t); return t; });
|
|
322
|
+
const h = { borrow: true, remove: () => {
|
|
323
|
+
for (const t of taken.splice(0)) {
|
|
324
|
+
if (Object.is(obj[t.key], t.wrote)) obj[t.key] = t.was;
|
|
325
|
+
if (lent.get(t.key) === t) lent.delete(t.key);
|
|
326
|
+
}
|
|
327
|
+
this._modTracked.get(name)?.delete(h); // a module that borrows often (a cutscene a minute) does not pile up dead handles, as with control below
|
|
328
|
+
} };
|
|
329
|
+
return track(h);
|
|
330
|
+
});
|
|
331
|
+
// input: declare actions / bind the keys the game handed the module, owned by the module (removed with it); never a key of its own
|
|
332
|
+
const input = {
|
|
333
|
+
action: ifLive((n, o) => track(this.input.action(n, { ...o, owner: name }))),
|
|
334
|
+
bind: ifLive((n, keys) => track(this.input.bind(n, keys, { owner: name }))),
|
|
335
|
+
};
|
|
336
|
+
// control: engine.control.take with the module as default owner, tracked, so a module that goes (unload, rollback, replaces) hands back every
|
|
337
|
+
// character it was steering. Unlike mod an owner may be given: one module can hold several characters on its own names (one per cutscene run).
|
|
338
|
+
// A hold that ends by itself leaves the tracked set too, so a module taking control often (a cutscene a minute) does not pile up dead handles.
|
|
339
|
+
// Taking the same character again under the same owner replaces the hold, so the stale handle leaves the tracked set as well.
|
|
340
|
+
const held = new Map(); // `${id} ${owner}` -> the live handle
|
|
341
|
+
const control = {
|
|
342
|
+
take: ifLive((who, o = {}) => {
|
|
343
|
+
const h = this.session._untrack(this.control.take(who, { ...o, owner: o.owner ?? name })), end = h.remove, key = `${h.id} ${h.owner}`;
|
|
344
|
+
const old = held.get(key);
|
|
345
|
+
if (old) this._modTracked.get(name)?.delete(old);
|
|
346
|
+
held.set(key, h);
|
|
347
|
+
h.remove = () => { end(); if (held.get(key) === h) held.delete(key); this._modTracked.get(name)?.delete(h); };
|
|
348
|
+
return track(h);
|
|
349
|
+
}),
|
|
350
|
+
has: (who, owner = name) => this.control.has(who, owner),
|
|
351
|
+
};
|
|
352
|
+
// whileCompiling: a one-time warm-up (a WASM library's first call) run while start() waits for the GPU to compile shaders, when the page's
|
|
353
|
+
// thread is idle anyway (startup.js); after start() it runs at once
|
|
354
|
+
// It checks the install like track does: a warm-up queued by an install that was unloaded before start() ran the queue must not run
|
|
355
|
+
// (it would touch state of an install that is gone), and one asked for by an install that is already stale is not queued at all
|
|
356
|
+
const whileCompiling = fn => {
|
|
357
|
+
if (!this._isLive(name, inst)) return;
|
|
358
|
+
const run = () => { if (this._isLive(name, inst)) fn(); };
|
|
359
|
+
if (this.ready) run(); else this._whileCompiling.push(run);
|
|
360
|
+
};
|
|
361
|
+
// one scope for everything a module registers, so unload, rollback and a failed init all clean up through _dropTracked and none of them needs its own list.
|
|
362
|
+
// Why ctx verbs and not "the module installing now": the callback that registers may run long after install; inst says which install it belongs to
|
|
363
|
+
const own = (kind, id, h) => track(Object.assign(h, { kind, id, owner: name, inst }));
|
|
364
|
+
const owned = (kind, add) => ifLive((id, ...rest) => own(kind, id, add(id, ...rest)));
|
|
365
|
+
// a part keeps its data only when the module ran: a rolled-back or failed install has only half-built state to offer (Saves.register)
|
|
366
|
+
const register = ifLive((key, part) => {
|
|
367
|
+
const h = this.saves.register(key, part);
|
|
368
|
+
return own('save', key, { remove: () => h.remove({ keep: this._isLive(name, inst) && this._modState.get(name) === 'running' }) });
|
|
369
|
+
});
|
|
370
|
+
// declared, not just called: _planUse finds a ground conflict from provides before anything installs, which a call inside install() could not give
|
|
371
|
+
const provideGround = ifLive(g => {
|
|
372
|
+
if (!m.provides?.includes('ground')) throw codedError('module-provides', fmt(STRINGS.groundClaim, { name }));
|
|
373
|
+
return own('ground', 'ground', this._provideGround(g));
|
|
374
|
+
});
|
|
375
|
+
// feeds: this module puts data into whoever holds that capability. fn runs when a new holder arrives, before its use() returns, and leaves with this module
|
|
376
|
+
const feeds = (capability, fn) => {
|
|
377
|
+
const f = { name: capability, fn };
|
|
378
|
+
(this._feeders ??= []).push(f);
|
|
379
|
+
return track({ remove: () => this._feeders.splice(this._feeders.indexOf(f), 1) });
|
|
380
|
+
};
|
|
381
|
+
// signal: aborts when this install ends (_dropTracked), the one lifecycle; an async init checks it after each await instead of keeping its own flag
|
|
382
|
+
return { name, signal: inst?.ac.signal, track, mod, borrow, feeds, input, control, whileCompiling,
|
|
383
|
+
// rule: a replaceable rule of this module, set by anyone with engine.mod(name, { owner, id?, set }). Not tracked: the point outlives a module that shares it, its entries go with their owners
|
|
384
|
+
rule: (n, def, names) => this.stacks.rule(n, def, names),
|
|
385
|
+
ops: { define: owned('op', (n, def) => this.ops.define(n, def)) },
|
|
386
|
+
saves: { register },
|
|
387
|
+
ui: { define: owned('ui', (n, factory, def) => this.ui.define(n, factory, def)) },
|
|
388
|
+
stream: { addReadyCheck: owned('ready', (n, fn) => this.stream.addReadyCheck(n, fn)) },
|
|
389
|
+
budget: { metric: owned('metric', (n, read, o) => this.budget.metric(n, read, o)) },
|
|
390
|
+
things: { addSource: ifLive(src => own('source', name, this._things.addSource(src))), explainWith: ifLive(fn => own('explainer', name, this.explainWith(fn))) },
|
|
391
|
+
ground: { provide: provideGround, addColliders: ifLive(fn => own('colliders', name, this.addGroundColliders(fn))) },
|
|
392
|
+
};
|
|
393
|
+
},
|
|
394
|
+
/** @internal remove every handle a module tracked, newest first like dispose; one that throws is reported and the rest still go */
|
|
395
|
+
_dropTracked(name) {
|
|
396
|
+
this._modInst.get(name)?.ac.abort(); // ctx.signal: the install is over (unload, rollback, failed init), async work it started stops
|
|
397
|
+
const set = this._modTracked.get(name);
|
|
398
|
+
if (!set) return;
|
|
399
|
+
this._modTracked.delete(name);
|
|
400
|
+
for (const h of [...set].reverse()) { if (h._timer) this.session._dropTimer(h._timer); try { h.remove(); } catch (err) { reportError(this, err, `remove() of a handle module ${name} tracked`, { soft: true }); } }
|
|
401
|
+
},
|
|
402
|
+
/**
|
|
403
|
+
* @internal a module disabled after an error stays installed, so its other handles wait for unload, but what it borrowed goes back now: nothing keeps that value up any more.
|
|
404
|
+
* Newest first, like unload: oldest first would leave a first borrow's value in place of the original.
|
|
405
|
+
*/
|
|
406
|
+
_returnBorrowed(name) {
|
|
407
|
+
for (const h of [...this._modTracked.get(name) ?? []].reverse()) if (h.borrow) {
|
|
408
|
+
try { h.remove(); } catch (err) { reportError(this, err, `remove() of a borrow module ${name} made`, { soft: true }); }
|
|
409
|
+
}
|
|
410
|
+
},
|
|
411
|
+
/** @internal move a module to a new state and refresh the hooks (initializing / failed modules run none) */
|
|
412
|
+
_setModState(m, state) {
|
|
413
|
+
if (this.disposed || this._modState.get(m.name) === state) return;
|
|
414
|
+
this._modState.set(m.name, state);
|
|
415
|
+
this._sortHooks();
|
|
416
|
+
},
|
|
417
|
+
/**
|
|
418
|
+
* Where each module is: 'registered' (init not started yet), 'initializing', 'running', 'failed' (init threw: no hooks), 'disabled' (a picture or ui module that threw while
|
|
419
|
+
* running: switched off, the game goes on), 'blocked' (a provider it requires is not running: no init, no hooks; engine.catalog(name).blockedBy says which) or 'disposed'.
|
|
420
|
+
* @returns {Record<string, string>}
|
|
421
|
+
* @example engine.use(shop()); await engine.loading.settled(); engine.explain({ module: 'shop' }).ok // true
|
|
422
|
+
*/
|
|
423
|
+
/** @internal */
|
|
424
|
+
get moduleStates() {
|
|
425
|
+
return Object.fromEntries([...this._modState].map(([n, s]) => [n, s !== 'failed' && s !== 'disposed' && this._modBlocked.has(n) ? 'blocked' : s]));
|
|
426
|
+
},
|
|
427
|
+
/**
|
|
428
|
+
* What this game can do, read from the registrations (see core/inspect/catalog.js): no argument = short list, a module id or op name = that entry expanded.
|
|
429
|
+
* @param {string | { find?: string }} [id]
|
|
430
|
+
* @returns {any}
|
|
431
|
+
* @example engine.catalog(); engine.catalog('sky'); engine.catalog('shop.buy'); engine.catalog({ find: 'buy' })
|
|
432
|
+
*/
|
|
433
|
+
catalog(id) { return catalog(this, id); },
|
|
434
|
+
/**
|
|
435
|
+
* Is a module of this name, or a provider of this capability, installed? Installed only: engine.explain({ module: name }) says whether it is running.
|
|
436
|
+
* @param {string} name
|
|
437
|
+
* @example if (!engine.has('inventory')) engine.use(inventory());
|
|
438
|
+
*/
|
|
439
|
+
has(name) { return this.modules.has(name) || this._provided(name); },
|
|
440
|
+
/** @internal Can this module or capability be called now? True once it is running: init finished, nothing it requires is down, not disabled after an error. Game code asks engine.explain({ module }) */
|
|
441
|
+
usable(name) {
|
|
442
|
+
return giversOf([...this.modules.values()], name).some(m => this._modState.get(m.name) === 'running' && !this._modBlocked.has(m.name));
|
|
443
|
+
},
|
|
444
|
+
/** Run order of module hooks (module names, first to last), for debugging "who runs first". */
|
|
445
|
+
get moduleOrder() { return this._moduleOrder ?? []; },
|
|
446
|
+
|
|
447
|
+
/** Re-sort the module hooks in the main loop (disabled picture / ui modules are not put back). */
|
|
448
|
+
_sortHooks() {
|
|
449
|
+
const order = sortModules([...this.modules.values()]);
|
|
450
|
+
this._moduleOrder = order.map(m => m.name);
|
|
451
|
+
this._refreshBlocks();
|
|
452
|
+
for (const k of HOOKS) this._hooks[k] = [];
|
|
453
|
+
for (const m of order) {
|
|
454
|
+
const st = this._modState.get(m.name);
|
|
455
|
+
if (st !== 'running' || this._modBlocked.has(m.name)) continue; // registered (init not run yet), initializing, failed, disabled, blocked: no hooks
|
|
456
|
+
let c = hookCache.get(m);
|
|
457
|
+
if (!c) hookCache.set(m, c = {});
|
|
458
|
+
for (const k of HOOKS) if (m[k]) this._hooks[k].push(c[k] ??= { fn: m[k].bind(m), name: m.name, mod: m });
|
|
459
|
+
}
|
|
460
|
+
this._initWaiting();
|
|
461
|
+
this._warnContractGaps();
|
|
462
|
+
},
|
|
463
|
+
/** @internal who is blocked now: derived from the states on every change, so install, unload, replace and a failed init need no rule of their own */
|
|
464
|
+
_refreshBlocks() {
|
|
465
|
+
const mods = [...this.modules.values()], seen = new Map(), blocks = new Map(), dead = new Set();
|
|
466
|
+
const up = m => {
|
|
467
|
+
if (seen.has(m)) return seen.get(m);
|
|
468
|
+
seen.set(m, true); // a requires cycle does not block itself
|
|
469
|
+
const by = [];
|
|
470
|
+
for (const dep of m.requires ?? []) {
|
|
471
|
+
const givers = giversOf(mods, dep);
|
|
472
|
+
if (givers.some(up)) continue;
|
|
473
|
+
const p = givers[0], state = !p ? 'missing' : blocks.has(p.name) ? 'blocked' : this._modState.get(p.name);
|
|
474
|
+
by.push({ requires: dep, module: p?.name ?? null, state });
|
|
475
|
+
if (state === 'failed' || dead.has(p?.name)) dead.add(m.name); // waiting ends by itself; a failure does not
|
|
476
|
+
}
|
|
477
|
+
if (by.length) blocks.set(m.name, by);
|
|
478
|
+
const ok = !by.length && this._modState.get(m.name) === 'running';
|
|
479
|
+
seen.set(m, ok);
|
|
480
|
+
return ok;
|
|
481
|
+
};
|
|
482
|
+
mods.forEach(up);
|
|
483
|
+
this._modBlocked = blocks;
|
|
484
|
+
for (const name of dead) {
|
|
485
|
+
const m = this.modules.get(name), inst = this._modInst.get(name);
|
|
486
|
+
if (!m.critical || this._modFatal.has(inst)) continue;
|
|
487
|
+
this._modFatal.add(inst);
|
|
488
|
+
const b = blocks.get(name)[0], err = codedError('module-critical', fmt(STRINGS.critical, { name, dep: b.requires, by: b.module, state: b.state }));
|
|
489
|
+
if (this._initsDone) reportError(this, err, fmt(STRINGS.lateInit, { name }), { module: m });
|
|
490
|
+
else this.loading._fail(this.loading._begin(name, 'module', { critical: true }), err); // start() stops on it, like a critical init that threw
|
|
491
|
+
}
|
|
492
|
+
},
|
|
493
|
+
/** Called by start(): warn once in dev when an optional dependency written as { module: 'what is lost' } is not installed. */
|
|
494
|
+
_checkOptional() {
|
|
495
|
+
if (!DEV) return;
|
|
496
|
+
for (const m of this.modules.values()) {
|
|
497
|
+
const opt = m.optional;
|
|
498
|
+
if (!opt || Array.isArray(opt)) continue;
|
|
499
|
+
for (const [dep, what] of Object.entries(opt)) if (!this.has(dep))
|
|
500
|
+
warnOnce(coded('module-requires', fmt(STRINGS.optional, { name: m.name, dep, what })));
|
|
501
|
+
}
|
|
502
|
+
},
|
|
503
|
+
};
|