@threenative/core 0.3.12 → 0.3.15
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/README.md +1 -1
- package/capabilities.json +1047 -44
- package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
- package/dist/{canvas-layer-CWuFRT7G.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
- package/dist/{chunk-7UUT3TY5.js → chunk-2GPHICV6.js} +1 -1
- package/dist/{chunk-GMHATRPW.js → chunk-GEMQJBY4.js} +1650 -383
- package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
- package/dist/{chunk-5O73CDMR.js → chunk-QAMSM3Z5.js} +415 -27
- package/dist/{chunk-2Z44XSI2.js → chunk-QAQHYOWY.js} +3 -7
- package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
- package/dist/{chunk-OKXUCASC.js → chunk-VBBYWGAT.js} +3 -4
- package/dist/chunk-VP43GIWW.js +18 -0
- package/dist/{chunk-N5LRP4BR.js → chunk-VQRPEOKY.js} +66 -3
- package/dist/{chunk-6KLNISRJ.js → chunk-XDTZ4QMO.js} +11 -4
- package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
- package/dist/{game-D7pAzZUY.d.ts → game-k8K3hZai.d.ts} +72 -8
- package/dist/hot.d.ts +5 -4
- package/dist/hot.js +5 -8
- package/dist/index.d.ts +871 -1018
- package/dist/index.js +4786 -1631
- package/dist/{model-lod-B6BMqS1r.d.ts → model-lod-DPTzeCcD.d.ts} +4 -2
- package/dist/playtest.d.ts +5 -4
- package/dist/playtest.js +6 -5
- package/dist/quality-BADStsTn.d.ts +868 -0
- package/dist/react.d.ts +3 -2
- package/dist/render-environment.d.ts +170 -0
- package/dist/render-environment.js +352 -0
- package/dist/{renderer-DvFVoAgj.d.ts → renderer-BtOSseYf.d.ts} +29 -31
- package/dist/spells/index.js +1 -1
- package/dist/ui-layer.js +3 -2
- package/dist/worker.js +12 -5
- package/dist/world.d.ts +280 -16
- package/dist/world.js +1529 -642
- package/mcp/animation-server.mjs +1 -1
- package/mcp/engine-server.mjs +135 -11
- package/mcp/servers.mjs +4 -4
- package/package.json +10 -6
- package/scripts/ensure-mcp.mjs +6 -1
- package/src/animation-batch.ts +193 -0
- package/src/animation-layers.ts +7 -3
- package/src/animation.ts +209 -29
- package/src/asset-cache.ts +3 -3
- package/src/asset-memo.ts +202 -0
- package/src/assets.ts +436 -131
- package/src/auto-batch.ts +190 -44
- package/src/clustered-batch.ts +146 -3
- package/src/clustered-mesh.ts +548 -20
- package/src/compute-driven.ts +1 -1
- package/src/config.ts +8 -0
- package/src/debug.ts +119 -22
- package/src/dev-global.ts +54 -0
- package/src/displaced-surface.ts +428 -0
- package/src/engine-hooks.ts +37 -0
- package/src/frame-budget.ts +35 -3
- package/src/game-boot-phase.ts +269 -0
- package/src/game-dev-tools.ts +7 -14
- package/src/game-frame-loop.ts +45 -82
- package/src/game-startup.ts +145 -70
- package/src/game-ui.ts +84 -0
- package/src/game.ts +168 -552
- package/src/gamepad-mappings.ts +269 -0
- package/src/generated/console-markers.ts +14 -0
- package/src/geometry-capture.ts +28 -4
- package/src/gpu-readings.ts +98 -0
- package/src/gpu-scene-bvh.ts +149 -36
- package/src/grass-field.ts +628 -0
- package/src/hot.ts +4 -7
- package/src/index.ts +227 -8
- package/src/input.ts +237 -25
- package/src/instanced-batch-lod.ts +3 -8
- package/src/interpolation.ts +171 -40
- package/src/look/ao-admission.ts +4 -3
- package/src/look/auto-exposure.ts +5 -16
- package/src/look/default-tone-mapping.ts +41 -5
- package/src/look/local-exposure.ts +2 -7
- package/src/look/quad-pass.ts +21 -0
- package/src/look/quality.ts +4 -0
- package/src/look/unreal-bloom.ts +4 -13
- package/src/look/world-environment.ts +58 -115
- package/src/merge-parts.ts +20 -24
- package/src/model-lod.ts +97 -14
- package/src/particle-significance.ts +12 -0
- package/src/particles.ts +19 -10
- package/src/platform.ts +23 -4
- package/src/profiling/FrameStages.ts +5 -6
- package/src/profiling/Spans.ts +3 -17
- package/src/profiling/debug-telemetry.ts +2 -6
- package/src/profiling/render-list-validate.ts +6 -15
- package/src/projection-marker.ts +2 -1
- package/src/quiet-markers.ts +3 -10
- package/src/render/cpu-bvh.ts +100 -0
- package/src/render/depth-pyramid.ts +6 -14
- package/src/render/environment/environmentContribution.ts +202 -0
- package/src/render/environment/environmentRadiance.ts +44 -0
- package/src/render/environment/environmentSampleCache.ts +56 -0
- package/src/render/environment/environmentSampling.ts +201 -0
- package/src/render/environment/environmentSnapshot.ts +71 -0
- package/src/render/environment/gate.ts +57 -0
- package/src/render/material-key.ts +21 -1
- package/src/render/mesh-pool.ts +3 -19
- package/src/render/probe-trace.ts +872 -0
- package/src/render/probe-volume.ts +780 -34
- package/src/render/radiance-cache.ts +17 -0
- package/src/render/screen-probe-gather.ts +303 -0
- package/src/render/short-range-ao.ts +274 -0
- package/src/render/virtual-shadow-partial.ts +13 -0
- package/src/render/virtual-shadow.ts +18 -16
- package/src/render/world-impostor-surface.ts +207 -9
- package/src/render/world-impostor.ts +5 -2
- package/src/render-camera-cull.ts +105 -4
- package/src/render-environment.ts +41 -0
- package/src/renderer-config.ts +36 -0
- package/src/renderer-facts.ts +37 -0
- package/src/renderer.ts +78 -32
- package/src/resolution-scaler.ts +3 -2
- package/src/scatter-field.ts +496 -0
- package/src/scene-entry-inspectors.ts +61 -0
- package/src/snow-field.ts +1 -0
- package/src/startup-offscreen-bytes.ts +84 -0
- package/src/state.ts +16 -3
- package/src/static-transform.ts +100 -25
- package/src/streamed-textures.ts +112 -0
- package/src/streaming.ts +68 -4
- package/src/texture-streaming.ts +331 -0
- package/src/tile-ring.ts +294 -0
- package/src/version.ts +1 -1
- package/src/warmup.ts +15 -2
- package/src/worker.ts +12 -2
- package/src/world-bundle-safety.ts +55 -10
- package/src/world-cell-batches.ts +166 -200
- package/src/world-cell-chunks.ts +3 -7
- package/src/world-cell-data.ts +7 -0
- package/src/world-cell-impostors.ts +20 -8
- package/src/world-cell-models.ts +36 -8
- package/src/world-cell-options.ts +2 -14
- package/src/world-cell-placements.ts +194 -90
- package/src/world-cell-prewarm.ts +39 -4
- package/src/world-cell-records.ts +401 -0
- package/src/world-cell-render-bundles.ts +2 -2
- package/src/world-cell-render-gpu-dress.ts +17 -19
- package/src/world-cell-render-main-cull.ts +73 -17
- package/src/world-cell-render-util.ts +18 -5
- package/src/world-cell-render.ts +13 -5
- package/src/world-cell-residency.ts +15 -6
- package/src/world-cell-stale.ts +238 -0
- package/src/world-cells.ts +23 -6
- package/src/world-gpu-flags.ts +18 -50
- package/src/world-gpu-reference.ts +22 -8
- package/src/world-gpu-scene.ts +44 -24
- package/src/world-gpu-shadow.ts +21 -8
- package/src/world-gpu-types.ts +41 -13
- package/src/world-load-limiter.ts +5 -0
- package/src/world-model-sections.ts +80 -0
- package/src/world-river-ribbon.ts +273 -0
- package/src/world-root-frame.ts +39 -0
- package/src/world-shore-field.ts +91 -0
- package/src/world-static-pose.ts +163 -0
- package/src/world-surface-sampler.ts +48 -0
- package/src/world-terrain-splat.ts +10 -18
- package/src/world-tile-budget.ts +4 -11
- package/src/world-tiles.ts +79 -12
- package/src/world-validate.ts +6 -14
- package/src/world-warm.ts +51 -0
- package/src/world-water-bodies.ts +113 -3
- package/src/world.ts +13 -0
package/src/index.ts
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The version this library reports.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
4
|
+
* `version.ts` is the one owner, generated from `package.json` at build time. Declared here rather
|
|
5
|
+
* than re-exported under another name: the native engine's bundler reads this barrel for the
|
|
6
|
+
* bindings a game may import, and `export { CORE_VERSION as version } from …` gave it a name the
|
|
7
|
+
* module does not export, refusing every game that stamps the version into its HUD
|
|
8
|
+
* (`TN_NATIVE_ENGINE_UNBOUND`).
|
|
8
9
|
*/
|
|
9
|
-
|
|
10
|
+
import { CORE_VERSION } from "./version.js";
|
|
11
|
+
|
|
12
|
+
export const version = CORE_VERSION;
|
|
10
13
|
|
|
11
14
|
/**
|
|
12
15
|
* Play a skinned or sprite animation from game code.
|
|
@@ -144,16 +147,48 @@ export type { CameraShakeCurve, ICameraShakeOffset, ICameraShakeOptions } from "
|
|
|
144
147
|
* @situation free the disk cache from a settings menu
|
|
145
148
|
* @situation prefetch assets into the Cache Storage disk cache of a large web game
|
|
146
149
|
* @situation load assets from a nonstandard base path or a compiled asset manifest
|
|
150
|
+
* @situation stream a large game: boot on the spawn bytes and prefetch the rest
|
|
151
|
+
* @situation make the first scene play before the whole game finishes downloading
|
|
152
|
+
* @situation draw a heavy model's coarsest level first and its full detail when the file lands
|
|
153
|
+
* @situation draw a model's textures at their resident mips first and the whole files later
|
|
147
154
|
* @alias different area props
|
|
155
|
+
* @situation coarse first model streaming
|
|
156
|
+
* @situation streamMeshes and streamTextures: stream the meshes and textures of a model
|
|
157
|
+
* @situation mip streaming textures
|
|
158
|
+
* @situation TN_STREAMING_POOL
|
|
159
|
+
* @situation TN_ASSET_LATE
|
|
148
160
|
* @alias first playable screen external assets
|
|
161
|
+
* @situation an asset pops in after the reveal and the game needs to count it
|
|
162
|
+
* @situation a model texture looks blurry or low resolution right after load, then sharpens
|
|
163
|
+
* @situation build a collider or navmesh from a streamed model only once its full file landed
|
|
149
164
|
* @constraint reuse the loader handed to scenes as `ctx.assets` instead of building parallel caches
|
|
150
165
|
* @constraint await everything the spawn camera sees before the reveal; `ctx.assets.prefetch` and the background fill are for content out of view, or the player spawns into a half-built world
|
|
166
|
+
* @constraint a whole-file load requested after the reveal that the game had not `prefetch`ed logs one `TN_ASSET_LATE` line with its bytes, so a pop-in is countable from a playtest
|
|
151
167
|
* @constraint web only: a native host reads installed files, so `ctx.assets.cache` reports `enabled: false` with the reason and `prefetch` resolves at once
|
|
168
|
+
* @constraint streaming is engine-owned and on by default: a cooked LOD-chained model loads its `.coarse.<digest>.glb` companion first, then the full file at "soon" priority, and the full geometry replaces the coarse in place (clones and the projection mirror included); a failed coarse load falls back to the whole file and logs `TN_ASSETS_STREAM_FAILED`
|
|
169
|
+
* @constraint texture streaming rides on the coarse parse: each shared `.ktx2` of that model is read by `Range` as its resident mips (the header and the tail), and the whole files replace them when the full model lands; a host without `Range` sends the whole file and keeps it whole. `TN_STREAMING_POOL` reports `files`, `residentBytes`, `fullBytes`, `deferredBytes` and `upgraded` once, two seconds after the last change
|
|
152
170
|
* @override `assets.cache: false` turns the disk cache off and `assets.backgroundFill: false` turns the post-reveal fill off; both are reported on `ctx.assets.cache`
|
|
171
|
+
* @constraint the whole texture keeps what the game set on the resident one (`anisotropy`, wrap, filters, offset, repeat, `userData`), so the swap changes the mips and nothing else
|
|
172
|
+
* @override `ctx.assets.model(path, { whole: true })` resolves only once the full file has replaced the coarse companion, for a collider or navmesh that copies vertices once
|
|
173
|
+
* @override `assets.streamMeshes: false` loads every model whole (reported once as `TN_ASSETS_STREAM_MESHES_OFF`); `assets.streamTextures: false` loads every model texture whole (`TN_ASSETS_STREAM_TEXTURES_OFF`)
|
|
174
|
+
* @situation compressed texture upload on the owned engine (KTX2 to BC7 or ETC2 on the GPU)
|
|
175
|
+
* @situation load a model with KHR_texture_basisu or EXT_meshopt_compression on the owned engine
|
|
176
|
+
* @situation stream a finer mip level into a CompressedTexture that already draws
|
|
177
|
+
* @situation KTX2Loader on the owned engine
|
|
178
|
+
* @situation CompressedTexture upload
|
|
179
|
+
* @situation TN_TEXTURE_TRANSCODE_TARGET
|
|
180
|
+
* @situation TN_NATIVE_TEXTURE_UNSUPPORTED
|
|
181
|
+
* @situation webRuntimeDecoders meshopt ktx2
|
|
182
|
+
* @constraint every web build cooks meshopt geometry and KTX2 textures for both engines (`webRuntimeDecoders` in create-threenative answers `{ ktx2: true, meshopt: true }`); the owned engine's glTF loader decodes both itself, with no JS decoder
|
|
183
|
+
* @constraint the owned engine transcodes a KTX2 image to BC7 on a device with `texture-compression-bc`, else ETC2, else RGBA8 with an engine mip chain, and prints `TN_TEXTURE_TRANSCODE_TARGET <target>` once; a block format needs a width and height that are multiples of 4, so any other size stays RGBA8 and the same line names it
|
|
184
|
+
* @constraint a three `CompressedTexture` (format plus `mipmaps`) uploads one GPU write per level; a block format the device lacks throws `TN_NATIVE_TEXTURE_UNSUPPORTED` by name instead of drawing garbage
|
|
185
|
+
* @constraint levels are coarse-first: a level whose `mipmaps[i].data` is null is not resident and the texture samples its finest resident level; set `mipmaps[i].data` and `needsUpdate = true` to write that one finer level in place, without re-creating the texture or rewriting the other levels
|
|
186
|
+
* @override `engine: "threejs"` runs three's own `KTX2Loader` and `MeshoptDecoder` in JS instead of the owned engine's decoders
|
|
153
187
|
* @example const assets = createAssetLoader({ basePath: "/assets" });
|
|
154
188
|
* const rock = await assets.texture("rock.png");
|
|
155
189
|
*/
|
|
156
|
-
export { createAssetLoader } from "./assets.js";
|
|
190
|
+
export { ASSET_LATE_MARKER, createAssetLoader } from "./assets.js";
|
|
191
|
+
export { fetchAsset } from "./assets.js";
|
|
157
192
|
export { onLaunchFailure } from "./launch-diagnostics.js";
|
|
158
193
|
export { resetAudioCueLedger } from "./audio.js";
|
|
159
194
|
export type { ILaunchFailure, LaunchFailureKind } from "./launch-diagnostics.js";
|
|
@@ -325,6 +360,60 @@ export type {
|
|
|
325
360
|
ITracedRay,
|
|
326
361
|
ITracedReflectionsOptions,
|
|
327
362
|
} from "./render/traced-reflections.js";
|
|
363
|
+
/**
|
|
364
|
+
* Lumen's Screen Probe Gather: one probe per 16 x 16 pixels traces an 8 x 8 octahedron of rays, the probes are filtered
|
|
365
|
+
* into an irradiance octahedron each, and a pixel blends the four nearest probes it can see, instead of every pixel
|
|
366
|
+
* tracing its own rays. A ray that hits on screen returns the lit frame minus the cache along it; a ray that leaves the
|
|
367
|
+
* screen continues through the packed scene up to the radiance cache's cell and reads the cache where it ended, so the
|
|
368
|
+
* light that arrives from off screen is that direction's and not the pixel's mean.
|
|
369
|
+
* @situation bounce light that reads the room off screen instead of a flat ambient term
|
|
370
|
+
* @situation global illumination that costs a fraction of one ray per pixel
|
|
371
|
+
* @situation the light a corner sees from around the wall, which a per-pixel screen trace loses
|
|
372
|
+
* @situation lumen screen probe gather
|
|
373
|
+
* @situation lumen final gather
|
|
374
|
+
* @constraint the owned engine only: on engine: "threejs" the upstream node takes the camera as its fourth argument and has no probes, and gather() refuses
|
|
375
|
+
* @constraint the gather is a delta in E / pi: multiply it by the receiver's diffuse colour (mrt({ diffuseColor })) and add it after the scene pass, and give the scene pass no other indirect diffuse or the light is counted twice
|
|
376
|
+
* @constraint a viewport resize needs a new gather: the probe grid is fixed when it is built
|
|
377
|
+
* @constraint the grid is the cost: downsampleFactor 16 and an 8 x 8 octahedron are Unreal's Epic, 32 and 8 its High
|
|
378
|
+
* @constraint radiance answers in the frame's units (the cache read times the frame's gain), and a trace reads it only where the screen has nothing
|
|
379
|
+
* @override downsampleFactor, tracingOctahedronResolution, cacheCellSize, timedPass and the strength of the composite are game-owned choices
|
|
380
|
+
* @example
|
|
381
|
+
* const gather = new ScreenProbeGather({ camera, viewport, radiance, trace });
|
|
382
|
+
* const gi = gather.gather(convertToTexture(input), depth(), normalView());
|
|
383
|
+
* const bounce = gather.getGINode().rgb.mul(diffuseColor.rgb);
|
|
384
|
+
*/
|
|
385
|
+
export { ScreenProbeGather } from "./render/screen-probe-gather.js";
|
|
386
|
+
export type {
|
|
387
|
+
IScreenProbeCamera,
|
|
388
|
+
IScreenProbeGatherOptions,
|
|
389
|
+
IScreenProbeGatherReport,
|
|
390
|
+
ScreenProbePass,
|
|
391
|
+
} from "./render/screen-probe-gather.js";
|
|
392
|
+
/**
|
|
393
|
+
* Unreal's Short Range AO: a horizon search of 2 sweeps around the view normal, 3 samples each at the squared fraction
|
|
394
|
+
* of a 32 px screen reach, at full resolution, with a bent normal at Epic. It is the occlusion that runs *with* dynamic
|
|
395
|
+
* global illumination — the contact detail Lumen keeps after the screen probe gather has already answered the wide
|
|
396
|
+
* occlusion — so a gathered frame is not darkened twice by two wide treatments. The result is one texture: `rgb` the
|
|
397
|
+
* bent normal in view space, `a` the share of the hemisphere left open, which multiplies indirect light only.
|
|
398
|
+
* @situation contact shadow at the foot of an object while dynamic GI runs
|
|
399
|
+
* @situation dark line where a wall meets the floor, without a second wide AO over the gathered light
|
|
400
|
+
* @situation lumen short range ao
|
|
401
|
+
* @constraint it replaces GTAO when dynamic GI runs; a tier without GI keeps ambientOcclusion
|
|
402
|
+
* @constraint the occlusion multiplies indirect light only: direct light and emission keep their own occlusion
|
|
403
|
+
* @constraint multi-bounce and its albedo cap belong to the game's composite; Unreal caps the albedo at 0.5
|
|
404
|
+
* @constraint an authored stage that carries its name must anchor itself (`before: "ssgi"`), because the chain's built-in order names no shortRangeAO
|
|
405
|
+
* @override horizonSearchSliceCount, horizonSearchStepCount, reachPx, bentNormal and intensity are game-owned choices
|
|
406
|
+
* @example
|
|
407
|
+
* const shortRange = new ShortRangeAO({ camera, viewport: renderer.drawingBufferSize });
|
|
408
|
+
* const contact = shortRange.occlusion(depth(), normalView());
|
|
409
|
+
* const indirect = input.rgb.mul(contact.a);
|
|
410
|
+
*/
|
|
411
|
+
export { ShortRangeAO } from "./render/short-range-ao.js";
|
|
412
|
+
export type {
|
|
413
|
+
IShortRangeAOCamera,
|
|
414
|
+
IShortRangeAOOptions,
|
|
415
|
+
IShortRangeAOReport,
|
|
416
|
+
} from "./render/short-range-ao.js";
|
|
328
417
|
/**
|
|
329
418
|
* Collapse many copies of one game-authored shape into a single draw, without counting them first.
|
|
330
419
|
*
|
|
@@ -414,13 +503,22 @@ export { mergeByMaterial } from "./merge-parts.js";
|
|
|
414
503
|
export type { IMergeByMaterialOptions } from "./merge-parts.js";
|
|
415
504
|
/**
|
|
416
505
|
* Read a debug switch from the URL, or from `TN_DEBUG_*` in the environment on a native launch.
|
|
417
|
-
* @situation read a debug toggle from the URL
|
|
506
|
+
* @situation read a debug toggle from the URL, an environment variable or a harness global
|
|
418
507
|
* @constraint a name in camelCase becomes UPPER_SNAKE: `debugFlag("freeCam")` reads `?freeCam` or `TN_DEBUG_FREE_CAM`
|
|
419
508
|
* @constraint `0` and `false` are off, so a saved URL cannot turn a switch back on
|
|
420
509
|
* @example import { debugFlag } from "@threenative/core";
|
|
421
510
|
* if (debugFlag("freeCam")) camera.flyMode = true;
|
|
422
511
|
*/
|
|
423
512
|
export { debugFlag } from "./debug.js";
|
|
513
|
+
/**
|
|
514
|
+
* Read the text a debug switch was given by the launch, on the same rule as `debugFlag`.
|
|
515
|
+
* @situation read a debug override whose value is not a boolean
|
|
516
|
+
* @situation override a quality tier or a mode for one run without changing the code
|
|
517
|
+
* @constraint the same name rule as `debugFlag`: `?quality=` on the web, `TN_DEBUG_QUALITY` on a native launch
|
|
518
|
+
* @example import { debugValue } from "@threenative/core";
|
|
519
|
+
* const tier = debugValue("quality");
|
|
520
|
+
*/
|
|
521
|
+
export { debugValue } from "./debug.js";
|
|
424
522
|
/**
|
|
425
523
|
* Publish one game object under `__THREENATIVE__.debug` for a capture script or the console.
|
|
426
524
|
* @situation expose a game object to a capture script or the console in dev builds
|
|
@@ -430,6 +528,20 @@ export { debugFlag } from "./debug.js";
|
|
|
430
528
|
* // then from the console: __THREENATIVE__.debug.player
|
|
431
529
|
*/
|
|
432
530
|
export { exposeDebug } from "./debug.js";
|
|
531
|
+
/**
|
|
532
|
+
* The one name every dev surface publishes under, and the reader/writer for it.
|
|
533
|
+
* @situation read or extend the `__THREENATIVE__` object a dev launch publishes
|
|
534
|
+
* @constraint every dev surface publishes under this key; the worker's typed mirror tuple names it too
|
|
535
|
+
* @example import { DEV_GLOBAL_KEY, devGlobal } from "@threenative/core";
|
|
536
|
+
* const tools = devGlobal(globalThis);
|
|
537
|
+
*/
|
|
538
|
+
export {
|
|
539
|
+
DEV_GLOBAL_KEY,
|
|
540
|
+
type DevGlobal,
|
|
541
|
+
type IDevTools,
|
|
542
|
+
devGlobal,
|
|
543
|
+
publishDevGlobal,
|
|
544
|
+
} from "./dev-global.js";
|
|
433
545
|
/**
|
|
434
546
|
* Draw a model too detailed for the screen to resolve, without submitting the part it cannot.
|
|
435
547
|
*
|
|
@@ -536,6 +648,19 @@ export {
|
|
|
536
648
|
* @example const geometry = baseGeometryOf(mesh);
|
|
537
649
|
*/
|
|
538
650
|
export { baseGeometryOf } from "./model-lod.js";
|
|
651
|
+
/**
|
|
652
|
+
* True while a geometry is the coarse companion a streamed model draws first (PRD-860), before its
|
|
653
|
+
* full file replaces it in place. A caller that copies vertices (a trimesh collider, a navmesh bake,
|
|
654
|
+
* a merge) waits with `ctx.assets.model(path, { whole: true })` instead of copying the coarse ones.
|
|
655
|
+
*
|
|
656
|
+
* @situation collider or navmesh built from a model is coarser than what is drawn
|
|
657
|
+
* @situation wait for the full model before copying its vertices
|
|
658
|
+
* @situation whole model before collision
|
|
659
|
+
* @situation TN_COLLIDER_COARSE
|
|
660
|
+
* @constraint `CollisionShape3D.fromMesh` with "trimesh" or "convexHull" on a streamed geometry warns `TN_COLLIDER_COARSE` naming the mesh and the `{ whole: true }` override, and still builds
|
|
661
|
+
* @example const coarse = isStreamedGeometry(mesh.geometry);
|
|
662
|
+
*/
|
|
663
|
+
export { isStreamedGeometry } from "./model-lod.js";
|
|
539
664
|
/**
|
|
540
665
|
* The cooked automatic LOD chain (`TN_discrete_lod`) a loaded geometry carries, or `undefined`.
|
|
541
666
|
*
|
|
@@ -1041,6 +1166,26 @@ export {
|
|
|
1041
1166
|
PROBE_VOLUME_MARKER,
|
|
1042
1167
|
ProbeVolume,
|
|
1043
1168
|
} from "./render/probe-volume.js";
|
|
1169
|
+
/**
|
|
1170
|
+
* A probe field of diffuse irradiance that refreshes by tracing the packed scene, with no scene draw: the
|
|
1171
|
+
* radiance cache of a dynamic global-illumination pass. Probes in view refresh first, oldest first, within
|
|
1172
|
+
* `numProbesToTraceBudget` a frame; a lamp toggled in game code or a sun that steps more than one degree
|
|
1173
|
+
* re-traces them while the old values keep lighting the frame.
|
|
1174
|
+
* @situation light follows a lamp that switches on and off in a room
|
|
1175
|
+
* @situation bounce light that updates when the sun moves, with no baked lightmap
|
|
1176
|
+
* @situation global illumination that refreshes fast enough to read as dynamic
|
|
1177
|
+
* @alias lumen radiance cache
|
|
1178
|
+
* @alias radiance cache
|
|
1179
|
+
* @alias irradiance field
|
|
1180
|
+
* @alias dynamic probe gi
|
|
1181
|
+
* @constraint build a GPUSceneBVH of the static meshes first and pass it as trace.bvh; the cache reads colour and emissive from each material, a texture or a node is counted as ignored
|
|
1182
|
+
* @constraint add the cache with ctx.add() so its refresh is measured in the render phase, and read it with sampleNode(position, normal) from a game-owned material
|
|
1183
|
+
* @constraint a one-sided material is not seen from behind, as a cube capture would not draw it
|
|
1184
|
+
* @override numProbesToTraceBudget (100), probeResolution (8, so 64 rays a probe; 32 for a small emitter), bounds, density, bounces and the sun and sky values are game-owned
|
|
1185
|
+
* @example const bvh = new GPUSceneBVH(ctx.scene); ctx.add(bvh); const cache = new RadianceCache({ bounds, density: 0.5, trace: { bvh, sun, sky, camera: ctx.camera } }); ctx.add(cache);
|
|
1186
|
+
*/
|
|
1187
|
+
export { RadianceCache } from "./render/radiance-cache.js";
|
|
1188
|
+
export type { IRadianceCacheOptions } from "./render/radiance-cache.js";
|
|
1044
1189
|
/**
|
|
1045
1190
|
* The Surface Cache: what a traced global-illumination ray reads where it hits a surface. A material atlas
|
|
1046
1191
|
* (base colour and emissive maps reduced to small tiles) answers the albedo and the glow at the hit UV; a flat
|
|
@@ -1395,6 +1540,55 @@ export type {
|
|
|
1395
1540
|
*/
|
|
1396
1541
|
export { GPUReadback } from "./gpu-readback.js";
|
|
1397
1542
|
export type { IGPUReadbackOptions, IGPUReadbackSample } from "./gpu-readback.js";
|
|
1543
|
+
/**
|
|
1544
|
+
* Stream instanced grass in chunks around the camera; the game owns the blade and its TSL material.
|
|
1545
|
+
* @situation grass that sways and parts around the player
|
|
1546
|
+
* @situation a meadow, lawn or grassy field over terrain that streams around the camera
|
|
1547
|
+
* @situation ground cover grass blades with distance thinning and LOD that does not pop
|
|
1548
|
+
* @situation grass flattened or pushed aside where the player, a creature or a vehicle walks
|
|
1549
|
+
* @situation grow grass on a terrain biome's grass rows with grassFieldFromBiome
|
|
1550
|
+
* @constraint call `update(camera)` once per rendered frame from `ctx.beforeRender`; chunks build nearest first inside `buildBudgetMs`
|
|
1551
|
+
* @constraint the material reads `GRASS_FIELD_ATTRIBUTES` and the field's `nodes` uniforms, so its thinning matches the CPU trim
|
|
1552
|
+
* @constraint a chunk is built inside 1.3 × the draw distance and discarded past 1.4 ×, so a camera on the edge rebuilds nothing
|
|
1553
|
+
* @override densityScale and cullDistanceScale scale every density and distance at once; prewarm() builds all in range on the next update
|
|
1554
|
+
* @example // the look lives in the kit's src/render/grass.ts
|
|
1555
|
+
* const grass = new GrassField3D({ blade: grassBlade(), material: grassMaterial, getHeight: height });
|
|
1556
|
+
* ctx.add(grass);
|
|
1557
|
+
* ctx.beforeRender(() => { grass.pushers[0]?.set(hero.x, hero.y, hero.z, 1.2); grass.update(ctx.camera); });
|
|
1558
|
+
*/
|
|
1559
|
+
export { GRASS_FIELD_ATTRIBUTES, GrassField3D } from "./grass-field.js";
|
|
1560
|
+
export type {
|
|
1561
|
+
IGrassField3DOptions,
|
|
1562
|
+
IGrassFieldBlade,
|
|
1563
|
+
IGrassFieldBounds,
|
|
1564
|
+
IGrassFieldNodes,
|
|
1565
|
+
IGrassFieldStats,
|
|
1566
|
+
} from "./grass-field.js";
|
|
1567
|
+
|
|
1568
|
+
/**
|
|
1569
|
+
* Stream instanced copies of any baked mesh around a follow point, with distance thinning and levels
|
|
1570
|
+
* of detail, from the game's own placement rule.
|
|
1571
|
+
* @situation scatter fallen logs, twigs, leaf litter, stones and ferns over a forest floor
|
|
1572
|
+
* @situation stream instanced props of any baked mesh round the player without one draw per prop
|
|
1573
|
+
* @situation place rocks, debris or plants on a heightfield with distance thinning and level of detail
|
|
1574
|
+
* @constraint call `update(follow)` once per rendered frame
|
|
1575
|
+
* @constraint `place` runs once per candidate per tile build: return false for paths and clearings
|
|
1576
|
+
* @constraint rotating or scaling the field is not supported; translating it is
|
|
1577
|
+
* @requires npm i -D @threenative/procedural-vegetation for the bake these instances come from
|
|
1578
|
+
* @example
|
|
1579
|
+
* const floor = new ScatterField3D({ parts: [{ lods, material }], getHeight, density: 0.05, place });
|
|
1580
|
+
* ctx.add(floor);
|
|
1581
|
+
* ctx.beforeRender(() => floor.update(hero.position));
|
|
1582
|
+
*/
|
|
1583
|
+
export { ScatterField3D } from "./scatter-field.js";
|
|
1584
|
+
export type {
|
|
1585
|
+
IScatterField3DOptions,
|
|
1586
|
+
IScatterFieldBounds,
|
|
1587
|
+
IScatterFieldStats,
|
|
1588
|
+
IScatterPart,
|
|
1589
|
+
IScatterPlacement,
|
|
1590
|
+
IScatterPoint,
|
|
1591
|
+
} from "./scatter-field.js";
|
|
1398
1592
|
/**
|
|
1399
1593
|
* Dispatch a game-owned particle surface and process function through a pooled system.
|
|
1400
1594
|
* @situation emit sparks, smoke, or other transient effects
|
|
@@ -1657,9 +1851,19 @@ export type {
|
|
|
1657
1851
|
* @constraint image ray tracing is unavailable on native until buffer-to-texture copy-out interop exists; `mystralRT.traceRays` refuses instead of resolving success without a readable result
|
|
1658
1852
|
* @constraint a native desktop host with ray tracing hardware traces ray batches with `mystralRT.traceRayBatch`, which writes hit records into a typed array you own; read `mystralRT.capabilities().rayBatch` first, and keep the software BVH trace for the web and every other host
|
|
1659
1853
|
* @constraint when `mystralRT.capabilities().sharedTransport` is true, `mystralRT.traceRayBatchGpu({ tlas, rays, hits, rayCount })` traces between two GPUBuffers with no copy through CPU memory; `rays` needs the CopySrc usage and `hits` the CopyDst usage, and each call costs CPU time, so measure it against the software trace for your batch size
|
|
1854
|
+
* @situation show gamepad prompts and bind pad buttons on a games console such as the PS4
|
|
1660
1855
|
* @example if (isMobile()) showTouchControls();
|
|
1856
|
+
* @example if (isConsole()) showPadPrompts(isPs4() ? "dualshock" : "generic");
|
|
1661
1857
|
*/
|
|
1662
|
-
export {
|
|
1858
|
+
export {
|
|
1859
|
+
getPlatform,
|
|
1860
|
+
isConsole,
|
|
1861
|
+
isMobile,
|
|
1862
|
+
isNative,
|
|
1863
|
+
isPs4,
|
|
1864
|
+
isTouchscreenAvailable,
|
|
1865
|
+
isWeb,
|
|
1866
|
+
} from "./platform.js";
|
|
1663
1867
|
export type {
|
|
1664
1868
|
IPlatformInfo,
|
|
1665
1869
|
PlatformFormFactor,
|
|
@@ -1896,6 +2100,7 @@ export type {
|
|
|
1896
2100
|
ContextMenuPolicy,
|
|
1897
2101
|
IInputAction,
|
|
1898
2102
|
IInputGamepad,
|
|
2103
|
+
IInputMapOptions,
|
|
1899
2104
|
InputBindings,
|
|
1900
2105
|
InputPlatformSource,
|
|
1901
2106
|
IRawInputPointer,
|
|
@@ -1913,8 +2118,22 @@ export type {
|
|
|
1913
2118
|
* @situation map WASD keys to a movement axis instead of reading the held key set in the update loop
|
|
1914
2119
|
* @situation read a jump, a fire or a reload as one named action bound to key, gamepad button and mouse button together
|
|
1915
2120
|
* @situation read mouse look, wheel zoom or a two-finger pinch as an axis the frame loop already ticks
|
|
2121
|
+
* @situation support an Xbox pad, a generic XInput clone, an 8BitDo or a Steam Deck controller
|
|
2122
|
+
* @situation the character drifts while the controller stick is idle
|
|
2123
|
+
* @situation the controller does nothing in Firefox on Linux
|
|
2124
|
+
* @situation a second controller or a wheel steals the input from the pad the player holds
|
|
2125
|
+
* @alias gamepad
|
|
2126
|
+
* @alias controller
|
|
2127
|
+
* @alias joypad
|
|
2128
|
+
* @alias xbox
|
|
2129
|
+
* @alias 8bitdo
|
|
2130
|
+
* @alias steam deck
|
|
1916
2131
|
* @constraint `buttons` is the gamepad and `mouseButtons` the mouse; `up`/`down`/`left`/`right` are the directions of `vector(name)`, not the keys that press it
|
|
1917
2132
|
* @constraint scroll, pinch and pointer-relative sources are declared on the binding and read through `axis(name)`; a game adds no window listener of its own
|
|
2133
|
+
* @constraint gamepad buttons are W3C standard indices on every pad: 0 south (A/Cross), 1 east, 2 west, 3 north, 4/5 shoulders, 6/7 triggers, 8 select, 9 start, 10/11 stick clicks; axes 0..3 are the sticks
|
|
2134
|
+
* @constraint both sticks carry a radial dead zone, `0.2` by default, reported per connected pad as `TN_GAMEPAD`; a pad the browser reports unmapped and the table does not know is ignored, never read with raw indices
|
|
2135
|
+
* @constraint a pad claims the input when a button goes down or a stick travels past half tilt, and keeps it while idle so its releases read; a stick resting past the dead zone or jittering across it claims nothing, so an idle pad in the first slot cannot steal input
|
|
2136
|
+
* @override defineGame({ gamepadDeadZone: 0 }) publishes raw axes
|
|
1918
2137
|
* @example const game = defineGame({ input: { move: { up: ["KeyW"], down: ["KeyS"], left: ["KeyA"], right: ["KeyD"] } }, scenes: { Play } });
|
|
1919
2138
|
* // inside the scene, per frame: ctx.input.axis("move") is 0 at rest and 1 at full tilt
|
|
1920
2139
|
*/
|
package/src/input.ts
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
import { Vector2 } from "three";
|
|
2
|
+
import {
|
|
3
|
+
type GamepadNormalizer,
|
|
4
|
+
type IStandardPad,
|
|
5
|
+
createStandardPad,
|
|
6
|
+
toStandardPad,
|
|
7
|
+
} from "./gamepad-mappings.js";
|
|
2
8
|
|
|
3
9
|
/**
|
|
4
10
|
* One action, read either as a button through `pressed`/`justPressed`, a 2D axis through
|
|
@@ -81,10 +87,27 @@ function mouseButtonMask(button: number): number {
|
|
|
81
87
|
export interface IInputGamepad {
|
|
82
88
|
readonly axes: ArrayLike<number>;
|
|
83
89
|
readonly buttons: readonly { readonly pressed: boolean }[];
|
|
90
|
+
/** The browser's device name, which carries the vendor:product an unmapped pad is looked up by. */
|
|
91
|
+
readonly id?: string;
|
|
92
|
+
/**
|
|
93
|
+
* `"standard"` when the pad already uses the W3C standard layout, and `""` when the browser does
|
|
94
|
+
* not know the device. A source with no `mapping` at all is standard by construction: the owned
|
|
95
|
+
* native host builds standard pads, and so does a fixture.
|
|
96
|
+
*/
|
|
97
|
+
readonly mapping?: string;
|
|
84
98
|
}
|
|
85
99
|
|
|
86
100
|
export type InputPlatformSource = () => readonly (IInputGamepad | null)[];
|
|
87
101
|
|
|
102
|
+
export interface IInputMapOptions {
|
|
103
|
+
/**
|
|
104
|
+
* Radial dead zone for both sticks, `0`..`1`. Default `0.2`, the stock Enhanced Input dead zone
|
|
105
|
+
* (`UInputModifierDeadZone`, `LowerThreshold = 0.2`, `EDeadZoneType::Radial`). A stick inside it
|
|
106
|
+
* reads zero, one outside it is rescaled so full tilt is still `1`. `0` publishes raw axes.
|
|
107
|
+
*/
|
|
108
|
+
readonly gamepadDeadZone?: number;
|
|
109
|
+
}
|
|
110
|
+
|
|
88
111
|
export interface IRawInputPointer {
|
|
89
112
|
readonly id: number;
|
|
90
113
|
buttons: number;
|
|
@@ -158,6 +181,41 @@ function pointerLockDocument(): PointerLockDocument | undefined {
|
|
|
158
181
|
const browserGamepads: InputPlatformSource = () =>
|
|
159
182
|
(globalThis.navigator as Navigator | undefined)?.getGamepads?.() ?? [];
|
|
160
183
|
|
|
184
|
+
const DEFAULT_GAMEPAD_DEAD_ZONE = 0.2;
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* How far past the dead zone a stick must travel to claim the input from another pad, on the
|
|
188
|
+
* rescaled axis: half travel. A worn stick jittering around the zone rescales to about `0.01` and
|
|
189
|
+
* never claims, while a deliberate move always does. A button press claims at any deflection.
|
|
190
|
+
*/
|
|
191
|
+
const GAMEPAD_CLAIM_STICK = 0.5;
|
|
192
|
+
|
|
193
|
+
/** Stable names for pads a fixture reports with no `id`, so reporting allocates nothing per tick. */
|
|
194
|
+
const PAD_SLOT_KEYS: readonly string[] = Array.from({ length: 16 }, (_, index) => `slot-${index}`);
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* The radial dead zone, in place. A stick inside `deadZone` reads zero; one outside is rescaled by
|
|
198
|
+
* `(magnitude - deadZone) / (1 - deadZone)` so the edge of the zone is still `0` and full tilt is
|
|
199
|
+
* still `1`, which is what makes a 0.6 stick read 0.5 rather than 0.4.
|
|
200
|
+
*/
|
|
201
|
+
function applyStickDeadZone(axes: number[], x: number, y: number, deadZone: number): void {
|
|
202
|
+
// `0` is the documented raw-axes override, so it must publish the stick untouched — the rescale
|
|
203
|
+
// below would still pull a corner in to the unit circle.
|
|
204
|
+
if (!(deadZone > 0)) return;
|
|
205
|
+
const zone = Math.min(deadZone, 1);
|
|
206
|
+
const stickX = axes[x] ?? 0;
|
|
207
|
+
const stickY = axes[y] ?? 0;
|
|
208
|
+
const magnitude = Math.sqrt(stickX * stickX + stickY * stickY);
|
|
209
|
+
if (magnitude <= zone || zone >= 1) {
|
|
210
|
+
axes[x] = 0;
|
|
211
|
+
axes[y] = 0;
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
const scale = Math.min(1, (magnitude - zone) / (1 - zone)) / magnitude;
|
|
215
|
+
axes[x] = stickX * scale;
|
|
216
|
+
axes[y] = stickY * scale;
|
|
217
|
+
}
|
|
218
|
+
|
|
161
219
|
/**
|
|
162
220
|
* Ask the browser to lock the pointer to `target`, the capture every first-person mouse look needs.
|
|
163
221
|
*
|
|
@@ -195,6 +253,20 @@ export class InputMap {
|
|
|
195
253
|
#pinchSample = 0;
|
|
196
254
|
#gamepadAxes: number[] = [];
|
|
197
255
|
#gamepadButtons: boolean[] = [];
|
|
256
|
+
/** The pad every read goes through: one reused buffer, filled once per read and never allocated. */
|
|
257
|
+
#padScratch: IStandardPad = createStandardPad();
|
|
258
|
+
/** Which source slot the player last used. It stays active until another pad reports input. */
|
|
259
|
+
#activePadSlot = -1;
|
|
260
|
+
#padSeen = new Set<string>();
|
|
261
|
+
#padReports = new Map<string, GamepadNormalizer>();
|
|
262
|
+
/** Each slot's pressed-button mask and stick travel last tick: a pad takes the slot on a claim. */
|
|
263
|
+
#padButtonMask: number[] = [];
|
|
264
|
+
#padStick: number[] = [];
|
|
265
|
+
/** Whether the current pad took the slot by claiming it, rather than by being the only pad there. */
|
|
266
|
+
#activePadClaimed = false;
|
|
267
|
+
/** The `TN_GAMEPAD` key per slot, and the `id` it was built from, so a tick allocates no string. */
|
|
268
|
+
#padKeys: Array<string | undefined> = [];
|
|
269
|
+
#padKeyIds: Array<string | undefined> = [];
|
|
198
270
|
#previousPressed = new Map<string, boolean>();
|
|
199
271
|
#justPressed = new Set<string>();
|
|
200
272
|
#justReleased = new Set<string>();
|
|
@@ -214,13 +286,28 @@ export class InputMap {
|
|
|
214
286
|
#tracksPinch = false;
|
|
215
287
|
#listeners: Array<[EventTarget, string, EventListener]> = [];
|
|
216
288
|
|
|
289
|
+
/**
|
|
290
|
+
* Radial dead zone for both sticks; `0` publishes the raw axes. Read on every tick, so a game may
|
|
291
|
+
* change it while running, and a value that is not a finite number from 0 through 1 reads as raw
|
|
292
|
+
* axes. `defineGame({ gamepadDeadZone })` sets the starting value and refuses one it cannot honour.
|
|
293
|
+
*/
|
|
294
|
+
gamepadDeadZone: number;
|
|
295
|
+
|
|
217
296
|
constructor(
|
|
218
297
|
bindings: InputBindings = DEFAULT_BINDINGS,
|
|
219
298
|
target: EventTarget = globalThis,
|
|
220
299
|
pointerTarget: EventTarget = target,
|
|
221
300
|
source: InputPlatformSource = browserGamepads,
|
|
222
301
|
contextMenu: ContextMenuPolicy = "suppress",
|
|
302
|
+
options: IInputMapOptions = {},
|
|
223
303
|
) {
|
|
304
|
+
const deadZone = options.gamepadDeadZone ?? DEFAULT_GAMEPAD_DEAD_ZONE;
|
|
305
|
+
if (!Number.isFinite(deadZone) || deadZone < 0 || deadZone > 1) {
|
|
306
|
+
throw new RangeError(
|
|
307
|
+
`gamepadDeadZone must be a number from 0 through 1, received ${deadZone}.`,
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
this.gamepadDeadZone = deadZone;
|
|
224
311
|
this.#bindings = { ...DEFAULT_BINDINGS, ...bindings };
|
|
225
312
|
// Bindings are fixed at construction; freezing the key list keeps tick() from calling
|
|
226
313
|
// Object.keys every step.
|
|
@@ -345,7 +432,11 @@ export class InputMap {
|
|
|
345
432
|
return Math.max(-1, Math.min(1, value));
|
|
346
433
|
}
|
|
347
434
|
|
|
348
|
-
/**
|
|
435
|
+
/**
|
|
436
|
+
* Request pointer capture explicitly from a named game gesture. Relative bindings request it on
|
|
437
|
+
* canvas click by default. A refused lock — an unfocused window, an untrusted gesture — leaves
|
|
438
|
+
* `raw.pointer.captured` false and warns once as `TN_POINTER_LOCK_REFUSED:`, never a rejection.
|
|
439
|
+
*/
|
|
349
440
|
captureMouse(): void {
|
|
350
441
|
if (this.raw.pointer.captured) return;
|
|
351
442
|
const result = captureMouse(this.#pointerTarget);
|
|
@@ -357,7 +448,9 @@ export class InputMap {
|
|
|
357
448
|
() => this.#syncCaptured(true),
|
|
358
449
|
(error: unknown) => {
|
|
359
450
|
this.raw.pointer.captured = false;
|
|
360
|
-
|
|
451
|
+
console.warn(
|
|
452
|
+
`TN_POINTER_LOCK_REFUSED: ${error instanceof Error ? error.message : String(error)}`,
|
|
453
|
+
);
|
|
361
454
|
},
|
|
362
455
|
);
|
|
363
456
|
}
|
|
@@ -426,29 +519,7 @@ export class InputMap {
|
|
|
426
519
|
this.#scrollSample = this.#clampAxis(this.#scrollDelta);
|
|
427
520
|
this.#scrollDelta = 0;
|
|
428
521
|
this.#samplePinch();
|
|
429
|
-
|
|
430
|
-
let gamepad: IInputGamepad | undefined;
|
|
431
|
-
for (let index = 0; index < sources.length; index += 1) {
|
|
432
|
-
const candidate = sources[index];
|
|
433
|
-
if (candidate !== null) {
|
|
434
|
-
gamepad = candidate;
|
|
435
|
-
break;
|
|
436
|
-
}
|
|
437
|
-
}
|
|
438
|
-
// Reused buffers: fresh arrays here were four allocations per update step, device or not.
|
|
439
|
-
this.#gamepadAxes.length = 0;
|
|
440
|
-
this.#gamepadButtons.length = 0;
|
|
441
|
-
if (gamepad?.axes) {
|
|
442
|
-
const axes = gamepad.axes;
|
|
443
|
-
for (let axis = 0; axis < axes.length; axis += 1)
|
|
444
|
-
this.#gamepadAxes.push(axes[axis] as number);
|
|
445
|
-
}
|
|
446
|
-
if (gamepad?.buttons) {
|
|
447
|
-
for (let index = 0; index < gamepad.buttons.length; index += 1)
|
|
448
|
-
this.#gamepadButtons.push(gamepad.buttons[index]?.pressed ?? false);
|
|
449
|
-
}
|
|
450
|
-
this.raw.gamepad.axes = this.#gamepadAxes;
|
|
451
|
-
this.raw.gamepad.buttons = this.#gamepadButtons;
|
|
522
|
+
this.#sampleGamepad();
|
|
452
523
|
this.#justPressed.clear();
|
|
453
524
|
this.#justReleased.clear();
|
|
454
525
|
for (let index = 0; index < this.#bindingNames.length; index += 1) {
|
|
@@ -486,6 +557,7 @@ export class InputMap {
|
|
|
486
557
|
this.#pinchPair = undefined;
|
|
487
558
|
this.#pinchDistance = 0;
|
|
488
559
|
this.#pinchSample = 0;
|
|
560
|
+
this.#activePadSlot = -1;
|
|
489
561
|
this.#previousPressed.clear();
|
|
490
562
|
this.#justPressed.clear();
|
|
491
563
|
this.#justReleased.clear();
|
|
@@ -505,6 +577,146 @@ export class InputMap {
|
|
|
505
577
|
this.clear();
|
|
506
578
|
}
|
|
507
579
|
|
|
580
|
+
/**
|
|
581
|
+
* Reads every pad once, normalizes each to the standard mapping, and publishes the one pad the
|
|
582
|
+
* player is holding. Reading the first non-null slot instead let a wheel or a paired-but-idle
|
|
583
|
+
* dongle at slot 0 swallow the pad in the player's hands.
|
|
584
|
+
*/
|
|
585
|
+
#sampleGamepad(): void {
|
|
586
|
+
const sources = this.#source();
|
|
587
|
+
this.#padSeen.clear();
|
|
588
|
+
let claimSlot = -1;
|
|
589
|
+
let inputSlot = -1;
|
|
590
|
+
let firstMapped = -1;
|
|
591
|
+
let activeStillMapped = false;
|
|
592
|
+
for (let index = 0; index < sources.length; index += 1) {
|
|
593
|
+
const pad = sources[index];
|
|
594
|
+
if (pad === null || pad === undefined) {
|
|
595
|
+
this.#forgetPad(index);
|
|
596
|
+
continue;
|
|
597
|
+
}
|
|
598
|
+
if (this.#readPad(pad, index) === "unmapped") {
|
|
599
|
+
this.#forgetPad(index);
|
|
600
|
+
continue;
|
|
601
|
+
}
|
|
602
|
+
if (firstMapped < 0) firstMapped = index;
|
|
603
|
+
// A claim, not a level and not a pad-wide edge: a worn stick resting past the dead zone reports
|
|
604
|
+
// input on every tick, and one jittering across the zone produces an edge every few ticks, so
|
|
605
|
+
// either test would let a phantom pad take the slot in the middle of a real move — the bug this
|
|
606
|
+
// PRD exists to remove. A wedge either presses a button that was up, or travels past half a
|
|
607
|
+
// stick; a resting stick does neither, and a button press reclaims even while the player is
|
|
608
|
+
// already holding their stick still.
|
|
609
|
+
const mask = this.#padButtonMaskNow();
|
|
610
|
+
const stick = this.#padStickNow();
|
|
611
|
+
const pressedNewButton = (mask & ~(this.#padButtonMask[index] ?? 0)) !== 0;
|
|
612
|
+
const travelled =
|
|
613
|
+
stick >= GAMEPAD_CLAIM_STICK && (this.#padStick[index] ?? 0) < GAMEPAD_CLAIM_STICK;
|
|
614
|
+
if ((pressedNewButton || travelled) && claimSlot < 0) claimSlot = index;
|
|
615
|
+
this.#padButtonMask[index] = mask;
|
|
616
|
+
this.#padStick[index] = stick;
|
|
617
|
+
if (this.#padHasInput() && inputSlot < 0) inputSlot = index;
|
|
618
|
+
if (index === this.#activePadSlot) activeStillMapped = true;
|
|
619
|
+
}
|
|
620
|
+
// A source that shrinks never visits its old slots again, so they are forgotten here; otherwise a
|
|
621
|
+
// pad that later connects into one of them would inherit the previous pad's claim history.
|
|
622
|
+
for (let index = sources.length; index < this.#padButtonMask.length; index += 1)
|
|
623
|
+
this.#forgetPad(index);
|
|
624
|
+
for (const key of this.#padReports.keys())
|
|
625
|
+
if (!this.#padSeen.has(key)) this.#padReports.delete(key);
|
|
626
|
+
// The pad the player last claimed owns the input, and keeps it while idle so its releases are
|
|
627
|
+
// read. A pad that disappeared, or one the browser now reports unmapped, hands over to whichever
|
|
628
|
+
// pad is being held, then to the first pad there is. A slot nobody claimed — it merely held the
|
|
629
|
+
// input when nothing else did — is not owned, so a gentle tilt of the pad in the player's hands
|
|
630
|
+
// outranks it; that is what stops an idle dongle in slot 0 from needing a claim to get past.
|
|
631
|
+
let active: number;
|
|
632
|
+
let owned = false;
|
|
633
|
+
if (claimSlot >= 0) {
|
|
634
|
+
active = claimSlot;
|
|
635
|
+
owned = true;
|
|
636
|
+
} else if (activeStillMapped && this.#activePadClaimed && this.#activePadSlot >= 0) {
|
|
637
|
+
active = this.#activePadSlot;
|
|
638
|
+
owned = true;
|
|
639
|
+
} else if (inputSlot >= 0) {
|
|
640
|
+
active = inputSlot;
|
|
641
|
+
} else {
|
|
642
|
+
active = firstMapped;
|
|
643
|
+
}
|
|
644
|
+
this.#activePadSlot = active;
|
|
645
|
+
this.#activePadClaimed = owned;
|
|
646
|
+
// Reused buffers: fresh arrays here were four allocations per update step, device or not.
|
|
647
|
+
this.#gamepadAxes.length = 0;
|
|
648
|
+
this.#gamepadButtons.length = 0;
|
|
649
|
+
const pad = active < 0 ? undefined : sources[active];
|
|
650
|
+
if (pad === null || pad === undefined || this.#readPad(pad, active) === "unmapped") {
|
|
651
|
+
this.raw.gamepad.axes = this.#gamepadAxes;
|
|
652
|
+
this.raw.gamepad.buttons = this.#gamepadButtons;
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
for (const axis of this.#padScratch.axes) this.#gamepadAxes.push(axis);
|
|
656
|
+
for (const button of this.#padScratch.buttons) this.#gamepadButtons.push(button.pressed);
|
|
657
|
+
this.raw.gamepad.axes = this.#gamepadAxes;
|
|
658
|
+
this.raw.gamepad.buttons = this.#gamepadButtons;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/** Normalizes one pad into the scratch buffer and reports it once per connect. */
|
|
662
|
+
#readPad(pad: IInputGamepad, index: number): GamepadNormalizer {
|
|
663
|
+
const normalizer = toStandardPad(pad, this.#padScratch);
|
|
664
|
+
// `index:id`: two identical pads are two pads, and a hotplug that moves a pad to another slot
|
|
665
|
+
// is a new reading of where it is rather than a silent re-use of the old line. Built once per
|
|
666
|
+
// slot:id, because a template literal allocates and this runs twice a tick for the active pad.
|
|
667
|
+
const id = pad.id;
|
|
668
|
+
let key = this.#padKeys[index];
|
|
669
|
+
if (key === undefined || this.#padKeyIds[index] !== id) {
|
|
670
|
+
key = `${index}:${id ?? (PAD_SLOT_KEYS[index] as string)}`;
|
|
671
|
+
this.#padKeys[index] = key;
|
|
672
|
+
this.#padKeyIds[index] = id;
|
|
673
|
+
}
|
|
674
|
+
this.#padSeen.add(key);
|
|
675
|
+
if (this.#padReports.get(key) !== normalizer) {
|
|
676
|
+
this.#padReports.set(key, normalizer);
|
|
677
|
+
console.info(
|
|
678
|
+
`TN_GAMEPAD ${JSON.stringify({
|
|
679
|
+
deadZone: this.gamepadDeadZone,
|
|
680
|
+
id: pad.id ?? (PAD_SLOT_KEYS[index] as string),
|
|
681
|
+
mapping: normalizer,
|
|
682
|
+
})}`,
|
|
683
|
+
);
|
|
684
|
+
}
|
|
685
|
+
applyStickDeadZone(this.#padScratch.axes, 0, 1, this.gamepadDeadZone);
|
|
686
|
+
applyStickDeadZone(this.#padScratch.axes, 2, 3, this.gamepadDeadZone);
|
|
687
|
+
return normalizer;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
/** Clears one slot's claim history, so a pad that returns to it starts from rest. */
|
|
691
|
+
#forgetPad(index: number): void {
|
|
692
|
+
this.#padButtonMask[index] = 0;
|
|
693
|
+
this.#padStick[index] = 0;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
/** The scratch pad's pressed buttons as a mask, so a new press is one integer compare. */
|
|
697
|
+
#padButtonMaskNow(): number {
|
|
698
|
+
let mask = 0;
|
|
699
|
+
const buttons = this.#padScratch.buttons;
|
|
700
|
+
for (let index = 0; index < buttons.length; index += 1)
|
|
701
|
+
if (buttons[index]?.pressed === true) mask |= 1 << index;
|
|
702
|
+
return mask;
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/** The scratch pad's larger stick travel on the rescaled axes, which is what a claim compares. */
|
|
706
|
+
#padStickNow(): number {
|
|
707
|
+
const axes = this.#padScratch.axes;
|
|
708
|
+
const left = Math.sqrt((axes[0] ?? 0) ** 2 + (axes[1] ?? 0) ** 2);
|
|
709
|
+
const right = Math.sqrt((axes[2] ?? 0) ** 2 + (axes[3] ?? 0) ** 2);
|
|
710
|
+
return Math.max(left, right);
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/** Whether the normalized pad in the scratch buffer has moved past its dead zone or pressed anything. */
|
|
714
|
+
#padHasInput(): boolean {
|
|
715
|
+
for (const axis of this.#padScratch.axes) if (axis !== 0) return true;
|
|
716
|
+
for (const button of this.#padScratch.buttons) if (button.pressed) return true;
|
|
717
|
+
return false;
|
|
718
|
+
}
|
|
719
|
+
|
|
508
720
|
/** Was this action pressed at any point since the last tick, even if already released? */
|
|
509
721
|
#latchedPressed(name: string): boolean {
|
|
510
722
|
const binding = this.#bindings[name];
|