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/Describe.js
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// Game state description: engine.describe() returns a plain object (JSON.stringify-able); engine.describeText() returns multi-line text.
|
|
2
|
+
// For AI and test scripts: learn "what time it is, what the weather is, where the player is, what is nearby, which windows are open" without a screenshot.
|
|
3
|
+
//
|
|
4
|
+
// The core fills in only what it knows (time in seconds, player position, camera, windows, performance); the rest comes from modules' optional hooks:
|
|
5
|
+
// describe(e, ctx) {
|
|
6
|
+
// ctx.out.time.clock = '18:30'; // you may add info to the standard fields
|
|
7
|
+
// ctx.near(obj3D or {x,z}, { name, kind: 'npc' }); // report a "nearby thing"; the core computes distance, bearing and ordering
|
|
8
|
+
// return { ... }; // the return value goes into the result under the module name as key (omitted if nothing is returned)
|
|
9
|
+
// }
|
|
10
|
+
//
|
|
11
|
+
// A small game that does not want a full module: engine.describe.add(name, fn) registers the game's own state in one line; the return value goes into describe().<name> (fn gets the same arguments as a module hook).
|
|
12
|
+
// const h = engine.describe.add('range', () => ({ score, targets: targets.length })); h.remove() to cancel
|
|
13
|
+
// A big game writes its systems as modules and uses the module's describe hook.
|
|
14
|
+
// ctx.near(at, info, weak): reports for the same `at` (same object) are merged; with weak = true only missing fields are filled (used by the interaction module).
|
|
15
|
+
// Display names (ground type, weather name) are not hard-coded here: they come from the string table, ground.<type> and weather.<name> (registered by the terrain and weather modules), and go into groundName / label.
|
|
16
|
+
// describeText, which turns this into text, lives in describeText.js.
|
|
17
|
+
import { describeText } from './describeText.js';
|
|
18
|
+
import { inspect, explain } from './Inspect.js';
|
|
19
|
+
import { inspectScene } from './InspectScene.js';
|
|
20
|
+
import { codedError } from './errorHints.js';
|
|
21
|
+
import { r1 } from './math.js';
|
|
22
|
+
import { describeRender } from './describeRender.js';
|
|
23
|
+
import { describeLook } from './look/report.js';
|
|
24
|
+
import { describeScene } from './thingOps.js';
|
|
25
|
+
|
|
26
|
+
const NEAR_RADIUS = 30, NEAR_MAX = 15;
|
|
27
|
+
const COMPASS = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']; // north = -Z, east = +X
|
|
28
|
+
const RELATIVE = ['front', 'front-right', 'right', 'back-right', 'back', 'back-left', 'left', 'front-left']; // relative to the camera heading
|
|
29
|
+
const STANDARD = new Set(['ready', 'error', 'disabledModules', 'moduleStates', 'loading', 'time', 'player', 'camera', 'nearbyRadius', 'nearby', 'actions', 'ui', 'cutscene', 'modules', 'perf', 'scene', 'render', 'look']);
|
|
30
|
+
const ACTIONS_MAX = 8; // what the player can do now, with why not: saves the AI a guess for a few dozen characters // the core's own fields
|
|
31
|
+
const sector = a => Math.round(((a % (Math.PI * 2)) + Math.PI * 2) / (Math.PI / 4)) % 8;
|
|
32
|
+
|
|
33
|
+
/** Display name from the string table (prefix + key); null if missing (the text then uses the raw name) */
|
|
34
|
+
const nameOf = (e, prefix, key) => (key != null && e.i18n.has(prefix + key) ? e.t(prefix + key) : null);
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The engine's state questions, assigned onto the engine: describe (call it for the state object; .add registers the game's own state),
|
|
38
|
+
* describeText, inspect and explain (Inspect.js)
|
|
39
|
+
* @param {any} e
|
|
40
|
+
*/
|
|
41
|
+
export function describeApi(e) {
|
|
42
|
+
const extras = new Map();
|
|
43
|
+
/**
|
|
44
|
+
* Current game state (plain object, JSON.stringify-able). radius: how far counts as "nearby" (meters), default 30
|
|
45
|
+
* @param {{ radius?: number, center?: { x: number, z: number } }} [opts] center: measure "nearby" from here instead of the player (inspect uses it)
|
|
46
|
+
*/
|
|
47
|
+
const api = opts => describe(e, opts, extras);
|
|
48
|
+
/** @internal engine.catalog() reads which names were added (and by which module) */ api._extras = extras;
|
|
49
|
+
/**
|
|
50
|
+
* Register the game's own state: the return value of fn(engine, ctx) (must be JSON-able) goes into describe().<name>; undefined is omitted
|
|
51
|
+
* @param {string} name key in the result; must not match an existing field or module name
|
|
52
|
+
* @param {(e: any, ctx: any) => any} fn
|
|
53
|
+
* @returns {{ remove(): void }}
|
|
54
|
+
* @example engine.describe.add('range', () => ({ score: vars.get('score'), targets: targets.length }));
|
|
55
|
+
*/
|
|
56
|
+
api.add = (name, fn) => {
|
|
57
|
+
if (extras.has(name) || STANDARD.has(name) || e.modules.has(name)) throw codedError('describe-name', `describe.add('${name}'): this name is already taken; pick another (existing fields, module names and previously registered names cannot be reused)`);
|
|
58
|
+
extras.set(name, fn);
|
|
59
|
+
return { remove: () => { extras.delete(name); } };
|
|
60
|
+
};
|
|
61
|
+
/** Text of describe(): a summary by default; { path: 'world' } one part as JSON; { full: true } everything (see describeText.js) */
|
|
62
|
+
const text = ({ full, path, ...opts } = {}) => describeText(api(opts), { full, path });
|
|
63
|
+
const inspectApi = Object.assign((at, opts) => inspect(e, at, opts), { scene: opts => inspectScene(e, opts) });
|
|
64
|
+
return { describe: api, describeText: text, inspect: inspectApi, explain: q => explain(e, q) };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Only the modules that are not running normally (initializing / failed) appear in describe, so the common case adds nothing; engine.moduleStates has all of them */
|
|
68
|
+
function pendingModules(e) {
|
|
69
|
+
const out = {};
|
|
70
|
+
for (const [name, st] of e._modState) if (st === 'initializing' || st === 'failed') out[name] = st;
|
|
71
|
+
return Object.keys(out).length ? { moduleStates: out } : {};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Everyone who holds the engine still or takes something over, in one shape: { pause|freeze|camera|debugView: [{ owner, at }] } (empty kinds left out) */
|
|
75
|
+
function heldBy(e) {
|
|
76
|
+
const all = { pause: e._pausers, freeze: e._freezers, camera: e._cameraClaims, debugView: e.debug?._view };
|
|
77
|
+
return Object.fromEntries(Object.entries(all).map(([k, c]) => [k, c?.owners() ?? []]).filter(([, o]) => o.length));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Build the state object. radius: how far counts as "nearby"; extras: those registered by describe.add */
|
|
81
|
+
function describe(e, { radius = NEAR_RADIUS, center: at } = {}, extras) {
|
|
82
|
+
const p = e.player?.position, center = at || p || e.focus, cam = e.camera;
|
|
83
|
+
const dir = cam.getWorldDirection(new e.THREE.Vector3()), camYaw = Math.atan2(dir.x, -dir.z);
|
|
84
|
+
const out = {
|
|
85
|
+
ready: e.ready,
|
|
86
|
+
error: e.error, // gameplay error in dev / tests (gameplay is frozen)
|
|
87
|
+
disabledModules: [...e.disabledModules], // presentation modules disabled after an error
|
|
88
|
+
...pendingModules(e), // { moduleStates } while a module is initializing or failed
|
|
89
|
+
loading: e.loading.view(), // what is pending / failed and whether it blocks the start (Loading.js)
|
|
90
|
+
time: { elapsed: r1(e.elapsed), paused: e.paused, frozen: e.frozen, headless: e.headless, run: e.runState, heldBy: heldBy(e) },
|
|
91
|
+
player: p ? {
|
|
92
|
+
x: r1(p.x), y: r1(p.y), z: r1(p.z),
|
|
93
|
+
ground: e.groundType(p.x, p.z),
|
|
94
|
+
groundName: nameOf(e, 'ground.', e.groundType(p.x, p.z)),
|
|
95
|
+
inWater: e.waterAt(p.x, p.z) > p.y,
|
|
96
|
+
state: e.player.state ?? null,
|
|
97
|
+
running: e.player.state === 'run',
|
|
98
|
+
jumping: e.player.state === 'jump' || e.player.state === 'fall',
|
|
99
|
+
} : null,
|
|
100
|
+
camera: { type: null, x: r1(cam.position.x), y: r1(cam.position.y), z: r1(cam.position.z),
|
|
101
|
+
focus: { x: r1(e.focus.x), z: r1(e.focus.z) }, override: e.cameraOverride?.owner ?? null },
|
|
102
|
+
nearbyRadius: radius,
|
|
103
|
+
nearby: [],
|
|
104
|
+
ui: { windows: [...e.openWindows], inputLocked: !e.input.enabled, inputContexts: e.input.contexts, dialogue: null, parts: e.ui.describe() }, // windows include full-screen UI parts (title); parts: default / custom / off
|
|
105
|
+
cutscene: null,
|
|
106
|
+
modules: [...e.modules.keys()],
|
|
107
|
+
scene: describeScene(e), // engine.add / world things: counts by save tier and what will not survive a load (thingOps.js)
|
|
108
|
+
look: describeLook(e), // every look part key, its value and who set it (look/report.js)
|
|
109
|
+
render: describeRender(e), // renderer / post / lights and who set each (describeRender.js)
|
|
110
|
+
perf: {
|
|
111
|
+
fps: e.paused ? null : Math.round(e.fps), cpuMs: e.paused ? null : r1(e.cpuMs),
|
|
112
|
+
cpu: e.paused ? null : Object.fromEntries(Object.entries(e.cpuPhases).map(([k, v]) => [k, r1(v)])),
|
|
113
|
+
apply: e.budget.cost.report(),
|
|
114
|
+
drawCalls: e.renderer.info.render.calls, triangles: e.renderer.info.render.triangles, pixelRatio: e.renderer.getPixelRatio(),
|
|
115
|
+
budget: e.budget.report(), startup: e.startup, stream: e.stream.stats, batching: e.batching.stats, jobs: e.jobs.pending, commits: { pending: e.commits.pending, ...e.commits.stats },
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
// Nearby things: collect first, then sort and truncate once at the end
|
|
119
|
+
const found = new Map(), v = new e.THREE.Vector3();
|
|
120
|
+
const ctx = {
|
|
121
|
+
out, radius, center,
|
|
122
|
+
near(at, info, weak = false) {
|
|
123
|
+
const pos = at.isObject3D ? at.getWorldPosition(v) : at;
|
|
124
|
+
const dx = pos.x - center.x, dz = pos.z - center.z, dist = Math.hypot(dx, dz);
|
|
125
|
+
if (dist > radius) return;
|
|
126
|
+
const old = found.get(at);
|
|
127
|
+
if (old) { for (const k in info) if (!weak || old[k] == null) old[k] = info[k]; return; }
|
|
128
|
+
const bearing = Math.atan2(dx, -dz);
|
|
129
|
+
found.set(at, { ...info, dist: r1(dist), dir: COMPASS[sector(bearing)], rel: RELATIVE[sector(bearing - camYaw)], x: r1(pos.x), z: r1(pos.z) });
|
|
130
|
+
},
|
|
131
|
+
};
|
|
132
|
+
for (const m of e.modules.values()) {
|
|
133
|
+
if (!m.describe) continue;
|
|
134
|
+
const part = m.describe(e, ctx);
|
|
135
|
+
if (part !== undefined) out[m.name] = part;
|
|
136
|
+
}
|
|
137
|
+
for (const [name, fn] of extras) {
|
|
138
|
+
try { const part = fn(e, ctx); if (part !== undefined) out[name] = part; } catch (err) { out[name] = { error: String(err.message || err) }; } // an error in the game's own description must not take down the whole describe
|
|
139
|
+
}
|
|
140
|
+
out.nearby = [...found.values()].sort((a, b) => a.dist - b.dist).slice(0, NEAR_MAX);
|
|
141
|
+
// ops on offer for the player (engine.ops.list({ available: true })): possible ones first; omitted when the game has none
|
|
142
|
+
const acts = e.ops.list({ available: true }).sort((a, b) => b.ok - a.ok).slice(0, ACTIONS_MAX);
|
|
143
|
+
if (acts.length) out.actions = acts.map(a => ({ op: a.name, args: a.args, ok: a.ok, ...(a.ok ? {} : { code: a.code, facts: a.facts, nextActions: a.nextActions }) }));
|
|
144
|
+
return out;
|
|
145
|
+
}
|
package/core/Engine.js
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
// Engine core: what every 3D web game needs (rendering and post, main loop, events, input, assets, audio, saves, UI basics, loading screen, ground API).
|
|
2
|
+
// No terrain, sky or characters, and no art; everything else is a module installed with engine.use(...) (see recipes/14-custom-module.md).
|
|
3
|
+
// Split: main loop and step in loop.js, start() in startup.js, ground API in ground.js, module install in modules.js, dispose and counts in lifecycle.js (all
|
|
4
|
+
// mixed into Engine.prototype).
|
|
5
|
+
import * as THREE from 'three';
|
|
6
|
+
import { Page } from './page.js';
|
|
7
|
+
import { createServices } from './services.js';
|
|
8
|
+
import { PostFX } from '../render/PostFX.js';
|
|
9
|
+
import { createDefaultLights } from '../render/lights.js';
|
|
10
|
+
import { registerEngine, makeMaterial, MATERIAL_PURPOSES } from '../render/materials.js';
|
|
11
|
+
import { defineMaterialsLook, defineSurfaceLook } from '../render/lookSurface.js';
|
|
12
|
+
import { createUniforms } from '../render/effects.js';
|
|
13
|
+
import { bindUniforms } from '../render/engineUniforms.js';
|
|
14
|
+
import { UIParts } from '../ui/Parts.js';
|
|
15
|
+
import { defineCoreParts } from '../ui/defaults.js';
|
|
16
|
+
import { applyUIStyle } from '../ui/theme.js';
|
|
17
|
+
import { setValidate, checkOptions, warnOnce, DEV } from './validate.js';
|
|
18
|
+
import { loopMethods } from './loop.js';
|
|
19
|
+
import { holdMethods } from './holds.js';
|
|
20
|
+
import { startupMethods } from './startup.js';
|
|
21
|
+
import { groundMethods, flatGround } from './ground.js';
|
|
22
|
+
import { actorMethods } from './actor.js';
|
|
23
|
+
import { detectTier } from './tier.js';
|
|
24
|
+
import { lifecycleMethods } from './lifecycle.js';
|
|
25
|
+
import { createMovement } from './movement.js';
|
|
26
|
+
import { moduleMethods } from './modules.js';
|
|
27
|
+
import { skipMethods } from './skip.js';
|
|
28
|
+
import { checkMethods } from './checks.js';
|
|
29
|
+
import { styleFrom, NO_STYLE } from './styleParts.js';
|
|
30
|
+
import { canvasBox, placeUI, resizeMethods } from './canvasBox.js';
|
|
31
|
+
import { sceneMethods } from './sceneMethods.js';
|
|
32
|
+
import { recordRender } from './describeRender.js';
|
|
33
|
+
import { defineCoreLook, defineCloudShadowLook } from './look/coreParts.js';
|
|
34
|
+
import { shadowTypeOf } from './shadowTypes.js';
|
|
35
|
+
// Options createEngine accepts (must match the constructor destructuring)
|
|
36
|
+
const ENGINE_OPTIONS = ['canvas', 'style', 'shadows', 'shadowType', 'antialias', 'post', 'pixelRatio', 'adaptiveResolution', 'targetFps', 'ui', 'audio',
|
|
37
|
+
'fov', 'near', 'fogFar',
|
|
38
|
+
'locale', 'strings', 'bindings', 'saveKey', 'joystick', 'padBindings', 'headless', 'validate', 'decoders', 'budget', 'urlState', 'seed', 'movement', 'threads', 'pauseOnBlur', 'batching', 'lights', 'renderer'];
|
|
39
|
+
|
|
40
|
+
export class Engine {
|
|
41
|
+
/**
|
|
42
|
+
* @param o createEngine options: each option, its default and meaning is documented once on EngineOptions (types/core.d.ts).
|
|
43
|
+
* style can also be a list of parts deep-merged left to right (rules in core/styleParts.js). ENGINE_OPTIONS and the destructuring below must match it.
|
|
44
|
+
*/
|
|
45
|
+
constructor(opts = {}) {
|
|
46
|
+
setValidate(opts.validate);
|
|
47
|
+
checkOptions('createEngine()', opts, ENGINE_OPTIONS);
|
|
48
|
+
const { canvas: canvasIn, renderer: rendererIn, style: styleIn, shadows = true, shadowType = 'pcf', antialias, post, pixelRatio, adaptiveResolution = true, targetFps = 55, ui = {}, audio = {},
|
|
49
|
+
fov = 55, near = 0.3, fogFar = 600, locale = 'auto', strings = {}, bindings = {}, saveKey = 'game', joystick = 'auto', padBindings = {},
|
|
50
|
+
headless = new URLSearchParams(location.search).has('threedog-headless'), validate = true,
|
|
51
|
+
decoders = null, budget = null, urlState = DEV, seed, movement, threads = 'auto', pauseOnBlur = true, batching = {}, lights = true } = opts;
|
|
52
|
+
this.THREE = THREE;
|
|
53
|
+
const canvas = canvasIn ?? rendererIn?.domElement;
|
|
54
|
+
this.movement = createMovement(movement); // character radius / height / slope / step height: the single copy shared by collision, physics and nav
|
|
55
|
+
const style = this.style = styleFrom(styleIn); // a list of parts is deep-merged (styleParts.js); one object is used as is
|
|
56
|
+
if (!opts.style) warnOnce(NO_STYLE);
|
|
57
|
+
// a game-supplied renderer is used as is: the engine configures (pixel ratio, size, tone mapping, shadows) only a renderer it created itself
|
|
58
|
+
const owned = !rendererIn;
|
|
59
|
+
const r = this.renderer = rendererIn ?? new THREE.WebGLRenderer({ canvas, antialias: false, powerPreference: 'high-performance' });
|
|
60
|
+
this.tier = detectTier(r); // 'low' | 'high': device tier, decides default quality
|
|
61
|
+
if (owned || pixelRatio != null) r.setPixelRatio(pixelRatio ?? Math.min(devicePixelRatio || 1, this.tier === 'low' ? 1 : 1.5));
|
|
62
|
+
this._autoSize = undefined; // decided once the canvas is in the page (sizeMode): true = no CSS size, the engine sizes it to the window
|
|
63
|
+
const box = canvasBox(this);
|
|
64
|
+
if (owned) r.setSize(box.w, box.h, !!this._autoSize);
|
|
65
|
+
if (owned) {
|
|
66
|
+
r.shadowMap.enabled = shadows;
|
|
67
|
+
r.shadowMap.type = shadowTypeOf(shadowType, 'createEngine({ shadowType })');
|
|
68
|
+
}
|
|
69
|
+
r.info.autoReset = false;
|
|
70
|
+
|
|
71
|
+
this.scene = new THREE.Scene();
|
|
72
|
+
this.scene.background = new THREE.Color(style.background ?? 0x8c8c8c);
|
|
73
|
+
/** Default lights { sun: DirectionalLight, hemi: HemisphereLight }: neutral without sky, driven by sky when installed @type {{ sun: any, hemi: any }} */
|
|
74
|
+
/** Look parts by name, each with set / patch / replace (recipes/52-look.md): tone, lights, cloudShadow from core, the rest from the modules that provide them @type {Record<string, import('../index').LookPart>} */
|
|
75
|
+
this.look = {};
|
|
76
|
+
this.lights = createDefaultLights(this, { add: lights !== false });
|
|
77
|
+
defineCoreLook(this, { owned }); // look.tone (style.toneMapping / exposure; none and 1 without a style pack) and look.lights (coreParts.js)
|
|
78
|
+
recordRender(this, { owned }); // baseline for describe().render: which values the engine / style set
|
|
79
|
+
this.camera = new THREE.PerspectiveCamera(fov, box.w / box.h, near, 1500);
|
|
80
|
+
this.camera.position.set(0, 10, 20);
|
|
81
|
+
this.focus = new THREE.Vector3(); // camera focus (updated by the camera module): the view loads around it; simulation follows world.anchor
|
|
82
|
+
this.shadows = shadows;
|
|
83
|
+
/** Shadow filter in use ('basic' | 'pcf' | 'vsm'); change it with look.shadow.set({ type }) @type {string} */
|
|
84
|
+
this.shadowType = shadowType;
|
|
85
|
+
this.ground = flatGround;
|
|
86
|
+
this.player = null;
|
|
87
|
+
/**
|
|
88
|
+
* World record id of the one the local user controls (default 'player'): interactions, trigger zones, markers and ops (ctx.actor) use it. Set it to hand
|
|
89
|
+
* control to a vehicle or squad member @type {string}
|
|
90
|
+
*/
|
|
91
|
+
this.actor = 'player';
|
|
92
|
+
this.ready = false;
|
|
93
|
+
this.disposed = false; // true after dispose()
|
|
94
|
+
this._abort = new AbortController();
|
|
95
|
+
// attach DOM listeners to it: addEventListener(type, fn, { signal: engine.signal }); dispose cancels them together
|
|
96
|
+
this.signal = this._abort.signal;
|
|
97
|
+
this.uiRoot = document.createElement('div'); // engine and module UI elements live here (not on body); dispose removes the whole root
|
|
98
|
+
// the UI root sits right after the canvas and covers exactly its box (placeUI): HUD, windows and prompts line up with the canvas
|
|
99
|
+
// whether it fills the window, sits in a page section, a split layout or an editor panel
|
|
100
|
+
this.uiRoot.className = 'threedog-root';
|
|
101
|
+
if (r.domElement.parentElement) r.domElement.after(this.uiRoot); else document.body.appendChild(this.uiRoot);
|
|
102
|
+
this.headless = headless;
|
|
103
|
+
this.paused = headless; // while paused the real-time loop does not advance; only step() does
|
|
104
|
+
this.fps = 0;
|
|
105
|
+
this.cpuMs = 0; // main-thread ms of the last real-time frame; cpuPhases splits it (loop.js)
|
|
106
|
+
this.cpuPhases = { fixed: 0, frame: 0, render: 0, afterRender: 0 };
|
|
107
|
+
this.openWindows = new Set(); // ids of open windows (for describe)
|
|
108
|
+
this.fogFar = fogFar; // base fog distance; terrain view range changes it, weather scales it
|
|
109
|
+
this.modules = new Map();
|
|
110
|
+
this._modState = new Map(); // module name -> registered | initializing | running | failed | disposed (modules.js)
|
|
111
|
+
this.waterBodies = [];
|
|
112
|
+
this._fixed = []; this._frame = []; this._hooks = { fixed: [], frame: [], afterRender: [], skip: [] };
|
|
113
|
+
this._hookErrors = new Set(); // places that already reported an error (once per place, see errors.js)
|
|
114
|
+
this.error = null; // gameplay error in dev/test: { where, message, cause?, docs? }; gameplay is frozen (see errors.js)
|
|
115
|
+
this.disabledModules = new Set(); // presentation modules disabled after they threw
|
|
116
|
+
this._elapsed = 0; // engine.elapsed: fixed seconds, advanced per fixed step and copied into uniforms.uTime
|
|
117
|
+
/**
|
|
118
|
+
* This engine's shader uniforms (uTime, uWind, uCloud, season tints...); share these objects in your own ShaderMaterial or patch @type
|
|
119
|
+
* {import('../types/core').EngineUniforms}
|
|
120
|
+
*/
|
|
121
|
+
this.uniforms = createUniforms(style);
|
|
122
|
+
bindUniforms(r, this.uniforms); // built-in shader effects read this engine's uniforms when compiled by this renderer
|
|
123
|
+
defineCloudShadowLook(this); // look.cloudShadow: the cloud-shadow patch every engine material carries, declared (coreParts.js)
|
|
124
|
+
defineMaterialsLook(this, MATERIAL_PURPOSES); defineSurfaceLook(this); // look.materials / look.surface: what makeMaterial reads (render/lookSurface.js)
|
|
125
|
+
this._materials = registerEngine(this); // makeMaterial without an engine argument uses the first live engine's style pack
|
|
126
|
+
|
|
127
|
+
createServices(this, { canvas, validate, locale, strings, saveKey, joystick, bindings, padBindings, audio, decoders, budget, seed, headless, urlState, threads, batching });
|
|
128
|
+
this.startup = null; // startup timing report (set once start() finishes)
|
|
129
|
+
this._prof = null; // module hook timing (profile(true) turns it on)
|
|
130
|
+
this._afterTick = null; // at startup, checked once at the end of each frame for readiness
|
|
131
|
+
// effects come from the style pack; costly ones start off on low-tier devices unless the post option names them
|
|
132
|
+
this.post = new PostFX(this, { antialias: antialias ?? style.antialias ?? this.tier !== 'low', effects: style.post, enabled: post });
|
|
133
|
+
this._uiStyle = applyUIStyle(this, style.ui); // theme variables, pack CSS and fonts; removed on dispose
|
|
134
|
+
this.ui = new UIParts(this, ui); // UI parts: every piece of screen UI is replaceable or off (ui/Parts.js)
|
|
135
|
+
defineCoreParts(this);
|
|
136
|
+
this.ui.get('loading')?.show({});
|
|
137
|
+
this.adaptive = { paused: false, on: adaptiveResolution && !headless, target: targetFps, min: 0.6, max: r.getPixelRatio(),
|
|
138
|
+
t: 0, n: 0, good: 0, cooldown: 0 };
|
|
139
|
+
// follow the canvas's own CSS box, not the window: a canvas in a page section or editor panel renders at its own size.
|
|
140
|
+
// The window event stays for a canvas outside the page (no box, falls back to the window) and for moves that do not resize the canvas
|
|
141
|
+
addEventListener('resize', () => this._resize(), { signal: this.signal });
|
|
142
|
+
if (typeof ResizeObserver === 'function') {
|
|
143
|
+
const ro = new ResizeObserver(() => this._resize());
|
|
144
|
+
ro.observe(r.domElement);
|
|
145
|
+
this.signal.addEventListener('abort', () => ro.disconnect());
|
|
146
|
+
}
|
|
147
|
+
placeUI(this);
|
|
148
|
+
this.page = new Page(this, { pauseOnBlur }); // window focus, tab visibility, mouse lock, WebGL context: handled only there
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
get waterLevel() { return this.ground.waterLevel; }
|
|
152
|
+
|
|
153
|
+
// ---------- common ----------
|
|
154
|
+
/** Get a UI string (i18n) */
|
|
155
|
+
t(key, params) { return this.i18n.t(key, params); }
|
|
156
|
+
/**
|
|
157
|
+
* Elapsed fixed-step seconds (ignores clock.timeScale; stops while frozen or paused), for presentation animation (sway, bobbing). Game seconds are clock.now
|
|
158
|
+
* (= fixed-step seconds × timeScale); sky time of day is sky.timeOfDay
|
|
159
|
+
*/
|
|
160
|
+
get elapsed() { return this._elapsed; }
|
|
161
|
+
/** Material by role from this engine's style pack: engine.makeMaterial('prop', { color: 0x8a5a36 }) */
|
|
162
|
+
makeMaterial(purpose, params) { return makeMaterial(purpose, params, this); }
|
|
163
|
+
/** Ray cast: the nearest hit or null, see Rays.js */
|
|
164
|
+
raycast(origin, dir, opts) { return this.rays.cast(origin, dir, opts); }
|
|
165
|
+
/** Cast a ray from screen coordinates (-1..1) */
|
|
166
|
+
pick(ndcX, ndcY, opts) { return this.rays.pick(ndcX, ndcY, opts); }
|
|
167
|
+
/** Set up a scenario: { time, weather, pos, save, wait, cutscene, state }, see UrlState.js */
|
|
168
|
+
applyState(params) { return this._urlState.apply(params); }
|
|
169
|
+
/** Scenario ready: start() has finished and the URL parameters / latest applyState are applied (tests and screenshots wait for it) */
|
|
170
|
+
get stateApplied() { return this.ready && this._urlState.applied; }
|
|
171
|
+
/** Name a set of scenario parameters, then use applyState({ state: name }) or the URL ?state=name */
|
|
172
|
+
defineState(name, params) { this._urlState.define(name, params); return this; }
|
|
173
|
+
/** Fixed-step logic (60 per second): movement, timers, gameplay keys. Returns a handle { remove() } */
|
|
174
|
+
onFixed(fn) { this._fixed.push(fn); return { remove: () => { this._fixed = this._fixed.filter(f => f !== fn); } }; }
|
|
175
|
+
/** Once per frame: animation, camera, UI. Returns a handle { remove() } */
|
|
176
|
+
onFrame(fn) { this._frame.push(fn); return { remove: () => { this._frame = this._frame.filter(f => f !== fn); } }; }
|
|
177
|
+
|
|
178
|
+
/** @internal Display name of a module (loading screen): module.<name> from the string table, else the module's own label */
|
|
179
|
+
moduleName(m) { return this.i18n.has('module.' + m.name) ? this.t('module.' + m.name) : (m.label || m.name); }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Mix in by property descriptor (Object.assign would evaluate getters on the spot and lose them)
|
|
183
|
+
for (const part of [loopMethods, holdMethods, startupMethods, groundMethods, actorMethods, moduleMethods, lifecycleMethods, skipMethods, checkMethods, resizeMethods, sceneMethods])
|
|
184
|
+
Object.defineProperties(Engine.prototype, Object.getOwnPropertyDescriptors(part));
|
package/core/Events.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// Event bus: modules do not call each other directly; they "shout" and whoever cares listens.
|
|
2
|
+
// const h = engine.events.on('item:add', ({ id, count }) => ...); // returns a handle; h.remove() cancels (like every add/on in the engine)
|
|
3
|
+
// engine.events.emit('item:add', { id: 'fish', count: 1 });
|
|
4
|
+
// Event name format: 'noun:action' -- the noun is the singular of the emitter (item, quest, entity... camelCase), the action is a lowercase verb or state (add, done, change...).
|
|
5
|
+
//
|
|
6
|
+
// Event history: the last historySize entries (default 200) record { tick, name, data }; data keeps only simple values (numbers, strings, booleans; objects become '...') and never holds scene objects.
|
|
7
|
+
// engine.events.recent('item:add') reads recent events of one kind -- for "why did it not fire", first check whether it happened at all.
|
|
8
|
+
//
|
|
9
|
+
// All events, who emits and who listens: see packages/engine/docs/CODEMAP.md (generated by npm run map)
|
|
10
|
+
// In dev (npm run dev) event names are checked: a name never seen before that is one or two letters off a known event warns "did you mean xxx".
|
|
11
|
+
/** @import { Handle } from '../types/common' */
|
|
12
|
+
/** @import { EventName, EventArgs } from '../types/core' */
|
|
13
|
+
import { checkEventName } from './validate.js';
|
|
14
|
+
|
|
15
|
+
// Event names the engine and modules emit (for spelling checks): generated from EventMap in packages/engine/types/core.d.ts, never a hand-written second copy
|
|
16
|
+
import { ENGINE_EVENTS } from './events.generated.js';
|
|
17
|
+
|
|
18
|
+
/** engine.events: the event bus; modules "shout" and whoever cares listens */
|
|
19
|
+
export class Events {
|
|
20
|
+
/** @internal */
|
|
21
|
+
constructor({ check = false, onError = null, now = () => 0 } = {}) {
|
|
22
|
+
/** @internal */ this.map = new Map();
|
|
23
|
+
/** @internal */ this.seen = check ? new Set(ENGINE_EVENTS) : null;
|
|
24
|
+
/** @internal */ this.onError = onError;
|
|
25
|
+
/** @internal */ this.now = now;
|
|
26
|
+
/** @internal history ring: entries in arrival order until full, then _head marks the oldest */ this.history = [];
|
|
27
|
+
/** @internal */ this._head = 0;
|
|
28
|
+
/** How many history entries to keep, default 200; 0 records nothing */
|
|
29
|
+
this.historySize = 200;
|
|
30
|
+
/** @internal >0 while an atomic rollback reloads state: emit does nothing */ this.muted = 0;
|
|
31
|
+
/** Cause trace ring size, default 0 = off (no cost). Set e.g. 200 in dev to record which event or op caused which follow-up event; read with trace() */
|
|
32
|
+
this.traceSize = 0;
|
|
33
|
+
/** @internal trace ring: arrival order until full, then _th marks the oldest */ this._trace = []; this._th = 0; this._tid = 0; this._cur = null; this._focus = null;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Verbose trace for one object (needs traceSize > 0): perception queries and state checks that name `obj` === id are recorded in full (misses too), the rest of the world only
|
|
37
|
+
* records what changed. null clears. For "why did this guard not see me": traceFocus('guard-1'), play, then read trace('sight').
|
|
38
|
+
* @param {string | null} id world record id
|
|
39
|
+
* @example engine.events.traceSize = 300; engine.events.traceFocus('guard-1');
|
|
40
|
+
*/
|
|
41
|
+
traceFocus(id) { this._focus = id ?? null; }
|
|
42
|
+
/**
|
|
43
|
+
* Add one entry to the cause trace (no-op while traceSize is 0; check `events.traceSize > 0` first to skip building info). Returns its parent id (`ev:<n>`) to pass as info.parent of follow-ups, or null.
|
|
44
|
+
* info: code (failure code), obj (world record id it is about), data (small plain values), verbose (true = only recorded while traceFocus(obj)), parent (default: the event or op running now).
|
|
45
|
+
* The engine notes failed ops (`op:<name>`), collision.lineClear (`sight`) and NPC state changes (`npc:state`); a game's behaviors can note their own, e.g. 'npc:mode' patrol -> investigate.
|
|
46
|
+
* @param {string} name
|
|
47
|
+
* @param {{ code?: string, obj?: string, data?: object, verbose?: boolean, parent?: string }} [info]
|
|
48
|
+
* @returns {string | null}
|
|
49
|
+
* @example if (e.events.traceSize > 0) e.events.note('npc:mode', { obj: rec.id, data: { from: 'patrol', to: 'investigate' } });
|
|
50
|
+
*/
|
|
51
|
+
note(name, info = {}) {
|
|
52
|
+
if (this.traceSize <= 0 || (info.verbose && info.obj !== this._focus)) return null;
|
|
53
|
+
return `ev:${this._note(name, info)}`;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Cause chains (needs traceSize > 0): each emitted event is recorded with parent = the event (`ev:<id>`) or op (`op:<name>#<seq>`) whose handler emitted it, null when
|
|
57
|
+
* it came from outside any. chain lists the causes from the nearest to the root (as far as the ring still holds). For "why did this fire".
|
|
58
|
+
* @param {string} [name] only events of this name
|
|
59
|
+
* Entries also carry code (failure code), obj and data when noted with events.note.
|
|
60
|
+
* @returns {{ id: number, tick: number, name: string, parent: string | null, chain: string[], code?: string, obj?: string, data?: object }[]}
|
|
61
|
+
* @example engine.events.traceSize = 200; engine.ops.run('shop.buy', { item: 'bread' }); engine.events.trace('item:add').at(-1).chain; // ['op:shop.buy#12']
|
|
62
|
+
*/
|
|
63
|
+
trace(name) {
|
|
64
|
+
const all = this._ordered();
|
|
65
|
+
const byId = new Map(all.map(t => [`ev:${t.id}`, t]));
|
|
66
|
+
return all.filter(t => !name || t.name === name).map(t => {
|
|
67
|
+
const chain = []; let p = t.parent;
|
|
68
|
+
while (p && chain.length < 32) { chain.push(p); p = byId.get(p)?.parent ?? null; }
|
|
69
|
+
return { ...t, chain };
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Recent events (old -> new); with name, only that kind: { tick = which fixed step, name, data = summary (simple values only; objects become '…') }. For "why did it not fire", first check whether it happened at all
|
|
74
|
+
* @param {string} [name]
|
|
75
|
+
* @returns {{ tick: number, name: string, data: any }[]}
|
|
76
|
+
* @example engine.events.recent('item:add');
|
|
77
|
+
*/
|
|
78
|
+
recent(name) {
|
|
79
|
+
const r = this.history, all = this._head ? r.slice(this._head).concat(r.slice(0, this._head)) : r.slice();
|
|
80
|
+
return name ? all.filter(h => h.name === name) : all;
|
|
81
|
+
}
|
|
82
|
+
/** @internal Record one history entry in the ring (O(1); the size may change at runtime) */
|
|
83
|
+
_record(name, data) {
|
|
84
|
+
const n = this.historySize;
|
|
85
|
+
if (this.history.length > n || (this._head && this.history.length < n)) { this.history = this.recent().slice(-n); this._head = 0; } // historySize changed: re-lay in order
|
|
86
|
+
const e = { tick: this.now(), name, data };
|
|
87
|
+
if (this.history.length < n) this.history.push(e); else { this.history[this._head] = e; this._head = (this._head + 1) % n; }
|
|
88
|
+
}
|
|
89
|
+
/** @internal */
|
|
90
|
+
_check(name) { if (this.seen.has(name)) return; checkEventName(name, this.seen); this.seen.add(name); }
|
|
91
|
+
/**
|
|
92
|
+
* Listen to an event; returns a handle { remove() }
|
|
93
|
+
* @template {EventName} K
|
|
94
|
+
* @param {K} name
|
|
95
|
+
* @param {(...args: EventArgs<K & string>) => void} fn
|
|
96
|
+
* @returns {Handle}
|
|
97
|
+
* @example const h = engine.events.on('item:add', ({ id, count }) => console.log(id, count));
|
|
98
|
+
* h.remove();
|
|
99
|
+
*/
|
|
100
|
+
on(name, fn) { this.seen && this._check(name); if (!this.map.has(name)) this.map.set(name, new Set()); this.map.get(name).add(fn); return { remove: () => this._off(name, fn) }; }
|
|
101
|
+
/**
|
|
102
|
+
* Listen once; returns a handle { remove() } (can be removed before it fires)
|
|
103
|
+
* @template {EventName} K
|
|
104
|
+
* @param {K} name
|
|
105
|
+
* @param {(...args: EventArgs<K & string>) => void} fn
|
|
106
|
+
* @returns {Handle}
|
|
107
|
+
*/
|
|
108
|
+
once(name, fn) { const h = this.on(name, (...a) => { h.remove(); fn(...a); }); return h; }
|
|
109
|
+
/** @internal Total listeners (used by engine.counts()) */
|
|
110
|
+
get size() { let n = 0; for (const s of this.map.values()) n += s.size; return n; }
|
|
111
|
+
/** @internal Remove all listeners (engine.dispose calls it) */
|
|
112
|
+
dispose() { this.map.clear(); }
|
|
113
|
+
/** @internal */
|
|
114
|
+
_off(name, fn) { this.map.get(name)?.delete(fn); } // listeners are removed only through the handle, h.remove()
|
|
115
|
+
/**
|
|
116
|
+
* Emit an event
|
|
117
|
+
* @template {EventName} K
|
|
118
|
+
* @param {K} name
|
|
119
|
+
* @param {EventArgs<K & string>} args
|
|
120
|
+
* @example engine.events.emit('item:add', { id: 'fish', count: 1 });
|
|
121
|
+
*/
|
|
122
|
+
emit(name, ...args) {
|
|
123
|
+
if (this.muted > 0) return; // set by an atomic rollback: the load must not announce changes that never happened
|
|
124
|
+
this.seen && this._check(name);
|
|
125
|
+
if (this.historySize > 0) this._record(name, brief(args[0])); // 0 = no history: no allocation, no copying
|
|
126
|
+
const s = this.map.get(name); if (!s) { if (this.traceSize > 0) this._note(name); return; }
|
|
127
|
+
const prev = this._cur;
|
|
128
|
+
if (this.traceSize > 0) this._cur = `ev:${this._note(name)}`; // handlers run under this event: what they emit names it as parent
|
|
129
|
+
try { for (const fn of [...s]) { try { fn(...args); } catch (err) { if (this.onError) this.onError(name, err); else console.error(`[event ${name}]`, err); } } }
|
|
130
|
+
finally { this._cur = prev; }
|
|
131
|
+
}
|
|
132
|
+
/** @internal trace entries old -> new */
|
|
133
|
+
_ordered() { const t = this._trace; return this._th ? t.slice(this._th).concat(t.slice(0, this._th)) : t; }
|
|
134
|
+
/** @internal Record one trace entry, returns its id */
|
|
135
|
+
_note(name, info) {
|
|
136
|
+
const id = ++this._tid, n = this.traceSize;
|
|
137
|
+
if (this._trace.length > n || (this._th && this._trace.length < n)) { this._trace = this._ordered().slice(-n); this._th = 0; } // traceSize changed: re-lay in order
|
|
138
|
+
const e = { id, tick: this.now(), name, parent: info?.parent ?? this._cur };
|
|
139
|
+
if (info) { if (info.code) e.code = info.code; if (info.obj) e.obj = info.obj; if (info.data) e.data = info.data; }
|
|
140
|
+
if (this._trace.length < n) this._trace.push(e); else { this._trace[this._th] = e; this._th = (this._th + 1) % n; }
|
|
141
|
+
return id;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Summary of event data: keeps simple values only; objects and arrays become '…' (history must not hold scene objects) */
|
|
146
|
+
function brief(v) {
|
|
147
|
+
if (v == null || typeof v !== 'object') return typeof v === 'function' ? '…' : v;
|
|
148
|
+
if (Array.isArray(v) || v.isObject3D) return '…';
|
|
149
|
+
const out = {};
|
|
150
|
+
let n = 0;
|
|
151
|
+
for (const k in v) { if (n++ >= 8) break; const x = v[k]; out[k] = x == null || (typeof x !== 'object' && typeof x !== 'function') ? x : '…'; }
|
|
152
|
+
return out;
|
|
153
|
+
}
|
package/core/I18n.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// i18n: engine and modules hardcode no UI text; they fetch it with engine.t('key', { params }).
|
|
2
|
+
// Modules register their default text (zh-CN, en) on install; a game may override it or add languages.
|
|
3
|
+
//
|
|
4
|
+
// createEngine({ locale: 'en', strings: { en: { 'inventory.title': 'Bag' } } })
|
|
5
|
+
// engine.i18n.setLocale('zh-CN')
|
|
6
|
+
// engine.t('inventory.got', { name: '胶卷', n: 3 }) // "获得 胶卷 ×3"
|
|
7
|
+
//
|
|
8
|
+
// {name} in a string is replaced by the param; {key:interact} becomes the currently bound key label.
|
|
9
|
+
|
|
10
|
+
/** @import { StringTables } from '../types/core' */
|
|
11
|
+
import { warnMissing } from './validate.js';
|
|
12
|
+
|
|
13
|
+
const CORE = {
|
|
14
|
+
'zh-CN': {
|
|
15
|
+
'common.close': '关闭', 'common.loading': '加载中', 'common.loadingAssets': '加载资源', 'common.preparing': '准备 {name}',
|
|
16
|
+
'common.generating': '生成 {name}', 'common.world': '世界',
|
|
17
|
+
'loading.queued': '等待 {name}', 'loading.download': '下载 {name}', 'loading.decode': '解码 {name}', 'loading.upload': '上传 {name}', 'loading.build': '生成 {name}', 'loading.failed': '加载失败:{name}', 'common.on': '开', 'common.off': '关',
|
|
18
|
+
'input.moveForward': '前进', 'input.moveBack': '后退', 'input.moveLeft': '向左', 'input.moveRight': '向右',
|
|
19
|
+
'input.run': '奔跑', 'input.interact': '交互', 'input.confirm': '确认', 'input.cancel': '返回',
|
|
20
|
+
'key.Space': '空格', 'key.Mouse0': '鼠标左键', 'key.Mouse1': '鼠标中键', 'key.Mouse2': '鼠标右键', 'key.Enter': '回车', 'ground.default': '默认',
|
|
21
|
+
'module.world': '世界数据', 'module.terrain': '地形', 'module.vegetation': '植被', 'module.sky': '天空', 'module.weather': '天气', 'module.water': '水面', 'module.collision': '碰撞', 'module.rigid': '物理引擎', 'module.cameraRig': '相机', 'module.characters': '角色', 'module.interactions': '交互', 'module.dialogue': '对话', 'module.inventory': '背包', 'module.quests': '任务', 'module.photo': '拍照', 'module.ambience': '环境音', 'module.debugPanel': '调试面板', 'module.level': '关卡', 'module.triggers': '触发区', 'module.entities': '实体', 'module.particles': '粒子', 'module.settings': '设置', 'module.music': '音乐', 'module.timeline': '时间轴', 'module.nav': '导航网格', 'module.hlod': '远景合并', 'module.lightPool': '光源池', 'module.content': '内容', 'module.flow': '游戏流程', 'module.hud': '目标指示', 'module.net': '联机', 'module.grids': '网格摆放',
|
|
22
|
+
},
|
|
23
|
+
en: {
|
|
24
|
+
'common.close': 'Close', 'common.loading': 'Loading', 'common.loadingAssets': 'Loading assets', 'common.preparing': 'Preparing {name}',
|
|
25
|
+
'common.generating': 'Generating {name}', 'common.world': 'world',
|
|
26
|
+
'loading.queued': 'Waiting for {name}', 'loading.download': 'Downloading {name}', 'loading.decode': 'Decoding {name}', 'loading.upload': 'Uploading {name}', 'loading.build': 'Building {name}', 'loading.failed': 'Failed to load: {name}', 'common.on': 'On', 'common.off': 'Off',
|
|
27
|
+
'input.moveForward': 'Forward', 'input.moveBack': 'Back', 'input.moveLeft': 'Left', 'input.moveRight': 'Right',
|
|
28
|
+
'input.run': 'Run', 'input.interact': 'Interact', 'input.confirm': 'Confirm', 'input.cancel': 'Back',
|
|
29
|
+
'key.Space': 'Space', 'key.Mouse0': 'Left click', 'key.Mouse1': 'Middle click', 'key.Mouse2': 'Right click', 'key.Enter': 'Enter', 'ground.default': 'default',
|
|
30
|
+
'module.world': 'world data', 'module.terrain': 'terrain', 'module.vegetation': 'vegetation', 'module.sky': 'sky', 'module.weather': 'weather', 'module.water': 'water', 'module.collision': 'collision', 'module.rigid': 'physics', 'module.cameraRig': 'camera', 'module.characters': 'characters', 'module.interactions': 'interactions', 'module.dialogue': 'dialogue', 'module.inventory': 'inventory', 'module.quests': 'quests', 'module.photo': 'photo', 'module.ambience': 'ambience', 'module.debugPanel': 'debug panel', 'module.level': 'level', 'module.triggers': 'triggers', 'module.entities': 'entities', 'module.particles': 'particles', 'module.settings': 'settings', 'module.music': 'music', 'module.timeline': 'timeline', 'module.nav': 'navmesh', 'module.hlod': 'distant merge', 'module.lightPool': 'light pool', 'module.content': 'content', 'module.flow': 'game flow', 'module.hud': 'objective markers', 'module.net': 'multiplayer', 'module.grids': 'grid placement',
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/** Resolve 'auto' from the browser: a language starting with zh gives 'zh-CN', anything else 'en'; other values pass through */
|
|
35
|
+
function resolveLocale(l) {
|
|
36
|
+
if (l !== 'auto') return l;
|
|
37
|
+
return /^zh/i.test(globalThis.navigator?.language ?? '') ? 'zh-CN' : 'en';
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** engine.i18n: string tables; t(key, params) fetches text and replaces {name} with params */
|
|
41
|
+
export class I18n {
|
|
42
|
+
/** @internal */
|
|
43
|
+
constructor(engine, { locale = 'auto', fallback = 'en', strings = {} } = {}) {
|
|
44
|
+
/** @internal */ this.engine = engine;
|
|
45
|
+
/** Current language, e.g. 'zh-CN' */
|
|
46
|
+
this.locale = resolveLocale(locale);
|
|
47
|
+
/** Language used when a key is missing in the current one (default 'en') */
|
|
48
|
+
this.fallback = fallback;
|
|
49
|
+
/** @internal keys already reported missing (t() may run every frame) */ this._missing = new Set();
|
|
50
|
+
/** @internal @type {StringTables} */ this.tables = {};
|
|
51
|
+
this.add(CORE);
|
|
52
|
+
/** @internal Game-given text wins @type {StringTables} */ this.overrides = strings;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Register string tables (never overrides text the game gave)
|
|
56
|
+
* @param {StringTables} tables
|
|
57
|
+
* @returns {this}
|
|
58
|
+
* @example engine.i18n.add({ 'zh-CN': { 'shop.buy': '购买 {name}' }, en: { 'shop.buy': 'Buy {name}' } });
|
|
59
|
+
*/
|
|
60
|
+
add(tables) { for (const lang in tables) this.tables[lang] = { ...this.tables[lang], ...tables[lang] }; return this; }
|
|
61
|
+
/** Switch language ('auto' picks from the browser like createEngine) @param {string} l */
|
|
62
|
+
setLocale(l) { this.locale = resolveLocale(l); this.engine.events.emit('i18n:change', this.locale); }
|
|
63
|
+
/** All available languages @returns {string[]} */
|
|
64
|
+
get languages() { return [...new Set([...Object.keys(this.tables), ...Object.keys(this.overrides)])]; }
|
|
65
|
+
/** Whether the key exists @param {string} key @returns {boolean} */
|
|
66
|
+
has(key) { return this._raw(key) != null; }
|
|
67
|
+
/** @internal */
|
|
68
|
+
_raw(key) {
|
|
69
|
+
for (const l of [this.locale, this.fallback]) {
|
|
70
|
+
const v = this.overrides[l]?.[key] ?? this.tables[l]?.[key];
|
|
71
|
+
if (v != null) return v;
|
|
72
|
+
}
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Fetch text; params replace {name}, {key:action} shows the key label
|
|
77
|
+
* @param {string} key
|
|
78
|
+
* @param {Record<string, any>} [params]
|
|
79
|
+
* @returns {string}
|
|
80
|
+
* @example engine.i18n.t('shop.buy', { name: '鱼' });
|
|
81
|
+
*/
|
|
82
|
+
t(key, params = {}) {
|
|
83
|
+
const raw = this._raw(key);
|
|
84
|
+
if (raw == null) {
|
|
85
|
+
// Looks like a key (a.b form) but has no text: probably misspelled or never registered
|
|
86
|
+
if (/^[\w-]+(\.[\w-]+)+$/.test(key) && !this._missing.has(key) && this._missing.add(key)) warnMissing('text', key, Object.keys({ ...this.tables[this.fallback], ...this.overrides[this.fallback], ...this.tables[this.locale], ...this.overrides[this.locale] }));
|
|
87
|
+
return key;
|
|
88
|
+
}
|
|
89
|
+
return String(raw).replace(/\{(\w+)(?::(\w+))?\}/g, (m, a, b) => {
|
|
90
|
+
if (a === 'key' && b) return this.engine.input.label(b);
|
|
91
|
+
return params[a] ?? m;
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
}
|