threedog 0.0.0-stage → 0.1.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 +267 -0
- package/core/Assets.js +240 -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/Describe.js +134 -0
- package/core/Engine.js +221 -0
- package/core/Events.js +95 -0
- package/core/I18n.js +94 -0
- package/core/Input.js +245 -0
- package/core/Inspect.js +97 -0
- package/core/InspectScene.js +187 -0
- package/core/Jobs.js +146 -0
- package/core/Loading.js +149 -0
- package/core/Ops.js +272 -0
- package/core/Random.js +52 -0
- package/core/Rays.js +160 -0
- package/core/SaveStore.js +85 -0
- package/core/Saves.js +253 -0
- package/core/Stream.js +279 -0
- package/core/Threads.js +158 -0
- package/core/UrlState.js +93 -0
- package/core/Vars.js +34 -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/audioRules.js +121 -0
- package/core/audioVoice.js +225 -0
- package/core/batchGroups.js +116 -0
- package/core/canvasBox.js +63 -0
- package/core/dayTime.js +15 -0
- package/core/describeText.js +136 -0
- package/core/easing.js +34 -0
- package/core/errorCodes.js +172 -0
- package/core/errorHints.js +203 -0
- package/core/errors.js +40 -0
- package/core/events.generated.js +84 -0
- package/core/ground.js +102 -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 +68 -0
- package/core/lightWatch.js +36 -0
- package/core/loop.js +199 -0
- package/core/math.js +33 -0
- package/core/modules.js +182 -0
- package/core/movement.js +19 -0
- package/core/mulberry32.js +14 -0
- package/core/opsCheck.js +86 -0
- package/core/opsGuard.js +26 -0
- package/core/opsHistory.js +27 -0
- package/core/page.js +78 -0
- package/core/pureWorker.js +5 -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 +125 -0
- package/core/screenToGround.js +39 -0
- package/core/session.js +171 -0
- package/core/shadowTypes.js +15 -0
- package/core/skip.js +104 -0
- package/core/startup.js +133 -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/thingOps.js +157 -0
- package/core/things.js +198 -0
- package/core/threadPure.js +120 -0
- package/core/threadServe.js +25 -0
- package/core/tier.js +11 -0
- package/core/validate.js +188 -0
- package/docs/AI.md +149 -0
- package/docs/API.md +84 -0
- package/docs/CODEMAP.md +335 -0
- package/docs/COMMANDS.md +96 -0
- package/docs/CONVENTIONS.md +134 -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 +60 -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 +142 -0
- package/docs/api/clock.md +7 -0
- package/docs/api/collision.md +35 -0
- package/docs/api/content.md +63 -0
- package/docs/api/debug.md +10 -0
- package/docs/api/dialogue.md +39 -0
- package/docs/api/engine.md +190 -0
- package/docs/api/entities.md +61 -0
- package/docs/api/events.md +91 -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 +9 -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 +31 -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 +55 -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 +151 -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 +104 -0
- package/docs/recipes/07-flow-scenes-pause.md +128 -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 +57 -0
- package/docs/recipes/13-animation.md +146 -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 +146 -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 +104 -0
- package/docs/recipes/22-shop-gold.md +107 -0
- package/docs/recipes/23-ops.md +139 -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 +35 -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 +81 -0
- package/docs/recipes/40-scene.md +79 -0
- package/docs/recipes/41-thing-registry.md +64 -0
- package/docs/recipes/42-terrain-shape.md +64 -0
- package/docs/recipes/43-shader-patches-surface-looks.md +118 -0
- package/docs/recipes/44-water-weather-look-hooks.md +133 -0
- package/docs/recipes/45-cascaded-shadows.md +51 -0
- package/docs/recipes/46-blender-art-route.md +92 -0
- package/docs/recipes/47-island-snow-backdrop.md +44 -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 +9 -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/look.js +5 -0
- package/examples/action/main.js +137 -0
- package/examples/action/models.js +25 -0
- package/examples/sheepisland/GAMEMAP.md +108 -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 +279 -0
- package/index.js +120 -0
- package/llms.txt +56 -0
- package/modules/ambience/Ambience.js +183 -0
- package/modules/camera/FirstPersonCamera.js +133 -0
- package/modules/camera/FixedCamera.js +155 -0
- package/modules/camera/FollowCamera.js +85 -0
- package/modules/camera/RtsCamera.js +134 -0
- package/modules/camera/common.js +152 -0
- package/modules/camera/index.js +11 -0
- package/modules/characters/Character.js +223 -0
- package/modules/characters/NPC.js +242 -0
- package/modules/characters/assetModel.js +42 -0
- package/modules/characters/astar.js +59 -0
- package/modules/characters/behaviors.js +72 -0
- package/modules/characters/footsteps.js +13 -0
- package/modules/characters/index.js +212 -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 +38 -0
- package/modules/characters/npcAvoid.js +129 -0
- package/modules/characters/npcSim.js +144 -0
- package/modules/characters/npcView.js +42 -0
- package/modules/characters/pathAsync.js +107 -0
- package/modules/characters/pathJob.js +61 -0
- package/modules/characters/pathWorker.js +7 -0
- package/modules/characters/playerStrings.js +12 -0
- package/modules/characters/proceduralRig.js +54 -0
- package/modules/collision/Collision.js +176 -0
- package/modules/collision/grid.js +63 -0
- package/modules/content/ids.js +95 -0
- package/modules/content/index.js +152 -0
- package/modules/content/loader.js +187 -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 +133 -0
- package/modules/content/templates.js +189 -0
- package/modules/debug/DebugPanel.js +168 -0
- package/modules/entities/Entities.js +239 -0
- package/modules/entities/build.js +25 -0
- package/modules/entities/index.js +4 -0
- package/modules/flow/index.js +98 -0
- package/modules/gameplay/Container.js +227 -0
- package/modules/gameplay/Containers.js +89 -0
- package/modules/gameplay/Dialogue.js +216 -0
- package/modules/gameplay/Interactions.js +243 -0
- package/modules/gameplay/Inventory.js +214 -0
- package/modules/gameplay/Quests.js +195 -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 +113 -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 +75 -0
- package/modules/hlod/index.js +164 -0
- package/modules/hud/index.js +164 -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 +231 -0
- package/modules/level/nodes.js +84 -0
- package/modules/lights/index.js +224 -0
- package/modules/music/Music.js +290 -0
- package/modules/music/index.js +2 -0
- package/modules/music/rules.js +28 -0
- package/modules/nav/index.js +154 -0
- package/modules/nav/navPath.js +17 -0
- package/modules/net/Client.js +136 -0
- package/modules/net/Host.js +117 -0
- package/modules/net/Net.js +49 -0
- package/modules/net/index.js +75 -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 +143 -0
- package/modules/rigid/RigidBodies.js +262 -0
- package/modules/rigid/Vehicles.js +97 -0
- package/modules/rigid/sync.js +158 -0
- package/modules/settings/Settings.js +294 -0
- package/modules/settings/apply.js +20 -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 +257 -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 +115 -0
- package/modules/sky/fog.js +136 -0
- package/modules/sky/frame.js +76 -0
- package/modules/sky/layers.js +69 -0
- package/modules/sky/look.js +50 -0
- package/modules/sky/schedule.js +80 -0
- package/modules/sky/shader.js +96 -0
- package/modules/sky/shadow.js +80 -0
- package/modules/sky/skyModule.js +59 -0
- package/modules/terrain/ChunkManager.js +291 -0
- package/modules/terrain/chunkJob.js +19 -0
- package/modules/terrain/chunkQueries.js +42 -0
- package/modules/terrain/chunkWorker.js +5 -0
- package/modules/terrain/index.js +110 -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 +249 -0
- package/modules/timeline/Tween.js +118 -0
- package/modules/timeline/letterbox.js +24 -0
- package/modules/timeline/shots.js +88 -0
- package/modules/triggers/index.js +261 -0
- package/modules/vegetation/Vegetation.js +255 -0
- package/modules/vegetation/groundChunks.js +177 -0
- package/modules/vegetation/index.js +40 -0
- package/modules/vegetation/modelGeometry.js +21 -0
- package/modules/water/Water.js +144 -0
- package/modules/water/surface.js +88 -0
- package/modules/weather/Weather.js +251 -0
- package/modules/weather/particles.js +92 -0
- package/modules/weather/shaders.js +49 -0
- package/modules/world/World.js +231 -0
- package/modules/world/cells.js +42 -0
- package/modules/world/index.js +64 -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/views.js +182 -0
- package/package.json +66 -4
- package/presets.js +96 -0
- package/render/PostFX.js +243 -0
- package/render/detail.js +105 -0
- package/render/effects.js +142 -0
- package/render/engineUniforms.js +23 -0
- package/render/fuse.js +72 -0
- package/render/lighting.js +100 -0
- package/render/lights.js +16 -0
- package/render/materials.js +203 -0
- package/render/patches.js +252 -0
- package/render/surface.js +67 -0
- package/render/uniformDecl.js +29 -0
- package/types/common.d.ts +34 -0
- package/types/core.d.ts +1773 -0
- package/types/gameplay.d.ts +1812 -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/Events.d.ts +46 -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 +162 -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 +161 -0
- package/types/generated/core/Stream.d.ts +93 -0
- package/types/generated/core/Threads.d.ts +82 -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 +64 -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 +152 -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 +72 -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 +128 -0
- package/types/generated/render/materials.d.ts +90 -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 +584 -0
- package/types/style.d.ts +628 -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 +195 -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/Engine.js
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
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 { Events } from './Events.js';
|
|
7
|
+
import { Input } from './Input.js';
|
|
8
|
+
import { I18n } from './I18n.js';
|
|
9
|
+
import { Saves } from './Saves.js';
|
|
10
|
+
import { Session } from './session.js';
|
|
11
|
+
import { Page } from './page.js';
|
|
12
|
+
import { Assets } from './Assets.js';
|
|
13
|
+
import { Audio } from './Audio.js';
|
|
14
|
+
import { PostFX } from '../render/PostFX.js';
|
|
15
|
+
import { createDefaultLights } from '../render/lights.js';
|
|
16
|
+
import { registerEngine, makeMaterial } from '../render/materials.js';
|
|
17
|
+
import { createUniforms } from '../render/effects.js';
|
|
18
|
+
import { bindUniforms } from '../render/engineUniforms.js';
|
|
19
|
+
import { UIParts } from '../ui/Parts.js';
|
|
20
|
+
import { defineCoreParts } from '../ui/defaults.js';
|
|
21
|
+
import { applyUIStyle } from '../ui/theme.js';
|
|
22
|
+
import { describeApi } from './Describe.js';
|
|
23
|
+
import { setValidate, checkOptions, warnOnce, DEV } from './validate.js';
|
|
24
|
+
import { Clock } from './Clock.js';
|
|
25
|
+
import { Vars } from './Vars.js';
|
|
26
|
+
import { Budget } from './Budget.js';
|
|
27
|
+
import { Rays } from './Rays.js';
|
|
28
|
+
import { UrlState } from './UrlState.js';
|
|
29
|
+
import { Jobs } from './Jobs.js';
|
|
30
|
+
import { Threads } from './Threads.js';
|
|
31
|
+
import { Commits } from './Commits.js';
|
|
32
|
+
import { Ops } from './Ops.js';
|
|
33
|
+
import { Stream } from './Stream.js';
|
|
34
|
+
import { Batching } from './Batching.js';
|
|
35
|
+
import { Random } from './Random.js';
|
|
36
|
+
import { loopMethods } from './loop.js';
|
|
37
|
+
import { startupMethods } from './startup.js';
|
|
38
|
+
import { groundMethods, flatGround } from './ground.js';
|
|
39
|
+
import { actorMethods } from './actor.js';
|
|
40
|
+
import { detectTier } from './tier.js';
|
|
41
|
+
import { lifecycleMethods } from './lifecycle.js';
|
|
42
|
+
import { reportListenerError } from './errors.js';
|
|
43
|
+
import { createMovement } from './movement.js';
|
|
44
|
+
import { moduleMethods } from './modules.js';
|
|
45
|
+
import { skipMethods, defineSkipOp } from './skip.js';
|
|
46
|
+
import { styleFrom, NO_STYLE } from './styleParts.js';
|
|
47
|
+
import { canvasBox, placeUI, resizeMethods } from './canvasBox.js';
|
|
48
|
+
import { sceneMethods, TONE } from './sceneMethods.js';
|
|
49
|
+
import { installThings } from './thingOps.js';
|
|
50
|
+
import { shadowTypeOf } from './shadowTypes.js';
|
|
51
|
+
// Options createEngine accepts (must match the constructor destructuring)
|
|
52
|
+
const ENGINE_OPTIONS = ['canvas', 'style', 'shadows', 'shadowType', 'antialias', 'post', 'pixelRatio', 'adaptiveResolution', 'targetFps', 'ui', 'audio',
|
|
53
|
+
'fov', 'near', 'fogFar',
|
|
54
|
+
'locale', 'strings', 'bindings', 'saveKey', 'joystick', 'padBindings', 'headless', 'validate', 'decoders', 'budget', 'urlState', 'seed', 'movement', 'threads', 'pauseOnBlur', 'batching'];
|
|
55
|
+
|
|
56
|
+
export class Engine {
|
|
57
|
+
/**
|
|
58
|
+
* @param o createEngine options: each option, its default and meaning is documented once on EngineOptions (types/core.d.ts).
|
|
59
|
+
* 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.
|
|
60
|
+
*/
|
|
61
|
+
constructor(opts = {}) {
|
|
62
|
+
setValidate(opts.validate);
|
|
63
|
+
checkOptions('createEngine()', opts, ENGINE_OPTIONS);
|
|
64
|
+
const { canvas, style: styleIn, shadows = true, shadowType = 'pcf', antialias, post, pixelRatio, adaptiveResolution = true, targetFps = 55, ui = {}, audio = {},
|
|
65
|
+
fov = 55, near = 0.3, fogFar = 600, locale = 'auto', strings = {}, bindings = {}, saveKey = 'game', joystick = 'auto', padBindings = {},
|
|
66
|
+
headless = new URLSearchParams(location.search).has('threedog-headless'), validate = true,
|
|
67
|
+
decoders = null, budget = null, urlState = DEV, seed, movement, threads = 'auto', pauseOnBlur = true, batching = {} } = opts;
|
|
68
|
+
this.THREE = THREE;
|
|
69
|
+
this.movement = createMovement(movement); // character radius / height / slope / step height: the single copy shared by collision, physics and nav
|
|
70
|
+
const style = this.style = styleFrom(styleIn); // a list of parts is deep-merged (styleParts.js); one object is used as is
|
|
71
|
+
if (!opts.style) warnOnce(NO_STYLE);
|
|
72
|
+
const r = this.renderer = new THREE.WebGLRenderer({ canvas, antialias: false, powerPreference: 'high-performance' });
|
|
73
|
+
this.tier = detectTier(r); // 'low' | 'high': device tier, decides default quality
|
|
74
|
+
r.setPixelRatio(pixelRatio ?? Math.min(devicePixelRatio || 1, this.tier === 'low' ? 1 : 1.5));
|
|
75
|
+
this._autoSize = undefined; // decided once the canvas is in the page (sizeMode): true = no CSS size, the engine sizes it to the window
|
|
76
|
+
const box = canvasBox(this);
|
|
77
|
+
r.setSize(box.w, box.h, !!this._autoSize);
|
|
78
|
+
r.toneMapping = TONE[style.toneMapping ?? 'none']; // no tone mapping without a style pack: the look (ACES, exposure) is the style pack's
|
|
79
|
+
this.setExposure(style.exposure ?? 1); // a number, or day keyframes / a function the sky evaluates each frame
|
|
80
|
+
r.shadowMap.enabled = shadows;
|
|
81
|
+
r.shadowMap.type = shadowTypeOf(shadowType, 'createEngine({ shadowType })');
|
|
82
|
+
r.info.autoReset = false;
|
|
83
|
+
|
|
84
|
+
this.scene = new THREE.Scene();
|
|
85
|
+
this.scene.background = new THREE.Color(style.background ?? 0x8c8c8c);
|
|
86
|
+
/** Default lights { sun: DirectionalLight, hemi: HemisphereLight }: neutral without sky, driven by sky when installed @type {{ sun: any, hemi: any }} */
|
|
87
|
+
this.lights = createDefaultLights(this);
|
|
88
|
+
this.camera = new THREE.PerspectiveCamera(fov, box.w / box.h, near, 1500);
|
|
89
|
+
this.camera.position.set(0, 10, 20);
|
|
90
|
+
this.focus = new THREE.Vector3(); // camera focus (updated by the camera module): the view loads around it; simulation follows world.anchor
|
|
91
|
+
this.shadows = shadows;
|
|
92
|
+
/** Shadow filter in use ('basic' | 'pcf' | 'vsm'); change it with sky.setShadow({ type }) @type {string} */
|
|
93
|
+
this.shadowType = shadowType;
|
|
94
|
+
this.ground = flatGround;
|
|
95
|
+
this.player = null;
|
|
96
|
+
/**
|
|
97
|
+
* 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
|
|
98
|
+
* control to a vehicle or squad member @type {string}
|
|
99
|
+
*/
|
|
100
|
+
this.actor = 'player';
|
|
101
|
+
this.ready = false;
|
|
102
|
+
this.disposed = false; // true after dispose()
|
|
103
|
+
this._abort = new AbortController();
|
|
104
|
+
// attach DOM listeners to it: addEventListener(type, fn, { signal: engine.signal }); dispose cancels them together
|
|
105
|
+
this.signal = this._abort.signal;
|
|
106
|
+
this.uiRoot = document.createElement('div'); // engine and module UI elements live here (not on body); dispose removes the whole root
|
|
107
|
+
// the UI root sits right after the canvas and covers exactly its box (placeUI): HUD, windows and prompts line up with the canvas
|
|
108
|
+
// whether it fills the window, sits in a page section, a split layout or an editor panel
|
|
109
|
+
this.uiRoot.className = 'threedog-root';
|
|
110
|
+
if (r.domElement.parentElement) r.domElement.after(this.uiRoot); else document.body.appendChild(this.uiRoot);
|
|
111
|
+
this.headless = headless;
|
|
112
|
+
this.paused = headless; // while paused the real-time loop does not advance; only step() does
|
|
113
|
+
this.fps = 0;
|
|
114
|
+
this.cpuMs = 0; // main-thread ms of the last real-time frame; cpuPhases splits it (loop.js)
|
|
115
|
+
this.cpuPhases = { fixed: 0, frame: 0, render: 0, afterRender: 0 };
|
|
116
|
+
this.openWindows = new Set(); // ids of open windows (for describe)
|
|
117
|
+
this.fogFar = fogFar; // base fog distance; terrain view range changes it, weather scales it
|
|
118
|
+
this.modules = new Map();
|
|
119
|
+
this._modState = new Map(); // module name -> registered | initializing | running | failed | disposed (modules.js)
|
|
120
|
+
this.waterBodies = [];
|
|
121
|
+
this._fixed = []; this._frame = []; this._hooks = { fixed: [], frame: [], afterRender: [], skip: [] };
|
|
122
|
+
this._hookErrors = new Set(); // places that already reported an error (once per place, see errors.js)
|
|
123
|
+
this.error = null; // gameplay error in dev/test: { where, message, cause?, docs? }; gameplay is frozen (see errors.js)
|
|
124
|
+
this.disabledModules = new Set(); // presentation modules disabled after they threw
|
|
125
|
+
this._elapsed = 0; // engine.elapsed: fixed seconds, advanced per fixed step and copied into uniforms.uTime
|
|
126
|
+
/**
|
|
127
|
+
* This engine's shader uniforms (uTime, uWind, uCloud, season tints...); share these objects in your own ShaderMaterial or patch @type
|
|
128
|
+
* {import('../types/core').EngineUniforms}
|
|
129
|
+
*/
|
|
130
|
+
this.uniforms = createUniforms(style);
|
|
131
|
+
bindUniforms(r, this.uniforms); // built-in shader effects read this engine's uniforms when compiled by this renderer
|
|
132
|
+
this._materials = registerEngine(this); // makeMaterial without an engine argument uses the first live engine's style pack
|
|
133
|
+
|
|
134
|
+
this.events = new Events({ check: import.meta.env?.DEV && validate !== false, // event-name spelling check runs in development only
|
|
135
|
+
onError: (name, err) => reportListenerError(this, name, err), now: () => this.tick }); // listener errors are handled by severity (errors.js)
|
|
136
|
+
this.i18n = new I18n(this, { locale, strings });
|
|
137
|
+
this.saves = new Saves(this, { prefix: saveKey + '-' });
|
|
138
|
+
this.session = new Session(this); // new game / continue / back to title from a clean slate (session.js)
|
|
139
|
+
this.input = new Input(this, canvas, { joystick, bindings, padBindings });
|
|
140
|
+
this.events.on('ui:open', id => this.openWindows.add(id));
|
|
141
|
+
this.events.on('ui:close', id => this.openWindows.delete(id));
|
|
142
|
+
this.audio = new Audio(this, audio);
|
|
143
|
+
this.decoders = decoders;
|
|
144
|
+
this.assets = new Assets(this);
|
|
145
|
+
this.clock = new Clock(this); // game clock (game seconds, timers)
|
|
146
|
+
this.vars = new Vars(this); // story flags and counters
|
|
147
|
+
this.budget = new Budget(this); // performance budget (default off)
|
|
148
|
+
if (budget) this.budget.enable(budget);
|
|
149
|
+
this.rays = new Rays(this); // ray registry: engine.raycast / pick
|
|
150
|
+
Object.assign(this, describeApi(this)); // describe / describeText / inspect / explain, see Describe.js
|
|
151
|
+
this.random = new Random(seed ?? (headless ? 1 : Date.now())); // wall-clock: differs per run when no seed is given
|
|
152
|
+
this.saves.register('random', { save: () => this.random.toJSON(), load: d => this.random.fromJSON(d) });
|
|
153
|
+
this._urlState = new UrlState(this, { fromUrl: urlState });
|
|
154
|
+
this._freezers = new Set(); // who froze gameplay (freeze)
|
|
155
|
+
this.tick = 0; // fixed-step count (the gameplay timeline: commits, event history and input records use it; stops while frozen)
|
|
156
|
+
this.commits = new Commits(this); // background results that affect gameplay take effect on a fixed tick (see Commits.js)
|
|
157
|
+
this.ops = new Ops(this); // one entry point for actions (define / run / can / list / recent), see Ops.js
|
|
158
|
+
defineSkipOp(this); // 'time.skip', behind engine.skip (skip.js)
|
|
159
|
+
installThings(this); // engine.add registry, thing.set / remove, 'scene' save part
|
|
160
|
+
this.jobs = new Jobs(this); // frame-spread job scheduler
|
|
161
|
+
this.threads = new Threads(threads); // worker pool (see Threads.js); workers start only when a lane is used
|
|
162
|
+
// spatial stream-in and the stream sources (where the world is loaded: stream, models, terrain, colliders read them)
|
|
163
|
+
this.stream = new Stream(this);
|
|
164
|
+
this.batching = new Batching(this, batching); // repeated static models drawn as InstancedMesh batches (Batching.js)
|
|
165
|
+
this.startup = null; // startup timing report (set once start() finishes)
|
|
166
|
+
this._prof = null; // module hook timing (profile(true) turns it on)
|
|
167
|
+
this._afterTick = null; // at startup, checked once at the end of each frame for readiness
|
|
168
|
+
// effects come from the style pack; costly ones start off on low-tier devices unless the post option names them
|
|
169
|
+
this.post = new PostFX(this, { antialias: antialias ?? style.antialias ?? this.tier !== 'low', effects: style.post, enabled: post });
|
|
170
|
+
this._uiStyle = applyUIStyle(this, style.ui); // theme variables, pack CSS and fonts; removed on dispose
|
|
171
|
+
this.ui = new UIParts(this, ui); // UI parts: every piece of screen UI is replaceable or off (ui/Parts.js)
|
|
172
|
+
defineCoreParts(this);
|
|
173
|
+
this.ui.get('loading')?.show({});
|
|
174
|
+
this.adaptive = { paused: false, on: adaptiveResolution && !headless, target: targetFps, min: 0.6, max: r.getPixelRatio(),
|
|
175
|
+
t: 0, n: 0, good: 0, cooldown: 0 };
|
|
176
|
+
// follow the canvas's own CSS box, not the window: a canvas in a page section or editor panel renders at its own size.
|
|
177
|
+
// 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
|
|
178
|
+
addEventListener('resize', () => this._resize(), { signal: this.signal });
|
|
179
|
+
if (typeof ResizeObserver === 'function') {
|
|
180
|
+
const ro = new ResizeObserver(() => this._resize());
|
|
181
|
+
ro.observe(r.domElement);
|
|
182
|
+
this.signal.addEventListener('abort', () => ro.disconnect());
|
|
183
|
+
}
|
|
184
|
+
placeUI(this);
|
|
185
|
+
this.page = new Page(this, { pauseOnBlur }); // window focus, tab visibility, mouse lock, WebGL context: handled only there
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
get waterLevel() { return this.ground.waterLevel; }
|
|
189
|
+
|
|
190
|
+
// ---------- common ----------
|
|
191
|
+
/** Get a UI string (i18n) */
|
|
192
|
+
t(key, params) { return this.i18n.t(key, params); }
|
|
193
|
+
/**
|
|
194
|
+
* Elapsed fixed-step seconds (ignores clock.timeScale; stops while frozen or paused), for presentation animation (sway, bobbing). Game seconds are clock.now
|
|
195
|
+
* (= fixed-step seconds × timeScale); sky time of day is sky.timeOfDay
|
|
196
|
+
*/
|
|
197
|
+
get elapsed() { return this._elapsed; }
|
|
198
|
+
/** Material by role from this engine's style pack: engine.makeMaterial('prop', { color: 0x8a5a36 }) */
|
|
199
|
+
makeMaterial(purpose, params) { return makeMaterial(purpose, params, this); }
|
|
200
|
+
/** Ray cast: the nearest hit or null, see Rays.js */
|
|
201
|
+
raycast(origin, dir, opts) { return this.rays.cast(origin, dir, opts); }
|
|
202
|
+
/** Cast a ray from screen coordinates (-1..1) */
|
|
203
|
+
pick(ndcX, ndcY, opts) { return this.rays.pick(ndcX, ndcY, opts); }
|
|
204
|
+
/** Set up a scenario: { time, weather, pos, save, wait, cutscene, state }, see UrlState.js */
|
|
205
|
+
applyState(params) { return this._urlState.apply(params); }
|
|
206
|
+
/** Scenario ready: start() has finished and the URL parameters / latest applyState are applied (tests and screenshots wait for it) */
|
|
207
|
+
get stateApplied() { return this.ready && this._urlState.applied; }
|
|
208
|
+
/** Name a set of scenario parameters, then use applyState({ state: name }) or the URL ?state=name */
|
|
209
|
+
defineState(name, params) { this._urlState.define(name, params); return this; }
|
|
210
|
+
/** Fixed-step logic (60 per second): movement, timers, gameplay keys. Returns a handle { remove() } */
|
|
211
|
+
onFixed(fn) { this._fixed.push(fn); return { remove: () => { this._fixed = this._fixed.filter(f => f !== fn); } }; }
|
|
212
|
+
/** Once per frame: animation, camera, UI. Returns a handle { remove() } */
|
|
213
|
+
onFrame(fn) { this._frame.push(fn); return { remove: () => { this._frame = this._frame.filter(f => f !== fn); } }; }
|
|
214
|
+
|
|
215
|
+
/** @internal Display name of a module (loading screen): module.<name> from the string table, else the module's own label */
|
|
216
|
+
moduleName(m) { return this.i18n.has('module.' + m.name) ? this.t('module.' + m.name) : (m.label || m.name); }
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Mix in by property descriptor (Object.assign would evaluate getters on the spot and lose them)
|
|
220
|
+
for (const part of [loopMethods, startupMethods, groundMethods, actorMethods, moduleMethods, lifecycleMethods, skipMethods, resizeMethods, sceneMethods])
|
|
221
|
+
Object.defineProperties(Engine.prototype, Object.getOwnPropertyDescriptors(part));
|
package/core/Events.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
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
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* 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
|
|
33
|
+
* @param {string} [name]
|
|
34
|
+
* @returns {{ tick: number, name: string, data: any }[]}
|
|
35
|
+
* @example engine.events.recent('item:add');
|
|
36
|
+
*/
|
|
37
|
+
recent(name) {
|
|
38
|
+
const r = this.history, all = this._head ? r.slice(this._head).concat(r.slice(0, this._head)) : r.slice();
|
|
39
|
+
return name ? all.filter(h => h.name === name) : all;
|
|
40
|
+
}
|
|
41
|
+
/** @internal Record one history entry in the ring (O(1); the size may change at runtime) */
|
|
42
|
+
_record(name, data) {
|
|
43
|
+
const n = this.historySize;
|
|
44
|
+
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
|
|
45
|
+
const e = { tick: this.now(), name, data };
|
|
46
|
+
if (this.history.length < n) this.history.push(e); else { this.history[this._head] = e; this._head = (this._head + 1) % n; }
|
|
47
|
+
}
|
|
48
|
+
/** @internal */
|
|
49
|
+
_check(name) { if (this.seen.has(name)) return; checkEventName(name, this.seen); this.seen.add(name); }
|
|
50
|
+
/**
|
|
51
|
+
* Listen to an event; returns a handle { remove() }
|
|
52
|
+
* @template {EventName} K
|
|
53
|
+
* @param {K} name
|
|
54
|
+
* @param {(...args: EventArgs<K & string>) => void} fn
|
|
55
|
+
* @returns {Handle}
|
|
56
|
+
* @example const h = engine.events.on('item:add', ({ id, count }) => console.log(id, count));
|
|
57
|
+
* h.remove();
|
|
58
|
+
*/
|
|
59
|
+
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) }; }
|
|
60
|
+
/**
|
|
61
|
+
* Listen once; returns a handle { remove() } (can be removed before it fires)
|
|
62
|
+
* @template {EventName} K
|
|
63
|
+
* @param {K} name
|
|
64
|
+
* @param {(...args: EventArgs<K & string>) => void} fn
|
|
65
|
+
* @returns {Handle}
|
|
66
|
+
*/
|
|
67
|
+
once(name, fn) { const h = this.on(name, (...a) => { h.remove(); fn(...a); }); return h; }
|
|
68
|
+
/** @internal Total listeners (used by engine.counts()) */
|
|
69
|
+
get size() { let n = 0; for (const s of this.map.values()) n += s.size; return n; }
|
|
70
|
+
/** @internal Remove all listeners (engine.dispose calls it) */
|
|
71
|
+
dispose() { this.map.clear(); }
|
|
72
|
+
/** @internal */
|
|
73
|
+
_off(name, fn) { this.map.get(name)?.delete(fn); } // listeners are removed only through the handle, h.remove()
|
|
74
|
+
/**
|
|
75
|
+
* Emit an event
|
|
76
|
+
* @template {EventName} K
|
|
77
|
+
* @param {K} name
|
|
78
|
+
* @param {EventArgs<K & string>} args
|
|
79
|
+
* @example engine.events.emit('item:add', { id: 'fish', count: 1 });
|
|
80
|
+
*/
|
|
81
|
+
emit(name, ...args) {
|
|
82
|
+
this.seen && this._check(name);
|
|
83
|
+
if (this.historySize > 0) this._record(name, brief(args[0])); // 0 = no history: no allocation, no copying
|
|
84
|
+
const s = this.map.get(name); if (s) for (const fn of [...s]) { try { fn(...args); } catch (err) { if (this.onError) this.onError(name, err); else console.error(`[event ${name}]`, err); } } }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Summary of event data: keeps simple values only; objects and arrays become '…' (history must not hold scene objects) */
|
|
88
|
+
function brief(v) {
|
|
89
|
+
if (v == null || typeof v !== 'object') return typeof v === 'function' ? '…' : v;
|
|
90
|
+
if (Array.isArray(v) || v.isObject3D) return '…';
|
|
91
|
+
const out = {};
|
|
92
|
+
let n = 0;
|
|
93
|
+
for (const k in v) { if (n++ >= 8) break; const x = v[k]; out[k] = x == null || (typeof x !== 'object' && typeof x !== 'function') ? x : '…'; }
|
|
94
|
+
return out;
|
|
95
|
+
}
|
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.debug': '调试面板', '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.debug': '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
|
+
}
|