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
package/core/Jobs.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// engine.jobs: a frame-sliced job scheduler. Build work (streaming, prop instancing, merging, cache reads) is queued and each frame spends at most budgetMs, so startup does not hitch.
|
|
2
|
+
// await engine.jobs.add(() => buildHouse()); // plain function: runs to completion in one go
|
|
3
|
+
// engine.jobs.add(function* () { for (const p of props) { place(p); yield; } }); // generator: may pause at each yield until the next frame
|
|
4
|
+
// engine.jobs.add(fn, { priority: 10 }) // higher priority first (FIFO within a priority)
|
|
5
|
+
// Returns a Promise of the job's result (a returned Promise is awaited). Runs after the frame hooks each frame.
|
|
6
|
+
// Jobs that change gameplay state pass apply: the result takes effect on a fixed tick through engine.commits, not on whichever frame the work finished (machine speed must not affect gameplay):
|
|
7
|
+
// engine.jobs.add(function* () { ...compute...; yield; ...; return result; }, { apply: result => changeGameplayState })
|
|
8
|
+
// If the job is not done by the due tick, the remaining steps run to completion on the spot, so such a job must be a plain function or generator (it cannot return a Promise).
|
|
9
|
+
// With apply, the returned Promise resolves when the work finishes, which may be before apply runs (it waits for the fixed tick); put anything that needs "state already changed" inside apply, do not assume it after await.
|
|
10
|
+
// A single step that is too slow (one next() over slowStepMs in the real-time loop) warns once in dev: add more yields to a loop to slice it, since the budget only limits how many steps run, it cannot split one step.
|
|
11
|
+
// Two ways to advance:
|
|
12
|
+
// Real-time loop: at most budgetMs per frame (loadingMs while the loading screen is up), always at least one step so a slow job cannot starve.
|
|
13
|
+
// Deterministic (engine.step(), headless loading): ignores real time and drains the queue on each run (generators run to the end);
|
|
14
|
+
// to stop jobs that keep adding jobs from hanging, one run takes at most maxSteps steps (default 100000), warns once past that, and continues next frame.
|
|
15
|
+
// The queue is a binary heap (priority, then insertion order), so thousands of queued builds stay fast.
|
|
16
|
+
import { warnOnce } from './validate.js';
|
|
17
|
+
import { codedError, coded } from './errorHints.js';
|
|
18
|
+
|
|
19
|
+
const STRINGS = { slow: 'engine.jobs: one job step took {ms} ms (over {max}) and will hitch the frame; add more yield calls in the loop to slice it', async: 'engine.jobs.add(..., { apply }): a job that changes gameplay state cannot return a Promise (it must be finishable on the spot when due); make it a plain function or generator', tooMany: 'engine.jobs: deterministic advance (step / headless) did not finish within {n} steps; the rest continues next frame (is a job endlessly adding new jobs?)' };
|
|
20
|
+
|
|
21
|
+
// a runs before b: higher priority first, then earlier insertion
|
|
22
|
+
const before = (a, b) => a.priority > b.priority || (a.priority === b.priority && a.seq < b.seq);
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* engine.jobs queues build work in a binary heap (higher priority first, FIFO within a priority).
|
|
26
|
+
* In the real-time loop each frame spends at most budgetMs; engine.step() and headless loading ignore real time and drain the queue each frame (reproducible results).
|
|
27
|
+
*/
|
|
28
|
+
export class Jobs {
|
|
29
|
+
/** @internal */
|
|
30
|
+
constructor(engine) {
|
|
31
|
+
/** @internal */ this.engine = engine;
|
|
32
|
+
/** Milliseconds allowed per frame, default 3 */
|
|
33
|
+
this.budgetMs = 3;
|
|
34
|
+
/** Milliseconds allowed per frame while the loading screen is up, default 12 */
|
|
35
|
+
this.loadingMs = 12;
|
|
36
|
+
/** Max steps per deterministic run (stops jobs that keep adding jobs from hanging), default 100000 */
|
|
37
|
+
this.maxSteps = 100000;
|
|
38
|
+
/** A step slower than this many ms warns in dev (default 8) */
|
|
39
|
+
this.slowStepMs = 8;
|
|
40
|
+
/** @internal */ this.heap = [];
|
|
41
|
+
/** @internal */ this._seq = 0;
|
|
42
|
+
/** @internal Total finished jobs (for describe) */ this.doneCount = 0;
|
|
43
|
+
}
|
|
44
|
+
/** Number of jobs not yet finished @returns {number} */
|
|
45
|
+
get pending() { return this.heap.length; }
|
|
46
|
+
/** @internal Drop queued jobs (called by engine.dispose; their Promises never settle) */
|
|
47
|
+
dispose() { this.heap.length = 0; }
|
|
48
|
+
/**
|
|
49
|
+
* Add a job: a plain function runs in one go, a generator may pause at each yield until the next frame; higher priority runs first; returns the job's result.
|
|
50
|
+
* A job that changes gameplay state passes apply: the result takes effect on a fixed tick via engine.commits (lag fixed steps later, default 30), and is finished on the spot if not done by then, so machine speed does not affect gameplay.
|
|
51
|
+
* Such a job must be a plain function or generator (it cannot return a Promise). With apply, the returned Promise resolves when the work finishes, before apply may have run; put logic that needs "state already changed" inside apply. A step over slowStepMs warns in dev to slice it with yield.
|
|
52
|
+
* @template [T=any]
|
|
53
|
+
* @param {(() => T) | (() => Generator<any, T, any>) | Generator<any, T, any>} work
|
|
54
|
+
* valid (with apply): still wanted when due? Default: dropped when a save load or level change happened since add.
|
|
55
|
+
* @param {{ priority?: number, apply?: ((result: T) => void) | null, lag?: number, valid?: () => boolean }} [opts]
|
|
56
|
+
* @returns {Promise<T>}
|
|
57
|
+
* @example await engine.jobs.add(function* () { for (const p of props) { place(p); yield; } }, { priority: 10 });
|
|
58
|
+
*/
|
|
59
|
+
add(work, opts = {}) {
|
|
60
|
+
const { priority = 0, apply = null, lag, valid } = opts, c = this.engine.commits, epoch = c.epoch;
|
|
61
|
+
return new Promise((res, rej) => {
|
|
62
|
+
const j = { work, priority, seq: this._seq++, res, rej, it: null, ticket: null };
|
|
63
|
+
const still = () => !j.failed && (valid ? valid() : c.epoch === epoch);
|
|
64
|
+
if (apply) j.ticket = c.request({ apply, lag, fallback: () => this._finishNow(j), valid: still });
|
|
65
|
+
this._push(j);
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
/** @internal Not done by the due tick: run the remaining steps now and return the result */
|
|
69
|
+
_finishNow(j) {
|
|
70
|
+
while (!j.finished && !j.failed) this._step(j);
|
|
71
|
+
if (j.failed) throw j.error;
|
|
72
|
+
return j.value;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Run the queue (the engine calls this each frame): by millisecond budget by default; deterministic: true ignores real time and drains it (used by step)
|
|
76
|
+
* @param {{ deterministic?: boolean }} [opts]
|
|
77
|
+
*/
|
|
78
|
+
run(opts = {}) {
|
|
79
|
+
const { deterministic = false } = opts;
|
|
80
|
+
if (!this.heap.length) return;
|
|
81
|
+
if (deterministic) {
|
|
82
|
+
let n = 0;
|
|
83
|
+
while (this.heap.length && n++ < this.maxSteps) this._stepTop();
|
|
84
|
+
if (this.heap.length) warnOnce(coded('jobs-slow', STRINGS.tooMany.replace('{n}', this.maxSteps)));
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
const end = performance.now() + (this.engine.ready ? this.budgetMs : Math.max(this.budgetMs, this.loadingMs)); // measure: frame budget
|
|
88
|
+
let first = true;
|
|
89
|
+
while (this.heap.length && (first || performance.now() < end)) { first = false; this._stepTop(); } // measure: frame budget
|
|
90
|
+
}
|
|
91
|
+
/** @internal Advance the top job by one step */
|
|
92
|
+
_stepTop() { this._step(this.heap[0]); }
|
|
93
|
+
/** @internal */
|
|
94
|
+
_step(j) {
|
|
95
|
+
const t0 = performance.now(); // measure: step time
|
|
96
|
+
try {
|
|
97
|
+
if (!j.it) {
|
|
98
|
+
const r = typeof j.work === 'function' ? j.work() : j.work;
|
|
99
|
+
if (typeof r?.next !== 'function') { this._finish(j, r); return; }
|
|
100
|
+
j.it = r;
|
|
101
|
+
}
|
|
102
|
+
const s = j.it.next();
|
|
103
|
+
if (s.done) this._finish(j, s.value);
|
|
104
|
+
} catch (err) { this._removeJob(j); j.failed = true; j.error = err; j.rej(err); }
|
|
105
|
+
const ms = performance.now() - t0; // measure: step time
|
|
106
|
+
if (ms > this.slowStepMs && this.engine.ready) warnOnce(coded('jobs-slow', STRINGS.slow.replace('{ms}', Math.round(ms)).replace('{max}', this.slowStepMs)));
|
|
107
|
+
}
|
|
108
|
+
/** @internal */
|
|
109
|
+
_finish(j, v) {
|
|
110
|
+
if (j.ticket && typeof v?.then === 'function') throw codedError('engine-misuse', STRINGS.async);
|
|
111
|
+
this._removeJob(j); this.doneCount++; j.finished = true; j.value = v; j.ticket?.resolve(v); j.res(v);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ---------- binary heap ----------
|
|
115
|
+
/** @internal */
|
|
116
|
+
_push(j) {
|
|
117
|
+
this.heap.push(j);
|
|
118
|
+
this._siftUp(this.heap.length - 1);
|
|
119
|
+
}
|
|
120
|
+
/** @internal Remove a job (usually the top; not the top if a higher-priority job was added mid-run) */
|
|
121
|
+
_removeJob(j) {
|
|
122
|
+
const h = this.heap, i = h.indexOf(j);
|
|
123
|
+
if (i < 0) return;
|
|
124
|
+
const last = h.pop();
|
|
125
|
+
if (i === h.length) return;
|
|
126
|
+
h[i] = last;
|
|
127
|
+
this._siftDown(i); this._siftUp(i);
|
|
128
|
+
}
|
|
129
|
+
/** @internal */
|
|
130
|
+
_siftUp(i) {
|
|
131
|
+
const h = this.heap;
|
|
132
|
+
while (i > 0) { const p = (i - 1) >> 1; if (!before(h[i], h[p])) break; [h[i], h[p]] = [h[p], h[i]]; i = p; }
|
|
133
|
+
}
|
|
134
|
+
/** @internal */
|
|
135
|
+
_siftDown(i) {
|
|
136
|
+
const h = this.heap, n = h.length;
|
|
137
|
+
for (;;) {
|
|
138
|
+
const l = 2 * i + 1, r = l + 1;
|
|
139
|
+
let m = i;
|
|
140
|
+
if (l < n && before(h[l], h[m])) m = l;
|
|
141
|
+
if (r < n && before(h[r], h[m])) m = r;
|
|
142
|
+
if (m === i) return;
|
|
143
|
+
[h[i], h[m]] = [h[m], h[i]]; i = m;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
package/core/Loading.js
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// engine.loading: one observable view of everything startup (and later on-demand loading) is waiting for.
|
|
2
|
+
// Asset loads, module init / isReady, the stream's required builds and the game's own steps (track) all appear here, so
|
|
3
|
+
// describe().loading, the dev bridge (threedog loading) and the loading-screen part read the same answer to
|
|
4
|
+
// "what are we waiting for, what failed, does it block the start".
|
|
5
|
+
//
|
|
6
|
+
// Each task: name, kind (model / texture / sound / module / stream / step), phase (queued -> download -> decode -> upload / build -> done | failed),
|
|
7
|
+
// progress 0-1, critical, error { message, url, status }, missing (referenced files that failed), fallback, source { manifest, url, version, bytes, animations }.
|
|
8
|
+
// Finished is not the same as succeeded: view().done says nothing is pending, view().ok says nothing failed.
|
|
9
|
+
|
|
10
|
+
const END = new Set(['done', 'failed']);
|
|
11
|
+
const VERB = { queued: 'queued', download: 'downloading', decode: 'decoding', upload: 'uploading to the GPU', build: 'building', module: 'waiting for module' };
|
|
12
|
+
const LIST_MAX = 8; // describe stays short: the full list is engine.loading.list()
|
|
13
|
+
|
|
14
|
+
class Task {
|
|
15
|
+
constructor(name, kind, { critical = false, url = null, manifest = null } = {}) {
|
|
16
|
+
this.name = name; this.kind = kind; this.critical = critical;
|
|
17
|
+
this.phase('queued');
|
|
18
|
+
this.error = null; this.missing = []; this.fallback = null;
|
|
19
|
+
this.source = { manifest, url, version: null, bytes: null, animations: null };
|
|
20
|
+
}
|
|
21
|
+
/** @param {string} p queued | download | decode | upload | build | done | failed @param {number} [progress] */
|
|
22
|
+
phase(p, progress = 0) { this.state = p; this.progress = progress; }
|
|
23
|
+
toJSON() {
|
|
24
|
+
const o = { name: this.name, kind: this.kind, phase: this.state, progress: Math.round(this.progress * 100) / 100, critical: this.critical };
|
|
25
|
+
if (this.error) o.error = this.error;
|
|
26
|
+
if (this.missing.length) o.missing = this.missing;
|
|
27
|
+
if (this.fallback) o.fallback = this.fallback;
|
|
28
|
+
o.source = this.source;
|
|
29
|
+
return o;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export class Loading {
|
|
34
|
+
/** @param {any} engine */
|
|
35
|
+
constructor(engine) {
|
|
36
|
+
this.engine = engine; this.tasks = new Map();
|
|
37
|
+
this._inits = new Set(); // init() of modules installed after start(), in flight
|
|
38
|
+
/** How long start() waits for modules whose isReady stays false before it rejects naming them (ms) @type {number} */
|
|
39
|
+
this.timeoutMs = 120000;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** @internal keep a late module init in flight until it ends (settled() waits for these) */
|
|
43
|
+
_track(p) { this._inits.add(p); p.finally(() => this._inits.delete(p)); }
|
|
44
|
+
/**
|
|
45
|
+
* Resolves when every module installed after start() has finished its init() (also when one failed: its state is then 'failed' in engine.moduleStates and the error went through the error tiers).
|
|
46
|
+
* engine.use() returns the engine, so await this to know a late module is running.
|
|
47
|
+
* @returns {Promise<void>}
|
|
48
|
+
* @example engine.use(shop()); await engine.loading.settled(); engine.moduleStates.shop // 'running'
|
|
49
|
+
*/
|
|
50
|
+
async settled() { while (this._inits.size) await Promise.allSettled([...this._inits]); }
|
|
51
|
+
|
|
52
|
+
/** Start (or restart) a task; engine-internal callers keep the returned task and move its phase */
|
|
53
|
+
_begin(name, kind, opts) { const t = new Task(name, kind, opts); this.tasks.set(kind + ':' + name, t); return t; } // keyed by kind too: a module and a model may share a name
|
|
54
|
+
_done(t) { t.phase('done', 1); }
|
|
55
|
+
/** Record a failure: err may carry url / status (LoadError) */
|
|
56
|
+
_fail(t, err, fallback = null) {
|
|
57
|
+
t.phase('failed');
|
|
58
|
+
t.error = { message: String(err?.message ?? err), url: err?.url ?? t.source.url, ...(err?.status ? { status: err.status } : {}) };
|
|
59
|
+
t.fallback = fallback;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Run one of the game's own loading steps as a task, so it shows in describe().loading and on the loading screen.
|
|
64
|
+
* critical (default true): when it fails before start() finishes, start() stops with the reason instead of starting a broken game.
|
|
65
|
+
* @template T
|
|
66
|
+
* @param {string} name e.g. 'level-data'
|
|
67
|
+
* @param {() => Promise<T>} fn
|
|
68
|
+
* @param {{ critical?: boolean }} [opts]
|
|
69
|
+
* @returns {Promise<T>}
|
|
70
|
+
* @example const data = await engine.loading.track('level-data', () => fetch('/levels/1.json').then(r => r.json()));
|
|
71
|
+
*/
|
|
72
|
+
async track(name, fn, { critical = true } = {}) {
|
|
73
|
+
const t = this._begin(name, 'step', { critical });
|
|
74
|
+
t.phase('build');
|
|
75
|
+
try { const v = await fn(); this._done(t); return v; } catch (err) { this._fail(t, err); throw err; }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* One task with its source (which manifest, which path, file version / size, animation names), or null.
|
|
80
|
+
* @param {string} name asset name (or path for unregistered loads), module name, or track() name
|
|
81
|
+
* @param {string} [kind] model / texture / sound / module / step, when one name is used by several kinds
|
|
82
|
+
* @example engine.loading.get('hero') // { phase: 'done', source: { manifest: 'main', url: '/models/hero.glb', animations: ['idle', 'walk'] } ... }
|
|
83
|
+
*/
|
|
84
|
+
get(name, kind) {
|
|
85
|
+
const t = kind ? this.tasks.get(kind + ':' + name) : [...this.tasks.values()].find(x => x.name === name);
|
|
86
|
+
return t?.toJSON() ?? null;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Every task so far (JSON-able), optionally only one kind or phase.
|
|
90
|
+
* @param {{ kind?: string, phase?: string }} [filter]
|
|
91
|
+
* @example engine.loading.list({ phase: 'failed' })
|
|
92
|
+
*/
|
|
93
|
+
list({ kind, phase } = {}) {
|
|
94
|
+
return [...this.tasks.values()].filter(t => (!kind || t.kind === kind) && (!phase || t.state === phase)).map(t => t.toJSON());
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Pending items: unfinished tasks + modules whose isReady is false + the stream's required builds (live, not stored) */
|
|
98
|
+
_pending() {
|
|
99
|
+
const e = this.engine, out = [...this.tasks.values()].filter(t => !END.has(t.state));
|
|
100
|
+
for (const m of e.modules.values()) if (m.isReady && !m.isReady(e)) out.push(Object.assign(new Task(m.name, 'module', { critical: true }), { state: 'build', label: e.moduleName(m) }));
|
|
101
|
+
if (!e.stream.ready) out.push(Object.assign(new Task('stream', 'stream', { critical: true }), { state: 'build' }));
|
|
102
|
+
return out;
|
|
103
|
+
}
|
|
104
|
+
/** The item to name when asked "what are we waiting for": a critical one first, the furthest along last */
|
|
105
|
+
_current(pending) { return pending.find(t => t.critical) ?? pending[0] ?? null; }
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* The summary describe().loading shows. done: nothing pending; ok: nothing failed and no missing references;
|
|
109
|
+
* blocked: a critical item failed before start() finished; waiting: one English line naming the current item.
|
|
110
|
+
* @returns {import('../types/core').LoadingView}
|
|
111
|
+
*/
|
|
112
|
+
view() {
|
|
113
|
+
const pending = this._pending(), all = [...this.tasks.values()];
|
|
114
|
+
const failed = all.filter(t => t.state === 'failed'), warned = all.filter(t => t.state === 'done' && t.missing.length);
|
|
115
|
+
const cur = this._current(pending);
|
|
116
|
+
return {
|
|
117
|
+
done: !pending.length, ok: !failed.length && !warned.length,
|
|
118
|
+
blocked: !this.engine.ready && failed.some(t => t.critical),
|
|
119
|
+
waiting: cur ? waitingText(cur) : null,
|
|
120
|
+
pending: pending.slice(0, LIST_MAX).map(t => ({ name: t.name, kind: t.kind, phase: t.state, progress: Math.round(t.progress * 100) / 100, critical: t.critical })),
|
|
121
|
+
failed: failed.slice(0, LIST_MAX).map(t => t.toJSON()),
|
|
122
|
+
warnings: warned.slice(0, LIST_MAX).map(t => ({ name: t.name, missing: t.missing, source: t.source })),
|
|
123
|
+
counts: { total: all.length, done: all.length - failed.length - all.filter(t => !END.has(t.state)).length, failed: failed.length, pending: pending.length },
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Player-facing text for the loading screen (i18n keys loading.<phase>); null when nothing is pending */
|
|
128
|
+
text() {
|
|
129
|
+
const cur = this._current(this._pending());
|
|
130
|
+
if (!cur) return null;
|
|
131
|
+
const e = this.engine, name = cur.label ?? (cur.kind === 'stream' ? e.t('common.world') : cur.name);
|
|
132
|
+
return e.t(cur.kind === 'module' || cur.kind === 'stream' ? 'common.generating' : 'loading.' + cur.state, { name });
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** English line for describe / the bridge: 'decoding model "hero" (/models/hero.glb, manifest "main") 40%' */
|
|
137
|
+
function waitingText(t) {
|
|
138
|
+
const verb = t.kind === 'module' ? VERB.module : VERB[t.state];
|
|
139
|
+
const what = t.kind === 'module' ? `${t.name}${t.label && t.label !== t.name ? ` (${t.label})` : ''}` : t.kind === 'stream' ? 'the stream\'s required nearby builds' : `${t.kind} "${t.name}"`;
|
|
140
|
+
const src = t.source?.url && t.source.url !== t.name ? ` (${t.source.url}${t.source.manifest ? `, manifest "${t.source.manifest}"` : ''})` : '';
|
|
141
|
+
return `${verb} ${what}${src}${t.state === 'download' && t.progress > 0 ? ' ' + Math.round(t.progress * 100) + '%' : ''}`;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** One English line per failure, for the start() error, the bridge and errors.log */
|
|
145
|
+
export function failureText(t) {
|
|
146
|
+
const j = t.toJSON?.() ?? t, s = j.source || {}, err = j.error || {};
|
|
147
|
+
const where = [err.url && err.url !== s.url ? `missing ${err.url}` : null, s.manifest ? `manifest "${s.manifest}"` : null].filter(Boolean);
|
|
148
|
+
return `${j.kind} "${j.name}" <- ${s.url ?? j.name}: ${err.message}${where.length ? ` [${where.join(', ')}]` : ''}`;
|
|
149
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// Material provenance for engine.inspect.scene(): "why is this mesh the wrong colour?" Diagnostics only: reads the material, never changes it.
|
|
2
|
+
// Where the spec came from is userData.materialSource, recorded by makeMaterial (materials without it were not made by makeMaterial).
|
|
3
|
+
const hex = c => '#' + c.getHexString();
|
|
4
|
+
const MAPS = ['map', 'normalMap', 'bumpMap', 'roughnessMap', 'metalnessMap', 'emissiveMap', 'alphaMap', 'aoMap', 'lightMap', 'gradientMap'];
|
|
5
|
+
const SIDES = ['front', 'back', 'double'];
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* @param {any} m a three.js material
|
|
9
|
+
* @param {any} [o] the mesh that uses it (its userData.purpose is the fallback role)
|
|
10
|
+
*/
|
|
11
|
+
export function materialInfo(m, o) {
|
|
12
|
+
const src = m.userData?.materialSource, white = !m.color || m.color.getHex() === 0xffffff;
|
|
13
|
+
const maps = MAPS.filter(k => m[k]).map(k => k === 'map' ? 'map (base colour)' : k === 'normalMap' || k === 'bumpMap' ? `${k} (detail, no colour)` : k);
|
|
14
|
+
const vc = !!m.vertexColors, hasMap = !!m.map;
|
|
15
|
+
const base = hasMap ? (white ? 'map' : `map x color ${hex(m.color)}`) : m.color ? `color ${hex(m.color)}` : 'no color';
|
|
16
|
+
const colorPath = `${base} (vertexColors ${vc ? 'on: also multiplied by the geometry color attribute' : 'off'})`;
|
|
17
|
+
const notes = [];
|
|
18
|
+
if (hasMap && !white) notes.push(`map already carries colour and color ${hex(m.color)} is not white: the result is map x color (fine when it is a tint)`);
|
|
19
|
+
if (vc && o?.geometry && !o.geometry.attributes?.color) notes.push('vertexColors is on but the geometry has no color attribute: it renders black');
|
|
20
|
+
return {
|
|
21
|
+
role: src?.role ?? m.userData?.purpose ?? o?.userData?.purpose ?? null,
|
|
22
|
+
from: src?.from ?? 'unknown (not made by makeMaterial)', keys: src?.keys ?? [],
|
|
23
|
+
type: m.type, color: m.color ? hex(m.color) : null, maps, vertexColors: vc,
|
|
24
|
+
side: SIDES[m.side] ?? m.side, transparent: !!m.transparent, opacity: m.opacity,
|
|
25
|
+
colorPath, ...(notes.length && { notes }),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** One-line text of materialInfo for a list */
|
|
30
|
+
export const infoLine = i => `${i.role ?? '-'} from ${i.from}${i.keys.length ? ` [${i.keys.join(',')}]` : ''} · ${i.type} ${i.color ?? ''} · ${i.colorPath}`
|
|
31
|
+
+ `${i.maps.length ? ' · ' + i.maps.join(', ') : ''}${i.side !== 'front' ? ' · side ' + i.side : ''}${i.transparent || i.opacity < 1 ? ` · transparent=${i.transparent} opacity ${i.opacity}` : ''}`
|
|
32
|
+
+ (i.notes ? '\n note: ' + i.notes.join('; ') : '');
|
package/core/Ops.js
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
// One entry point for actions: engine.ops. An op is one discrete thing an actor (player, NPC, network peer) decides to do:
|
|
2
|
+
// buy, talk, attack, roll, fire, craft, build. Continuous input (stick, look) and simulation (hunger, growth, burning) are not ops;
|
|
3
|
+
// they stay in fixed / world.simulate.
|
|
4
|
+
// engine.ops.define('shop.buy', { args: { shop: 'string', item: 'string' }, can(e, a, ctx) { return true or 'noMoney' }, run(e, a, ctx) { ... } });
|
|
5
|
+
// engine.ops.run('shop.buy', { shop: 'bakery', item: 'bread' }) // -> { ok: true, value } or { ok: false, code, facts, nextActions }
|
|
6
|
+
// Why one entry: UI, keys, bridge, tests, replay and net peers all end in the same run(),
|
|
7
|
+
// checked by the same can(), logged in one history (tick, phase, source, actor): tests need no key timing,
|
|
8
|
+
// the AI can ask "what can I do now", and replay / netcode have a record of who did what on which step.
|
|
9
|
+
// run() is always synchronous: inside a fixed step it is phase 'fixed'; between steps (UI, bridge, tests) phase 'between',
|
|
10
|
+
// which lands "after step N" and replays the same. Args must be plain data and self-contained (aim direction goes in the args).
|
|
11
|
+
// The guard (ops.guard) backs "don't go around it": in dev, saved gameplay state written outside loading, fixed steps and ops
|
|
12
|
+
// is reported (see recipes/23-ops.md). Dev argument checks live in opsCheck.js.
|
|
13
|
+
import { DEV, missingText, warnOnce } from './validate.js';
|
|
14
|
+
import { checkDef, checkArgs, devError, fmt, SOURCES } from './opsCheck.js';
|
|
15
|
+
import { coded } from './errorHints.js';
|
|
16
|
+
import { guardWrite } from './opsGuard.js';
|
|
17
|
+
import { failure, isStructured } from './opsFail.js';
|
|
18
|
+
import { runOp } from './opsRun.js';
|
|
19
|
+
import { newRing, logEntry, recentEntries } from './opsHistory.js';
|
|
20
|
+
import { defaultsOf, withDefaults } from './params.js';
|
|
21
|
+
|
|
22
|
+
const STRINGS = {
|
|
23
|
+
dup: "ops.define('{name}'): already defined. To replace it call remove() on the handle define returned first",
|
|
24
|
+
unknown: 'ops.run({name}): {text}',
|
|
25
|
+
canResult: "{name}'s can must return true or a reason string, e.g. return 'noMoney' (or { code, facts, nextActions }); got {got}",
|
|
26
|
+
badSource: "ops.run('{name}'): source '{source}' is not one of " + SOURCES.join(', '),
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* engine.ops: one entry point for the discrete things players and NPCs decide to do. define registers, run executes (sync, logged), can only asks, list says what exists / what is possible now, recent reads the log.
|
|
31
|
+
* Inside an op use ctx.actor (world record id, default engine.actor = 'player'), never engine.player: NPCs and network peers run the same op as themselves.
|
|
32
|
+
*/
|
|
33
|
+
export class Ops {
|
|
34
|
+
/** @internal */
|
|
35
|
+
constructor(engine) {
|
|
36
|
+
/** @internal */ this.engine = engine;
|
|
37
|
+
/** @internal */ this.defs = new Map();
|
|
38
|
+
/** @internal ring of history entries, allocated once */ this._ring = [];
|
|
39
|
+
/** @internal */ this._head = 0;
|
|
40
|
+
/** @internal */ this._len = 0;
|
|
41
|
+
/** @internal names of the ops currently running (nesting) */ this._stack = [];
|
|
42
|
+
/** @internal */ this._inCan = null;
|
|
43
|
+
/** @internal > 0 while state may be written without an op (save load, applyState, net sync) */ this._allowDepth = 0;
|
|
44
|
+
/** @internal */ this._warned = new Set();
|
|
45
|
+
/** @internal request counter (net replies carry it) */ this._seq = 0;
|
|
46
|
+
/** @internal ctx of the innermost running op (nested ops inherit source and actor) */ this._last = null;
|
|
47
|
+
/** @internal set by net() on clients: (def, args, opts) => result to return instead of running locally, or null to run here */ this._route = null;
|
|
48
|
+
/** @internal set by net() on clients: every write outside allow() is reported, even in fixed steps and ops (own movement, world.move, excepted) */ this._client = false;
|
|
49
|
+
/** Counter bumped on each committed op (an op that failed or rolled back does not bump it); every run result carries it, so "did anything change since I looked" is one compare */
|
|
50
|
+
this.revision = 0;
|
|
51
|
+
/** @internal depth of atomic runs in progress, and after hooks waiting for the outermost one to commit */ this._txDepth = 0; this._txAfter = [];
|
|
52
|
+
this.historySize = 256;
|
|
53
|
+
}
|
|
54
|
+
/** @internal Stamp a failed result with the current revision */
|
|
55
|
+
_res(f) { f.revision = this.revision; return f; }
|
|
56
|
+
/** @internal Name of the innermost op running right now, or null (world records who spawned a runtime record with it, dev only) @type {string | null} */
|
|
57
|
+
get running() { return this._stack.at(-1) ?? null; }
|
|
58
|
+
|
|
59
|
+
/** History entries kept (ring, default 256); setting it clears the history */
|
|
60
|
+
get historySize() { return this._ring.length; }
|
|
61
|
+
set historySize(n) {
|
|
62
|
+
this._ring = newRing(n);
|
|
63
|
+
this._head = 0; this._len = 0;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Register an op. Name it noun.verb. run changes state; can (optional) is read-only and returns true or a reason string; offers (optional) lists the arg sets possible now (for list / describe / the dev bridge `ops` command).
|
|
68
|
+
* args shape types: string number int bool position id any, suffix ? for optional. net: 'peer' lets remote players request it (default: host only);
|
|
69
|
+
* or { type, default, min, max, values, desc } (default is filled in, engine.catalog shows it).
|
|
70
|
+
* atomic: true = world records, inventory containers and vars written by run are rolled back if run fails or throws (events and other state are not; see recipe 23); after(e, args, value, ctx): sound / animation, runs only once the op committed.
|
|
71
|
+
* run (and can) may fail with { ok: false, code, facts, nextActions } (facts: object or list [{ id, field, actual, expected? }]); nextActions are the game's own suggestions.
|
|
72
|
+
* owner (optional, checked by net() for peer requests): args => world record id whose `owner` field must equal the requesting actor.
|
|
73
|
+
* @param {string} name
|
|
74
|
+
* targets (optional): the thing ids, kinds or template names this op is for; engine.thing(id).explain().ops lists it ('*' = any thing).
|
|
75
|
+
* @param {{ run: (e: any, args: any, ctx: OpContext) => any, can?: (e: any, args: any, ctx: OpContext) => true | string | { code: string, facts?: object, nextActions?: { op: string, args?: object }[] }, targets?: string | string[], args?: Record<string, string | { type: string, default?: any, min?: number, max?: number, values?: any[], desc?: string, optional?: boolean }>, offers?: (e: any, ctx: OpContext) => object[], reasons?: Record<string, string>, desc?: string, undo?: (e: any, args: any, value: any) => void, net?: 'peer' | 'local', owner?: (args: any) => string, atomic?: boolean, after?: (e: any, args: any, value: any, ctx: OpContext) => void }} def
|
|
76
|
+
* @returns {{ remove(): void }}
|
|
77
|
+
* @example
|
|
78
|
+
* const PRICE = { bread: 5 };
|
|
79
|
+
* engine.ops.define('shop.buy', {
|
|
80
|
+
* desc: 'Buy from a shop shelf',
|
|
81
|
+
* args: { shop: 'string', item: 'string', n: 'int?' },
|
|
82
|
+
* can(e, { shop, item, n = 1 }, ctx) {
|
|
83
|
+
* if (!e.inventory.container(shop).has(item, n)) return 'soldOut';
|
|
84
|
+
* if (e.inventory.container(ctx.actor).count('gold') < PRICE[item] * n) return 'noMoney';
|
|
85
|
+
* return true;
|
|
86
|
+
* },
|
|
87
|
+
* run(e, { shop, item, n = 1 }, ctx) {
|
|
88
|
+
* const got = e.inventory.transfer(shop, ctx.actor, item, n);
|
|
89
|
+
* e.inventory.container(ctx.actor).remove('gold', PRICE[item] * got);
|
|
90
|
+
* return got;
|
|
91
|
+
* },
|
|
92
|
+
* reasons: { soldOut: 'Shelf is empty', noMoney: 'Not enough gold' },
|
|
93
|
+
* });
|
|
94
|
+
*/
|
|
95
|
+
define(name, def) {
|
|
96
|
+
if (this.defs.has(name)) throw devError(fmt(STRINGS.dup, { name }));
|
|
97
|
+
const shape = checkDef(name, def);
|
|
98
|
+
const d = { name, ...def, shape, defaults: defaultsOf(shape) };
|
|
99
|
+
this.defs.set(name, d);
|
|
100
|
+
return { remove: () => { if (this.defs.get(name) === d) this.defs.delete(name); } };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Run an op now (synchronously): checks args (dev), calls can, then run, and logs it. Returns { ok: true, value, revision } or { ok: false, code, facts, nextActions, revision } (revision = ops.revision, counts committed ops); can may also return { code, facts?, nextActions? }.
|
|
105
|
+
* Pass a fresh args object each call (it is kept in the history; in dev it is frozen). opts.source: 'player' | 'game' | 'bridge' | 'test' | 'replay' | 'net'
|
|
106
|
+
* (default: 'game' inside a fixed step, 'player' between steps); opts.actor: who does it (world record id, default engine.actor, which is 'player' unless the game hands control elsewhere).
|
|
107
|
+
* @param {string} name
|
|
108
|
+
* @param {object} [args]
|
|
109
|
+
* @param {{ source?: string, actor?: string }} [opts]
|
|
110
|
+
* @returns {{ ok: boolean, value?: any, revision: number, code?: string, facts?: object, nextActions?: { op: string, args?: object }[] }}
|
|
111
|
+
* @example
|
|
112
|
+
* const r = engine.ops.run('shop.buy', { shop: 'bakery', item: 'bread' });
|
|
113
|
+
* if (!r.ok) showHint(engine.t('op.shop.buy.' + r.code));
|
|
114
|
+
* // from a fixed step, for an input-driven action: e.ops.run('combat.roll', { dir }, { source: 'player' })
|
|
115
|
+
*/
|
|
116
|
+
run(name, args = {}, opts) {
|
|
117
|
+
return runOp(this, name, args, opts);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Reverse a finished op with the undo(e, args, value) its definition declared: pass the same args and the value run returned.
|
|
122
|
+
* Returns { ok: true }, or { ok: false, code: 'noUndo', facts: { op }, nextActions } when the op did not declare undo. The undo runs as an op write (the dev guard stays quiet).
|
|
123
|
+
* @example const r = engine.ops.run('inventory.trade', { take: 'rusty_key', give: 'gold_key' }); engine.ops.undo('inventory.trade', { take: 'rusty_key', give: 'gold_key' }, r.value);
|
|
124
|
+
* @param {string} name
|
|
125
|
+
* @param {object} args
|
|
126
|
+
* @param {any} value
|
|
127
|
+
* @param {{ actor?: string }} [opts]
|
|
128
|
+
* @returns {{ ok: boolean, code?: string, facts?: object, nextActions?: { op: string, args?: object }[] }}
|
|
129
|
+
*/
|
|
130
|
+
undo(name, args, value, opts) {
|
|
131
|
+
const d = this._def(name);
|
|
132
|
+
if (!d) return this._res(failure({ code: 'unknownOp', facts: { op: name } }));
|
|
133
|
+
if (typeof d.undo !== 'function') return this._res(failure({ code: 'noUndo', facts: { op: name }, nextActions: [] }));
|
|
134
|
+
this._allowDepth++;
|
|
135
|
+
try { d.undo(this.engine, args, value, this._ctx(name, args, opts, null)); } finally { this._allowDepth--; }
|
|
136
|
+
return { ok: true };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Ask without doing: runs only can (no state change, no history). For greying out buttons and input buffers.
|
|
141
|
+
* @param {string} name
|
|
142
|
+
* @param {object} [args]
|
|
143
|
+
* @param {{ actor?: string, source?: string }} [opts]
|
|
144
|
+
* @returns {{ ok: boolean, code?: string, facts?: object, nextActions?: { op: string, args?: object }[] }}
|
|
145
|
+
* @example const { ok, code } = engine.ops.can('shop.buy', { shop: 'bakery', item: 'bread' });
|
|
146
|
+
* button.disabled = !ok;
|
|
147
|
+
*/
|
|
148
|
+
can(name, args = {}, opts) {
|
|
149
|
+
const d = this._def(name);
|
|
150
|
+
if (!d) return this._res(failure('unknownOp'));
|
|
151
|
+
args = withDefaults(d.defaults, args);
|
|
152
|
+
const ctx = this._ctx(name, args, opts, this._stack.length ? this._last : null);
|
|
153
|
+
if (this.engine._freezers.has('error')) return this._res(failure('halted'));
|
|
154
|
+
let res;
|
|
155
|
+
try { res = this._can(d, args, ctx); } catch (err) { if (err?.opsDevError) throw err; res = 'error'; }
|
|
156
|
+
return this._res(res === true ? { ok: true } : failure(res));
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* What exists, or with { available: true } what is possible now: every arg set from each op's offers checked with can
|
|
161
|
+
* (an op with neither offers nor args is checked once with {}; one with args but no offers is skipped, since its args are free-form).
|
|
162
|
+
* @param {{ available?: boolean, actor?: string }} [opts]
|
|
163
|
+
* @returns {{ name: string, desc?: string, args?: any, atomic: boolean, ok?: boolean, code?: string }[]}
|
|
164
|
+
* @example engine.ops.list({ available: true }); // [{ name: 'shop.buy', args: { shop: 'bakery', item: 'bread' }, ok: false, code: 'noMoney' }, ...]
|
|
165
|
+
*/
|
|
166
|
+
list({ available = false, actor } = {}) {
|
|
167
|
+
if (!available) return [...this.defs.values()].map(d => ({ name: d.name, desc: d.desc, args: d.args, atomic: d.atomic === true }));
|
|
168
|
+
const out = [];
|
|
169
|
+
for (const d of this.defs.values()) {
|
|
170
|
+
const ctx = this._ctx(d.name, null, { actor }, null);
|
|
171
|
+
let sets;
|
|
172
|
+
try { sets = d.offers ? d.offers(this.engine, ctx) : d.shape ? [] : [{}]; } catch { sets = []; }
|
|
173
|
+
for (const args of sets || []) { const r = this.can(d.name, args, { actor }); out.push({ name: d.name, args, ...r }); }
|
|
174
|
+
}
|
|
175
|
+
return out;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Recent history (old -> new), optionally of one op: { seq, tick, phase: 'fixed' | 'between', name, args, source, actor, ok, code, depth, count }.
|
|
180
|
+
* Consecutive identical failures (same actor, op and code) merge into one entry with count.
|
|
181
|
+
* @param {string} [name]
|
|
182
|
+
* @returns {{ seq: number, tick: number, phase: string, name: string, args: any, source: string, actor: string, ok: boolean, code: string | null, depth: number, count: number }[]}
|
|
183
|
+
* @example engine.ops.recent('shop.buy').at(-1); // { tick: 812, phase: 'between', ok: false, code: 'noMoney', ... }
|
|
184
|
+
*/
|
|
185
|
+
recent(name) {
|
|
186
|
+
return recentEntries(this, name);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Dev guard for a module that owns saved gameplay state: call it at the top of every method that writes that state. In development it warns once per call site
|
|
191
|
+
* when the write happens outside a fixed step, an op or an allow() window (before ready everything is allowed); in a production build it is a no-op, so just call `engine.ops.guard(...)` (no DEV check needed).
|
|
192
|
+
* @experimental
|
|
193
|
+
* @example set(k, v) { this.engine.ops.guard('myStore.set'); this.data[k] = v; }
|
|
194
|
+
* @param {string} where label shown in the warning, e.g. 'vars.setFlag'
|
|
195
|
+
* @returns {void}
|
|
196
|
+
*/
|
|
197
|
+
guard(where) {
|
|
198
|
+
if (!DEV) return; // release builds do not check; games cannot read DEV, so the no-op lives here
|
|
199
|
+
guardWrite(this, where);
|
|
200
|
+
}
|
|
201
|
+
/** @internal A separator in the history (save load): later entries belong to a different world state */
|
|
202
|
+
_mark(label) { this._log(label, null, { tick: this.engine.tick, source: 'game', actor: '' }, true, null, 0); }
|
|
203
|
+
/**
|
|
204
|
+
* Run fn with guarded writes allowed (loading a save, applying a scenario, net sync); works for an async fn too (allowed until its Promise settles). Returns what fn returns.
|
|
205
|
+
* @experimental
|
|
206
|
+
* @example engine.ops.allow(() => store.load(data));
|
|
207
|
+
* @template T
|
|
208
|
+
* @param {() => T} fn
|
|
209
|
+
* @returns {T}
|
|
210
|
+
*/
|
|
211
|
+
allow(fn) {
|
|
212
|
+
this._allowDepth++;
|
|
213
|
+
let r;
|
|
214
|
+
try { r = fn(); } catch (err) { this._allowDepth--; throw err; }
|
|
215
|
+
if (r && typeof r.then === 'function') return /** @type {any} */ (r.finally(() => { this._allowDepth--; }));
|
|
216
|
+
this._allowDepth--;
|
|
217
|
+
return r;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** @internal */
|
|
221
|
+
_def(name) {
|
|
222
|
+
const d = this.defs.get(name);
|
|
223
|
+
if (d) return d;
|
|
224
|
+
const msg = fmt(STRINGS.unknown, { name: JSON.stringify(name), text: missingText('op', name, [...this.defs.keys()]) });
|
|
225
|
+
if (!DEV) { warnOnce(coded('op-misuse', msg)); return d; } // release: the op is a no-op (reason unknownOp), said once
|
|
226
|
+
throw devError(msg);
|
|
227
|
+
}
|
|
228
|
+
/** @internal */
|
|
229
|
+
_ctx(name, args, opts, parent) {
|
|
230
|
+
const e = this.engine;
|
|
231
|
+
let source = opts?.source ?? parent?.source ?? (e._inFixed ? 'game' : 'player');
|
|
232
|
+
if (DEV) {
|
|
233
|
+
if (!SOURCES.includes(source)) throw devError(fmt(STRINGS.badSource, { name, source }));
|
|
234
|
+
if (args) checkArgs(e, this.defs.get(name), args);
|
|
235
|
+
}
|
|
236
|
+
return { source, actor: opts?.actor ?? parent?.actor ?? e.actor, tick: e.tick, frozen: e.frozen };
|
|
237
|
+
}
|
|
238
|
+
/** @internal returns true or a reason string */
|
|
239
|
+
_can(d, args, ctx) {
|
|
240
|
+
if (!d.can) return true;
|
|
241
|
+
const prev = this._inCan; this._inCan = d.name;
|
|
242
|
+
let r;
|
|
243
|
+
try { r = d.can(this.engine, args, ctx); } finally { this._inCan = prev; }
|
|
244
|
+
if (r === true || (typeof r === 'string' && r) || isStructured(r)) return r;
|
|
245
|
+
const msg = fmt(STRINGS.canResult, { name: d.name, got: JSON.stringify(r) ?? 'undefined' });
|
|
246
|
+
if (DEV) throw devError(msg);
|
|
247
|
+
warnOnce(coded('op-misuse', msg)); // release: denied, said once
|
|
248
|
+
return 'denied';
|
|
249
|
+
}
|
|
250
|
+
/** @internal write a history entry in place (no allocation); consecutive identical failures merge */
|
|
251
|
+
_log(name, args, ctx, ok, reason, depth) {
|
|
252
|
+
return logEntry(this, name, args, ctx, ok, reason, depth);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** @typedef {{ source: string, actor: string, tick: number, frozen: boolean }} OpContext */
|
package/core/Random.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Seeded random numbers, engine.random: gameplay randomness (auto weather, lightning intervals, drops, spawning) all uses it, so step / test results are reproducible and the state is saved with the save.
|
|
2
|
+
// engine.random.next() // 0-1
|
|
3
|
+
// engine.random.range(2, 5) // a decimal in 2-5
|
|
4
|
+
// engine.random.int(1, 6) // an integer in 1-6 (inclusive)
|
|
5
|
+
// engine.random.pick(['a', 'b']) // pick one at random
|
|
6
|
+
// engine.random.chance(0.3) // true with 30% probability
|
|
7
|
+
// engine.random.setSeed(42) // reseed (the sequence after is fixed)
|
|
8
|
+
// Seed: createEngine({ seed }); if omitted, headless mode uses 1 (reproducible) and real-time runs use the current time (different each run).
|
|
9
|
+
// Purely presentational randomness (particle jitter, bird-call pitch) does not use it: call Math.random() and tag the line // presentation (see packages/tools/rules/R04).
|
|
10
|
+
|
|
11
|
+
import { mulberry32 } from './mulberry32.js'; // 32-bit state, plenty for gameplay
|
|
12
|
+
|
|
13
|
+
/** engine.random is the seeded random generator. Gameplay randomness (auto weather, lightning, drops, spawning) uses it so step / tests are reproducible and the state is saved with the save. */
|
|
14
|
+
export class Random {
|
|
15
|
+
/** @param {number} [seed] Seed, default 1 */
|
|
16
|
+
constructor(seed = 1) { this.setSeed(seed); }
|
|
17
|
+
/**
|
|
18
|
+
* Reseed: the sequence afterwards is determined by seed.
|
|
19
|
+
* @param {number} seed
|
|
20
|
+
* @returns {this}
|
|
21
|
+
* @example engine.random.setSeed(42);
|
|
22
|
+
*/
|
|
23
|
+
setSeed(seed) { this.seed = seed >>> 0; this.state = this.seed; return this; }
|
|
24
|
+
/** A number from 0 (inclusive) to 1 (exclusive) @returns {number} */
|
|
25
|
+
next() { const v = mulberry32(this); this.state >>>= 0; return v; } // state kept unsigned (as saved)
|
|
26
|
+
/** A decimal between a and b @param {number} a @param {number} b @returns {number} */
|
|
27
|
+
range(a, b) { return a + this.next() * (b - a); }
|
|
28
|
+
/** An integer between a and b (inclusive) @param {number} a @param {number} b @returns {number} @example const dice = engine.random.int(1, 6); */
|
|
29
|
+
int(a, b) { return a + Math.floor(this.next() * (b - a + 1)); }
|
|
30
|
+
/**
|
|
31
|
+
* Pick one element of the array at random (undefined for an empty array).
|
|
32
|
+
* @template T
|
|
33
|
+
* @param {readonly T[]} list
|
|
34
|
+
* @returns {T | undefined}
|
|
35
|
+
*/
|
|
36
|
+
pick(list) { return list.length ? list[Math.floor(this.next() * list.length)] : undefined; }
|
|
37
|
+
/** True with probability p (0-1) @param {number} p @returns {boolean} */
|
|
38
|
+
chance(p) { return this.next() < p; }
|
|
39
|
+
/**
|
|
40
|
+
* Create an independent deterministic generator: the same seed always gives the same sequence, without touching engine.random's state or the save.
|
|
41
|
+
* For placing world initial data (the same things must be laid out on every start, and loading a save must not overwrite them with the saved engine.random).
|
|
42
|
+
* Gameplay randomness (drops, lightning) still uses engine.random (saved with the save).
|
|
43
|
+
* @param {number} seed
|
|
44
|
+
* @returns {Random}
|
|
45
|
+
* @example const rnd = engine.random.seeded(7); const x = rnd.range(-20, 20);
|
|
46
|
+
*/
|
|
47
|
+
seeded(seed) { return new Random(seed); }
|
|
48
|
+
/** For saving: { seed, state } @returns {{ seed: number, state: number }} */
|
|
49
|
+
toJSON() { return { seed: this.seed, state: this.state }; }
|
|
50
|
+
/** For loading @param {{ seed: number, state: number } | null | undefined} d */
|
|
51
|
+
fromJSON(d) { if (d) { this.seed = d.seed >>> 0; this.state = d.state >>> 0; } }
|
|
52
|
+
}
|