threedog 1.0.1 → 1.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.
@@ -1,764 +1,764 @@
1
- // Collision, real physics, camera.
2
- import type { Object3D, Vector3, DirXZ, Vec3Like, Ease, Handle, PositionLike } from './common';
3
- import type { Engine, ModuleDef } from './core';
4
- import type { Input } from './generated/core/input/Input';
5
- import type { Character } from './gameplay';
6
-
7
- // ======================================================================
8
- // Lightweight collision collision() → engine.collision
9
- // ======================================================================
10
-
11
- export interface CollisionOptions {
12
- /** Max walkable slope (height difference / horizontal distance), default 1.1 */
13
- maxClimb?: number;
14
- /** A camera above this height (meters) is not considered blocked by trees, default 5 */
15
- canopyHeight?: number;
16
- /** Margin between the camera and obstacles (meters), default 0.5 @experimental */
17
- cameraPad?: number;
18
- /** Nearest camera distance (meters), default 1.5 */
19
- cameraMin?: number;
20
- /** Height above the water surface (meters) at which it counts as walkable, default 0.2 @experimental */
21
- walkableWaterMargin?: number;
22
- /** What camera occlusion checks: 'both' (default) | 'colliders' | 'meshes' = static meshes registered with engine.rays.addStatic(mesh, { occluder: true }) */
23
- cameraOcclusion?: 'colliders' | 'meshes' | 'both';
24
- }
25
- /** Circle collider: center x/z, radius r, height h (meters), occ false when added with occluder: false */
26
- export interface CircleCollider { x: number; z: number; r: number; h: number; occ: boolean }
27
- /** Box collider: center x/z, half width hw, half depth hd, rotation around Y rot (radians), height h, bottom height y (meters), occ as in CircleCollider */
28
- export interface BoxCollider { x: number; z: number; hw: number; hd: number; rot: number; h: number; y?: number; occ: boolean; [k: string]: any }
29
-
30
- /** Parameters of addCircle() (meters) */
31
- export interface CircleColliderOptions {
32
- /** Radius, default 0.5 */
33
- radius?: number;
34
- /** Height, default 6 */
35
- height?: number;
36
- /** false: walkers are still stopped but the follow camera's occlusion check ignores it (forest trunks the camera may pass through). Default true */
37
- occluder?: boolean;
38
- }
39
- /** Parameters of addBox() (meters, radians) */
40
- export interface BoxColliderOptions {
41
- /** Half width (X direction), default 1 */
42
- halfWidth?: number;
43
- /** Half depth (Z direction), default 1 */
44
- halfDepth?: number;
45
- /** Rotation around the Y axis (radians), default 0 */
46
- rotation?: number;
47
- /** Height, default 6 */
48
- height?: number;
49
- /** Bottom height of the box; if omitted it sits on the ground (give it for walls placed on platforms in a level) */
50
- y?: number;
51
- /** false: walkers are still stopped but the follow camera's occlusion check ignores it (forest trunks the camera may pass through). Default true */
52
- occluder?: boolean;
53
- }
54
-
55
- /** engine.collision (lightweight collision: no walking through things, the camera is not blocked). Real physics is a separate module, engine.rigid */
56
- export interface Collision {
57
- /** @experimental */ maxClimb: number;
58
- /** @experimental */ canopyHeight: number;
59
- /** @experimental */ cameraPad: number;
60
- /** @experimental */ cameraMin: number;
61
- /** @experimental */ walkableWaterMargin: number;
62
- /** What camera occlusion checks (see CollisionOptions.cameraOcclusion) @experimental */
63
- cameraOcclusion: 'colliders' | 'meshes' | 'both';
64
- /** +1 each time a static collider is added or removed @experimental */
65
- version: number;
66
- /** Add a circle collider (pillar, campfire): position is the center, e.g. addCircle(mesh, { radius: 1 }). Returns a handle { remove() } */
67
- addCircle(position: PositionLike, opts?: CircleColliderOptions): Handle;
68
- /** Add a box collider (house, fence): position is the center, e.g. addBox(house, { halfWidth: 3, halfDepth: 2, rotation: 0.3 }). Returns a handle { remove() } */
69
- addBox(position: PositionLike, opts?: BoxColliderOptions): Handle;
70
- /** Add a thin wall along a -> b (fence). Options: thickness (default 0.3), height, y, occluder (as in addBox). A gap between segments is a gate. Returns a handle { remove() } */
71
- addSegment(a: PositionLike, b: PositionLike, opts?: { thickness?: number; height?: number; y?: number; occluder?: boolean }): Handle;
72
- /** Mark ground impassable where fn(x, z) is true (river, lava); fn must be pure (no side effects, same answer for the same (x, z)); reading engine.ground in it is fine. findPathAsync caches the answers, so after the ground or your own state changes, remove() and add the field again. bounds { minX, maxX, minZ, maxZ } (world metres, the field's x / z extent) skips fn outside it; give it to keep findPathAsync's ground sampling cheap. Returns a handle { remove() } */
73
- addBlocked(fn: (x: number, z: number) => boolean, opts?: { bounds?: { minX: number; maxX: number; minZ: number; maxZ: number } }): Handle;
74
- /** Is a character of this radius touching addBlocked ground at (x, z) @experimental */
75
- blockedAt(x: number, z: number, radius?: number): boolean;
76
- /** Add a collider from an object's bounding box, pad expands outward (meters), occluder as in addBox. Returns a handle { remove() } */
77
- addObject(obj: Object3D, opts?: { pad?: number; occluder?: boolean }): Handle;
78
- /** Iterate all static colliders added by hand @experimental */
79
- forEachStatic(fn: (type: 'box' | 'circle', data: any) => void): void;
80
- /** Keep an outside copy of the static colliders in step (physics colliders, navmesh obstacles): add builds one piece, remove drops one; sync() diffs only when colliders changed and returns whether it compared; clear() forgets every piece without remove (the outside world was thrown away) @experimental */
81
- mirror<P>(fns: { add(type: 'box' | 'circle', data: any): P; remove(piece: P, data: any): void }): { sync(): boolean; clear(): void; readonly size: number };
82
- /** Whether someone can stand at this position (for pathfinding): not in water, not too steep, not inside an obstacle. radius is the character radius (meters, default engine.movement.radius) */
83
- walkable(position: PositionLike, opts?: { radius?: number }): boolean;
84
- /** walkable with plain numbers, allocating nothing (A* inner loops); radius defaults to engine.movement.radius */
85
- walkableAt(x: number, z: number, radius?: number): boolean;
86
- /** Line of sight with height: is the 3D segment a -> b free of boxes, circles and terrain trees? radius fattens the line; addBlocked water is ignored. Give eye heights in a / b */
87
- lineClear(a: PositionLike, b: PositionLike, opts?: { radius?: number; /** who is looking (names the line in the event trace) */ who?: string }): boolean;
88
- }
89
-
90
- // ======================================================================
91
- // Real physics rigid() → engine.rigid
92
- // ======================================================================
93
-
94
- export interface RigidOptions {
95
- /** Gravity (m/s², negative points down), default -9.81 */
96
- gravity?: number;
97
- /** How many rings of chunks around the player get terrain colliders, default 1. A body outside them freezes until the player comes near (entry.enabled false, describe().rigid.frozen), because it would fall through the ground: raise this for a car or ball that must keep moving far away */
98
- terrainRing?: number;
99
- /** Whether there is buoyancy, default true */
100
- buoyancy?: boolean;
101
- /** Buoyancy strength (1 = just floats), default 1.6 @experimental */
102
- buoyancyForce?: number;
103
- /** Drag in water, default 2.5 @experimental */
104
- waterDrag?: number;
105
- /** Buoyancy "waterline": an object starts floating when its center is this many meters below the water surface, default 0.3 @experimental */
106
- floatLine?: number;
107
- /** Buoyancy reaches its maximum this many meters further down, default 0.8 @experimental */
108
- floatDepth?: number;
109
- /** Height (meters) of vegetation collision pillars (tree trunks), default 6 @experimental */
110
- treeColliderHeight?: number;
111
- /** Trunks get collision cylinders only in chunks within this many meters of the player or a moving rigid body (the rest are covered by engine.collision for characters), default 16 @experimental */
112
- treeRadius?: number;
113
- /** Player capsule size (meters), default computed from engine.movement radius / height @experimental */
114
- playerCapsule?: { halfHeight: number; radius: number };
115
- /** The flat plane at y = 0 when the ground has no collision of its own, default true. false: only your own bodies and colliders are there (a sky of islands) */
116
- fallbackFloor?: boolean;
117
- }
118
- /** Parameters for adding a physics body */
119
- export interface RigidBodyOptions {
120
- /** Stable id (e.g. the world record id): saves keep this body's pose, rotation, velocities and sleep under it, and a load hands them back to the body with this id, also one built after the load. Without an id the body is not saved. Unique among live bodies and vehicles */
121
- id?: string;
122
- /** Mass (kilograms), default 1 */
123
- mass?: number;
124
- /** Friction, default 0.7 */
125
- friction?: number;
126
- /** Restitution 0–1, default 0.1 */
127
- restitution?: number;
128
- /** Linear damping, default 0.05 */
129
- damping?: number;
130
- /** Angular damping, default 0.1 */
131
- angularDamping?: number;
132
- /** Fixed in place (only blocks other things) */
133
- fixed?: boolean;
134
- }
135
- /** Parameters of addBox() */
136
- export interface RigidBoxOptions extends RigidBodyOptions {
137
- /** Size [width, height, depth] (meters); if omitted, taken from the model's bounding box */
138
- size?: number[];
139
- }
140
- /** Parameters of addBall() */
141
- export interface RigidBallOptions extends RigidBodyOptions {
142
- /** Radius (meters); if omitted, taken from the model's bounding box */
143
- radius?: number;
144
- }
145
- /** A physics body (the handle returned by addBox / addBall / addHull) */
146
- export interface RigidEntry extends Handle {
147
- /** The id it was added with (saves name it by this), undefined without one */
148
- readonly id?: string;
149
- /** Rapier rigid body (translation(), mass(), setLinvel()…); newGame / a load rebuild the world, so read entry.body again instead of keeping it */
150
- body: any;
151
- /** Rapier collider */
152
- collider: any;
153
- /** The matching three.js model (position is written by physics every step) */
154
- mesh: Object3D;
155
- /** Same as mesh */
156
- object: Object3D;
157
- /** Whether it is being simulated: false while it is outside the terrain colliders (rigid({ terrainRing })), where it would fall through the ground */
158
- enabled: boolean;
159
- /** Volume (cubic meters, used for buoyancy) */
160
- volume: number;
161
- damping: number;
162
- angularDamping: number;
163
- wet?: boolean;
164
- /** Remove this rigid body (the model was passed in by you and is not deleted; call engine.remove(entry.object) when done). Casting / receiving shadows follows the model's own castShadow / receiveShadow */
165
- remove(): void;
166
- }
167
-
168
- /** Options of engine.rigid.ragdoll @experimental */
169
- export interface RagdollOptions {
170
- /** A push (kg*m/s) on the part nearest position, else on the root part. A hit stronger than the part can take spreads to the whole body, total momentum unchanged */
171
- impulse?: Vec3Like;
172
- /** Where the push lands (world) */
173
- position?: PositionLike;
174
- /** Humanoid graph only: part -> bone name or bone, over the auto-detection. Parts: hips, chest, head, upperArmL, lowerArmL, upperArmR, lowerArmR, upperLegL, lowerLegL, upperLegR, lowerLegR */
175
- bones?: Record<string, string | Object3D>;
176
- /** Part or kind ('lowerLeg', 'upperArm', 'chest', 'head'...) -> [min, max] radians from the bind pose: bend forward (a knee: backward), side, twist along the bone */
177
- limits?: Record<string, { bend?: [number, number]; side?: [number, number]; twist?: [number, number] }>;
178
- /** Whole body, kg (default the graph's; humanoid 70). The graph's proportions stay */
179
- mass?: number;
180
- }
181
-
182
- /** One part of a ragdoll graph, the value of the rule 'ragdoll.graph': { body: { bone: 'Spine' }, tail: { bone: 'Tail1', parent: 'body', mass: 2 } } @experimental */
183
- export interface RagdollPart {
184
- /** Bone name or bone */
185
- bone: string | Object3D;
186
- /** The part this one hangs from; its bone must be above this bone. Exactly one part has none: the root, which leads the body */
187
- parent?: string;
188
- /** Range of motion, [min, max] radians from the bind pose; default loose (45° bend and side, 30° twist) */
189
- limits?: { bend?: [number, number]; side?: [number, number]; twist?: [number, number] };
190
- /** kg; default 70 shared equally */
191
- mass?: number;
192
- /** The part this bone points at; default the middle of its child parts, then its first child bone. 'top' measures it from the mesh along up (a head) */
193
- end?: string;
194
- /** Which way a positive bend moves the tip, in bind space; default [0, 0, 1] */
195
- forward?: Vec3Like;
196
- /** Fallback for forward and the direction of end: 'top'; default [0, 1, 0] */
197
- up?: Vec3Like;
198
- /** Name shared by several parts, so one limits entry of rigid.ragdoll covers them ('leg') */
199
- kind?: string;
200
- }
201
-
202
- /** What engine.rigid.ragdoll returns. remove() gives the character back; safe to call twice @experimental */
203
- export interface Ragdoll extends Handle {
204
- /** False once removed (remove(), a load, the character deleted) */
205
- readonly active: boolean;
206
- /** Every part is at rest (asleep or frozen). Nothing is written to the bones then, so a game's own bone write stays */
207
- readonly settled: boolean;
208
- /** Part name -> its rigid entry: entry.body for forces, entry.object is the bone; engine.raycast hits carry the same entry. The bones stay plain three.js */
209
- readonly parts: Record<string, RigidEntry>;
210
- }
211
-
212
- /** A hit of Collider3D.sweep */
213
- export interface SweepHit {
214
- /** The ball's center at the hit */
215
- point: Vector3;
216
- /** World direction out of what it hit */
217
- normal: Vector3;
218
- /** How far the ball got (meters) */
219
- distance: number;
220
- }
221
- /** engine.collider3d: collision on all three axes (modules/rigid/collider3d.contract.js). rigid provides it; engine.use(mine(), { replaces: 'collider3d' }) swaps in your own @experimental */
222
- export interface Collider3D {
223
- /** A fixed solid turned any way. size [x, y, z] for a box or radius for a ball; rotation [x, y, z] radians or a quaternion. Callable before start(); newGame and a load keep it. engine.collision does not know it */
224
- addSolid(opts: { position: PositionLike; size?: number[]; radius?: number; rotation?: number[] | { x: number; y: number; z: number; w: number }; friction?: number }): Handle;
225
- /** Is a ball here inside something solid. Skips the player's capsule */
226
- overlap(position: PositionLike, radius?: number): boolean;
227
- /** Move a ball from there to there: null when clear, else the first hit. Skips the player's capsule */
228
- sweep(from: PositionLike, to: PositionLike, radius?: number): SweepHit | null;
229
- }
230
-
231
- /** engine.rigid (real physics; bodies can only be added after start(), or in the engine:ready event) */
232
- export interface RigidBodies {
233
- /** Is the physics engine ready (downloaded and initialized at start()) */
234
- readonly ready: boolean;
235
- /** All physics bodies */
236
- bodies: RigidEntry[];
237
- gravity: number;
238
- /** @experimental */ terrainRing: number;
239
- /** @experimental */ buoyancy: boolean;
240
- /** @experimental */ buoyancyForce: number;
241
- /** @experimental */ waterDrag: number;
242
- /** @experimental */ floatLine: number;
243
- /** @experimental */ floatDepth: number;
244
- /** @experimental */ treeColliderHeight: number;
245
- /** @experimental */ treeRadius: number;
246
- /** The Rapier library itself: its shape follows the Rapier version @experimental */
247
- rapier: any;
248
- /** The Rapier world: its shape follows the Rapier version @experimental */
249
- world: any;
250
- /** Add a box (crate). Physics is ready after engine.start() (or on engine:ready): called before, it throws in development, a release build warns once and returns null */
251
- addBox(mesh: Object3D, opts?: RigidBoxOptions): RigidEntry | null;
252
- /** Add a ball; null only as in addBox: a release build, called before physics is ready @experimental */
253
- addBall(mesh: Object3D, opts?: RigidBallOptions): RigidEntry | null;
254
- /** Add a convex hull (irregular objects such as rocks and barrels); null only as in addBox: a release build, called before physics is ready @experimental */
255
- addHull(mesh: Object3D, opts?: RigidBodyOptions): RigidEntry | null;
256
- /**
257
- * Turn a skinned character limp in one call; rd.remove() returns it to animation. who: a Character, an NPC handle, a character id or a skinned Object3D.
258
- * Its mover, animator, capsule and camera yield until then; calling again on the same one pushes it again and returns the same ragdoll.
259
- * Not saved: any load ends it. A skeleton it cannot read throws, naming the missing parts. The rule 'ragdoll.graph' (per character id) gives the parts: 'humanoid' (default),
260
- * Record<string, RagdollPart> for any other body, a function (facts: { character, root, mesh }, engine) => one of those, or false for no ragdoll (returns null). @experimental
261
- */
262
- ragdoll(who: any, opts?: RagdollOptions): Ragdoll | null;
263
- /** Give it a push: impulse vector impulse (Vector3 / [x, y, z] / { x, y, z }), e.g. impulse(ball, [0, 3, 5]) */
264
- impulse(entry: RigidEntry, impulse: Vec3Like): void;
265
- /** Teleport to position (velocity is zeroed) */
266
- setPosition(entry: RigidEntry, position: PositionLike): void;
267
- /** The player's Rapier kinematic body and capsule collider (follow the player position every step; used for collision when mover: 'rapier'; the capsule is off while driving) @experimental */
268
- playerBody: any;
269
- /** The capsule collider on playerBody @experimental */
270
- playerCollider: any;
271
- /** Player capsule size (meters) @experimental */
272
- playerCapsule: { halfHeight: number; radius: number };
273
- /** All vehicles @experimental */
274
- vehicles: Vehicle[];
275
- /**
276
- * Turn a model into a wheeled vehicle (Rapier ray-cast vehicle controller: cars, karts, carts); remove it with vehicle.remove() (anyone inside gets out
277
- * first). Before physics is ready it throws in development (release: warns, null), like addBox. Boats, mounts and mechs are the game's own objects with the same seat interface
278
- */
279
- addWheeled(mesh: Object3D, opts: VehicleOptions): Vehicle | null;
280
- /** Statistics */
281
- readonly stats: { bodies: number; active: number; colliders: number };
282
- }
283
-
284
- // ---------- Vehicles ----------
285
- /** A wheel: position relative to the body (meters), radius (meters), steer can steer, drive is powered, object is the wheel model that spins */
286
- export interface VehicleWheel { position: Vec3Like; radius: number; steer?: boolean; drive?: boolean; object?: Object3D }
287
- /** Parameters of rigid.addWheeled() */
288
- export interface VehicleOptions {
289
- /** Stable id (default 'vehicle1', 'vehicle2'... in creation order): saves name the player's vehicle and the vehicle's body state by it; give one when the creation order varies */
290
- id?: string;
291
- /** Wheels (at least 3) */
292
- wheels: VehicleWheel[];
293
- /** Mass (kilograms) */
294
- mass?: number;
295
- /** Throttle force, default 800 */
296
- engineForce?: number;
297
- /** Brake force, default 20 */
298
- brakeForce?: number;
299
- /** Max steering angle (radians), default 0.5 */
300
- maxSteer?: number;
301
- /** Suspension: rest natural length (meters), stiffness, damping */
302
- suspension?: { rest?: number; stiffness?: number; damping?: number };
303
- /** Seat positions relative to the body (meters): the first drives, the rest ride; each gets out beside its own seat. Default one at the body center */
304
- seats?: Vec3Like[];
305
- /** Hide whoever sits in it, default true; false keeps riders visible on their seats, turning with the vehicle (bikes, open carts, karts) */
306
- hideDriver?: boolean;
307
- /** Camera distance and height while driving (meters) */
308
- camera?: { distance?: number; height?: number };
309
- /** Body collision box size [width, height, depth] (meters); if omitted, taken from the model's bounding box (wheels excluded) */
310
- size?: number[];
311
- /** Tire grip, default 1.5 */
312
- friction?: number;
313
- /** Distance from the side of the body when getting out (meters), default 0.8 */
314
- exitOffset?: number;
315
- }
316
- /** A vehicle (returned by rigid.addWheeled, faces the model's +Z). player.enter(vehicle) gets in; with interactions installed, press the interact key nearby to get in / out */
317
- export interface Vehicle extends RigidEntry, Rideable {
318
- /** Stable id (rigid.addWheeled({ id })); saves name the player's vehicle by it */
319
- readonly id: string;
320
- /** Body model (the mesh you passed in) */
321
- object: Object3D;
322
- /** Rapier rigid body */
323
- body: any;
324
- /** Rapier vehicle controller (DynamicRayCastVehicleController) */
325
- controller: any;
326
- wheels: VehicleWheel[];
327
- seats: number;
328
- passengers: Character[];
329
- hideDriver: boolean;
330
- /** World position of a seat (default 0, the driver's) */
331
- seatPosition(seat?: number): Vector3;
332
- /** Where to get out of a seat (outside the door on that seat's side, world coordinates) */
333
- exitPosition(seat?: number, n?: number): Vector3;
334
- }
335
- /**
336
- * What character.enter(vehicle) needs from anything it rides (modules/characters/vehicle.contract.js): rigid.addWheeled's car passes it, and so does a
337
- * game's own boat, horse, mech or lift built on three.js or another physics library.
338
- */
339
- export interface Rideable {
340
- /** Stable id when saves should put the player back in it (rigid vehicles have one) */
341
- readonly id?: string;
342
- /** What the camera follows while driving */
343
- object: Object3D;
344
- /** Current speed (m/s): the driver's moveAmount (animation, describe) */
345
- readonly speed: number;
346
- /** Who is driving (null if nobody); character.enter / exit set it */
347
- driver: Character | null;
348
- /** Number of seats, driver included (default 1); enter takes the driver seat, else the first free passenger seat */
349
- seats?: number;
350
- /** Who rides in the other seats (enter creates the list when missing) */
351
- passengers?: Character[];
352
- /** false keeps riders visible on their seats (bikes, open carts); default hidden */
353
- hideDriver?: boolean;
354
- /** Camera parameters while driving */
355
- camera?: { distance?: number; height?: number };
356
- /** Controls, called every fixed step while driven: throttle -1..1, steer -1..1 (right is positive), brake 0–1; exit calls drive(0, 0, 1) */
357
- drive(throttle: number, steer: number, brake?: number): void;
358
- /** World position of a seat (default 0, the driver's; a rider is kept there) */
359
- seatPosition(seat?: number): Vector3 | Vec3Like;
360
- /** Where to get out of a seat (world coordinates; rigid cars: outside the door on that seat's side) */
361
- exitPosition(seat?: number, n?: number): Vector3 | Vec3Like;
362
- }
363
-
364
- // ======================================================================
365
- // Skeletal animation state machine Animator (returned by engine.assets.animate)
366
- // ======================================================================
367
-
368
- /** An animation state: clip is the clip name; or blend is a blend tree (blends several clips by the param parameter); loop: false is a one-shot clip */
369
- export interface AnimatorState {
370
- /** Clip name (the clip name in the glTF) */
371
- clip?: string;
372
- /** Blend tree: at the parameter value at it is fully this clip, in between they blend proportionally, e.g. [{ clip: 'Walk', at: 1.5 }, { clip: 'Run', at: 6 }] */
373
- blend?: { clip: string; at: number }[];
374
- /** Which parameter the blend tree reads (set by anim.set), default 'speed' */
375
- param?: string;
376
- /** Align the strides of blended clips, default true */
377
- sync?: boolean;
378
- /** Loop, default true; with false the anim:end event fires when it finishes */
379
- loop?: boolean;
380
- /** Which state a one-shot clip goes to when it finishes */
381
- then?: string;
382
- /** go() cannot interrupt it while playing */
383
- lock?: boolean;
384
- /**
385
- * For sync(): gameplay seconds -> clip seconds. A number = the gameplay length the whole clip is stretched over;
386
- * [[gameT, clipT], ...] = piecewise linear (land the swing on the hit phase). Without it clip seconds = t
387
- */
388
- timing?: number | [number, number][];
389
- }
390
- /** What an Animator is showing (anim.describe(), describe().player.anim) */
391
- export interface AnimatorInfo {
392
- state: string | null;
393
- /** Clip name as written in the state */
394
- clip: string | null;
395
- /** Clip seconds */
396
- time: number;
397
- /** 0-1 through the clip */
398
- progress: number;
399
- /** true while sync() drives it */
400
- driven: boolean;
401
- /** Last gameplay t passed to sync (only while driven) */
402
- t?: number;
403
- /** Share of each fading state (sums to 1) */
404
- weights: Record<string, number>;
405
- }
406
- /** Animation state machine parameters */
407
- export interface AnimatorOptions {
408
- /** Default transition seconds, default 0.25 (characters({ animation: { fade } }) for every character) */
409
- fade?: number;
410
- /** States: name → state */
411
- states?: Record<string, AnimatorState>;
412
- /** Transition seconds for specific pairs: { 'jump>fall': 0.1, '*>idle': 0.3 } */
413
- transitions?: Record<string, number>;
414
- /** Initial parameter values */
415
- params?: Record<string, number>;
416
- }
417
- /** Skeletal animation state machine (returned by engine.assets.animate(model, config)) */
418
- export declare class Animator {
419
- constructor(engine: Engine, root: Object3D, opts?: AnimatorOptions);
420
- /** The animated object */
421
- root: Object3D;
422
- /** three.js AnimationMixer */
423
- mixer: any;
424
- /** clip name → three.js AnimationAction */
425
- actions: Map<string, any>;
426
- /** Current state name */
427
- state: string | null;
428
- /** State configuration (states can be added directly) */
429
- states: Record<string, AnimatorState>;
430
- /** Parameters (used by blend trees) */
431
- params: Record<string, number>;
432
- /** Set a parameter, e.g. set('speed', 3) */
433
- set(param: string, value: number): this;
434
- /** Switch to a state ({ fade }: transition seconds); null (dev warning) if there is no such state / clip; ignored while sync() drives a state */
435
- go(state: string, opts?: { fade?: number }): any;
436
- /** One-shot clip: state name or clip name, returns to then or the previous state when done; go() cannot interrupt it while playing */
437
- action(name: string, opts?: { fade?: number }): any;
438
- /**
439
- * Gameplay drives the clock: show state at gameplay time t (fixed-step seconds) through its timing.
440
- * The clip never advances or ends by itself and go() leaves it alone; sync(null) hands control back
441
- */
442
- sync(state: string | null, t?: number): any;
443
- /** What is showing: state, clip, clip time, progress, driven, weights */
444
- describe(): AnimatorInfo;
445
- /**
446
- * Check the mapping against the action names the game plays: each problem as text with its fix ([] = all will play).
447
- * @example anim.check(['idle', 'walk', 'attack', 'hurt'])
448
- */
449
- check(actions?: string[]): string[];
450
- /** Stop the per-frame update when no longer needed */
451
- dispose(): void;
452
- }
453
-
454
- // ======================================================================
455
- // Camera → engine.cameraRig (install one kind, switch at runtime with engine.setCamera)
456
- // ======================================================================
457
-
458
- /** Camera kinds: 'follow' third person | 'firstPerson' first person | 'fixed' fixed shot | 'rts' strategy top-down */
459
- export type CameraKind = 'follow' | 'firstPerson' | 'fixed' | 'rts';
460
-
461
- /** Interface shared by all cameras */
462
- export interface CameraRigBase {
463
- /** Current kind (the first argument of engine.setCamera) */
464
- kind: CameraKind;
465
- /** The object being followed */
466
- target: Object3D | null;
467
- /** The pixelSnap option at work, or null: grid (give it to pixelSprite), error (last rounding in art pixels), agrees (false: something else set the view height, rounding stopped) */
468
- pixelSnap?: { readonly grid: import('./pixel').PixelGrid; readonly error: { x: number; y: number }; readonly agrees: boolean; bounds: import('./pixel').PixelBounds | null } | null;
469
- /** Follow someone (called automatically when the player is created), null to cancel. opts temporarily changes distance / height (used while driving), restored when the target changes */
470
- follow(obj: Object3D | null, opts?: { distance?: number; height?: number }): void;
471
- /** The "forward" direction on the horizontal plane (player movement is relative to it) */
472
- forward(): DirXZ;
473
- /** The "right" direction on the horizontal plane */
474
- right(): DirXZ;
475
- /** Where the world loads around (the followed object's position, else the camera's) */
476
- focusPoint(): Vector3;
477
- /** Screen coordinates (-1..1, engine.input.pointer.ndcX / ndcY) → the point on the ground under it, null if nothing is hit (every camera kind) */
478
- screenToGround(ndcX: number, ndcY: number): Vector3 | null;
479
- /** Update the camera every frame */
480
- update(dt: number, input: Input): void;
481
- /** Called when a cutscene takeover starts / ends */
482
- onOverride?(on: boolean): void;
483
- /** Called when this camera is switched in (switched: switched at runtime) */
484
- onEnter?(switched?: boolean): void;
485
- /** Called when this camera is switched out */
486
- onExit?(): void;
487
- }
488
-
489
- export interface FollowCameraOptions {
490
- /** 'orthographic' draws without perspective (isometric / 2.5D; the wheel then changes size); default 'perspective' */
491
- projection?: 'perspective' | 'orthographic';
492
- /** With projection 'orthographic': world units of view height, default 20 */
493
- size?: number;
494
- /** Which side of the focus the camera sits on (radians), default 0.8: camera = focus + (sin yaw, cos yaw) × distance, it looks along forward() = -(sin yaw, cos yaw). Behind a character facing f: yaw = f + PI */
495
- yaw?: number;
496
- /** Pitch angle (radians), default 0.42. Positive = camera above the look point, looking down: the opposite of firstPersonCamera's pitch */
497
- pitch?: number;
498
- /** Distance (meters), default 13 */
499
- distance?: number;
500
- /** Zoom range (meters) */
501
- minDistance?: number;
502
- maxDistance?: number;
503
- /** How high above the character to look at (meters), default 1.4 */
504
- height?: number;
505
- /** Follow smoothing, default 10 @experimental */
506
- smoothing?: number;
507
- /** Drag sensitivity, default 1 */
508
- sensitivity?: number;
509
- /** Pitch range (radians) */
510
- minPitch?: number;
511
- /** @experimental */ maxPitch?: number;
512
- /** Zoom ratio per wheel notch, default 0.1 @experimental */
513
- zoomStep?: number;
514
- /** Minimum camera height above the ground (meters), default 1.2 @experimental */
515
- groundClearance?: number;
516
- /** Invert vertical @experimental */
517
- invertY?: boolean;
518
- /** Lock the pitch angle (top-down games) */
519
- lockPitch?: boolean;
520
- /** Over-the-shoulder offset: meters to the right of the target the camera aims (negative = left shoulder), default 0 */
521
- shoulder?: number;
522
- /** Click locks the mouse; mouse motion turns the view without dragging (Esc releases), default false */
523
- pointerLock?: boolean;
524
- /** The press that locks the mouse is not delivered as Mouse0 / a click (default true); false delivers it too */
525
- swallowLockClick?: boolean;
526
- /**
527
- * What happens when the camera would go below the ground. 'raise': lift it (the view direction changes, so you cannot look up from flat ground);
528
- * 'shorten': pull it along the arm toward the look point (the view direction is kept, a negative minPitch really looks up); 'none': leave it;
529
- * a function gets the facts and returns the camera position (or null to keep it). Default: 'shorten' when minPitch < 0, else 'raise'
530
- */
531
- ground?: 'raise' | 'shorten' | 'none' | ((facts: FollowCameraGroundFacts) => Vec3Like | null | void);
532
- /** false: the built-in mouse / stick look and wheel zoom are off, the game drives the view with setView() (default true) */
533
- mouseLook?: boolean;
534
- /** Hide the followed object from the camera when the camera is closer than this to the look point (meters, 0 = never; default 0.9). The shadow stays */
535
- hideTargetNear?: number;
536
- /** Layer used to hide the followed object (0-31), default 30 */
537
- hideLayer?: number;
538
- /** Art-pixel rounding, orthographic only: rounds the camera on screen axes, clamps to bounds there first, and decides the view height (buffer height / pixelsPerMeter), so no size with it. Recipe 62 section 4b */
539
- pixelSnap?: { pixelsPerMeter: number; bounds?: import('./pixel').PixelBounds | null };
540
- }
541
- /** What a followCamera({ ground: fn }) function receives each frame */
542
- export interface FollowCameraGroundFacts {
543
- /** Camera position after wall avoidance (a copy) */
544
- position: Vector3;
545
- /** The point the camera looks at (target + height + shoulder) */
546
- lookPoint: Vector3;
547
- /** Unit arm direction, look point -> camera */
548
- dir: Vec3Like;
549
- /** Arm length after walls (m); distance is the wanted one */
550
- arm: number;
551
- distance: number;
552
- /** Ground height under the camera, groundClearance, and a ground query (x, z) => height */
553
- groundY: number;
554
- clearance: number;
555
- surface(x: number, z: number): number;
556
- rig: FollowCamera;
557
- }
558
- /** followCamera getView() */
559
- export interface FollowCameraView {
560
- yaw: number;
561
- /** Positive = camera above the look point looking down; negative = looking up */
562
- pitch: number;
563
- /** Wanted distance; arm is the actual one this frame (after walls and ground) */
564
- distance: number;
565
- arm: number;
566
- lookPoint: Vec3Like;
567
- /** Unit 3D direction the camera looks along */
568
- look: Vec3Like;
569
- }
570
- /** Third-person follow camera */
571
- export interface FollowCamera extends CameraRigBase, Required<Omit<FollowCameraOptions, 'lockPitch' | 'pixelSnap'>> {
572
- /** Smoothed follow point */
573
- focus: Vector3;
574
- lockPitch?: boolean;
575
- /** false: no occlusion handling */
576
- avoidOcclusion?: boolean;
577
- /** Lock-on framing set by frame() */
578
- framing: { target: Object3D | Vec3Like; strength: number } | null;
579
- /** Lock-on framing: turn yaw each frame toward "behind the followed object, looking at target"; mouse yaw is ignored meanwhile; null hands yaw back. strength default 6 (1/s) */
580
- frame(target: Object3D | Vec3Like | null, opts?: { strength?: number }): void;
581
- /** Set the view from game code: pitch is clamped to minPitch..maxPitch, distance to the zoom range. Negative pitch looks up. Pair with mouseLook: false to own it every frame */
582
- setView(view: { yaw?: number; pitch?: number; distance?: number }): this;
583
- /** The current view: angles, wanted / actual arm, look point and 3D look direction */
584
- getView(): FollowCameraView;
585
- /** Actual arm length last frame (after walls and ground), meters */
586
- readonly arm: number;
587
- }
588
-
589
- export interface FirstPersonCameraOptions {
590
- /** Eye height above the feet (meters), default 1.6 */
591
- height?: number;
592
- /** Mouse sensitivity, default 1 */
593
- sensitivity?: number;
594
- /** Field of view (degrees); unchanged if omitted */
595
- fov?: number | null;
596
- /** Walking bob amplitude (meters), 0 off, default 0.04 */
597
- headBob?: number;
598
- /** Bobs per meter @experimental */
599
- bobFrequency?: number;
600
- /** Hide the character itself (its shadow remains), default true @experimental */
601
- hideTarget?: boolean;
602
- /** Layer number used for hiding 0–31 */
603
- hideLayer?: number;
604
- /** Click to lock the mouse, default true */
605
- pointerLock?: boolean;
606
- /** The press that locks the mouse is not delivered as Mouse0 / a click (default true); false delivers it too */
607
- swallowLockClick?: boolean;
608
- /** Initial heading (radians) */
609
- yaw?: number;
610
- /** Initial look angle (radians), default 0 = level. Positive looks up, negative down: the opposite of followCamera's pitch */
611
- pitch?: number;
612
- /** Look down / up limit (radians), default -1.45 / 1.45 */
613
- minPitch?: number;
614
- /** @experimental */ maxPitch?: number;
615
- /** Turn range left / right [min, max] (radians), unlimited by default @experimental */
616
- yawLimits?: number[] | null;
617
- /** Smoothing of the camera following the body @experimental */
618
- smoothing?: number;
619
- /** Invert vertical @experimental */
620
- invertY?: boolean;
621
- }
622
- /** First-person camera */
623
- export interface FirstPersonCamera extends CameraRigBase, Required<Omit<FirstPersonCameraOptions, 'fov'>> {
624
- /** Eye position */
625
- eye: Vector3;
626
- /** Turn toward a world position (Vector3 / object / [x, y, z] / { x, y, z }) */
627
- lookAt(position: PositionLike): void;
628
- }
629
-
630
- /** Fixed shot */
631
- export interface CameraShot {
632
- /** Camera position */
633
- position: Vec3Like;
634
- /** Fixed point to look at (if omitted, it turns its head with the player) */
635
- lookAt?: Vec3Like;
636
- /** Turn its head with the player */
637
- track?: boolean;
638
- /** Field of view (degrees) */
639
- fov?: number;
640
- /** Position used to judge the "nearest shot", defaults to position */
641
- at?: Vec3Like;
642
- /** How high above the character to look at (meters) */
643
- trackHeight?: number;
644
- /** 'orthographic' draws this shot without perspective (isometric / 2.5D); default 'perspective' */
645
- projection?: 'perspective' | 'orthographic';
646
- /** With projection 'orthographic' (required there): world units of view height; the width follows the aspect */
647
- size?: number;
648
- }
649
- /** fixedCamera / setCamera('fixed', ...) options; the shot fields (position, lookAt, projection, size...) at the top level are a one-shot form: shots = { main: them } */
650
- export interface FixedCameraOptions extends Partial<CameraShot> {
651
- /** Art-pixel rounding, orthographic only: rounds the camera on screen axes, clamps to bounds there first, and decides the view height (buffer height / pixelsPerMeter), so no size with it. Recipe 62 section 4b */
652
- pixelSnap?: { pixelsPerMeter: number; bounds?: import('./pixel').PixelBounds | null };
653
- /** Shots: name → shot */
654
- shots?: Record<string, CameraShot>;
655
- /** Initial shot name */
656
- start?: string | null;
657
- /** Automatic switching: false | 'nearest' (pick the one nearest to the player) */
658
- auto?: false | 'nearest';
659
- /** Check interval for automatic switching (seconds) @experimental */
660
- autoInterval?: number;
661
- /** How many meters closer a new shot must be to switch (prevents flipping back and forth) */
662
- hysteresis?: number;
663
- /** Transition seconds for trigger-zone switches (0 = hard cut) @experimental */
664
- triggerBlend?: number;
665
- /** How high above the character a track shot looks (meters) @experimental */
666
- trackHeight?: number;
667
- /** Head-follow smoothing @experimental */
668
- trackSmoothing?: number;
669
- /** Keep the direction when switching shots until the direction key is released @experimental */
670
- holdDirection?: boolean;
671
- /** Transition easing */
672
- ease?: Ease;
673
- }
674
- /** Fixed-shot camera */
675
- export interface FixedCamera extends CameraRigBase {
676
- /** All shots. A shot stays where it was placed: for a view that pans at a fixed angle use followCamera({ mouseLook: false }) (recipe 21 section 6) */
677
- shots: Record<string, any>;
678
- /** Current shot name */
679
- current: string | null;
680
- auto: false | 'nearest';
681
- autoInterval: number;
682
- hysteresis: number;
683
- triggerBlend: number;
684
- trackHeight: number;
685
- trackSmoothing: number;
686
- holdDirection: boolean;
687
- ease: Ease;
688
- /** Add / replace a shot */
689
- add(name: string, shot: CameraShot): this;
690
- /** Cut to a shot immediately */
691
- cut(name: string): void;
692
- /** Transition smoothly to a shot ({ seconds = 1, ease }); the Promise resolves when done */
693
- blend(name: string, opts?: { seconds?: number; ease?: Ease }): Promise<void>;
694
- /** Name of the shot nearest to a point */
695
- nearest(p: Vector3): string | null;
696
- }
697
-
698
- export interface RtsCameraOptions {
699
- /** Camera height above the focus (meters), default 30 */
700
- height?: number;
701
- /** Zoom range (meters) */
702
- minHeight?: number;
703
- maxHeight?: number;
704
- /** Pitch down angle (radians, π/2 = straight down), default 0.95 */
705
- pitch?: number;
706
- /** Initial horizontal heading (radians) */
707
- yaw?: number;
708
- /** Pan speed multiplier @experimental */
709
- panSpeed?: number;
710
- /** Drag with the mouse to pan, default true @experimental */
711
- dragPan?: boolean;
712
- /** Pan at the screen edge, default false @experimental */
713
- edgePan?: boolean;
714
- /** Edge width (fraction of the screen) @experimental */
715
- edgeSize?: number;
716
- /** Focus range (meters) */
717
- bounds?: { minX?: number; maxX?: number; minZ?: number; maxZ?: number } | null;
718
- /** false: no turning. Default true: declares the actions rotateLeft / rotateRight (no keys; presets.bindings.rtsRotate binds Q / R) */
719
- rotate?: boolean;
720
- /** Rotation speed (radians/second) @experimental */
721
- rotateSpeed?: number;
722
- /** Zoom ratio per wheel notch @experimental */
723
- zoomStep?: number;
724
- /** Smoothing @experimental */
725
- smoothing?: number;
726
- /** Field of view (degrees); unchanged if omitted */
727
- fov?: number | null;
728
- /** Manual panning is not allowed while following @experimental */
729
- followLock?: boolean;
730
- /** Initial focus (position) */
731
- start?: PositionLike | null;
732
- }
733
- /** Strategy top-down camera */
734
- export interface RtsCamera extends CameraRigBase, Required<Omit<RtsCameraOptions, 'rotate' | 'fov' | 'start'>> {
735
- /** Is it following target */
736
- following: boolean;
737
- /** Focus (on the ground) */
738
- focus: Vector3;
739
- /** Can it rotate */
740
- rotate: boolean;
741
- /** Move the view to position (instant: true skips smoothing) */
742
- moveTo(position: PositionLike, opts?: { instant?: boolean }): void;
743
- }
744
-
745
- /**
746
- * engine.cameraRig: one of four cameras. The shared methods (follow, forward, right) always work;
747
- * properties specific to one camera (distance, cut(), moveTo()…) only exist when that camera is installed.
748
- */
749
- export type CameraRig = CameraRigBase
750
- & Partial<Omit<FollowCamera, keyof CameraRigBase>>
751
- & Partial<Omit<FirstPersonCamera, keyof CameraRigBase | 'height' | 'smoothing'>>
752
- & Partial<Omit<FixedCamera, keyof CameraRigBase | 'trackHeight' | 'add' | 'ease' | 'auto'>>
753
- & Partial<Omit<RtsCamera, keyof CameraRigBase | 'height' | 'smoothing' | 'focus'>>
754
- & {
755
- /** Fixed shot: add a shot */
756
- add?(name: string, shot: CameraShot): any;
757
- ease?: Ease;
758
- auto?: false | 'nearest';
759
- };
760
-
761
- /** Fixed-shot switch event */
762
- export interface CameraShotEvent { name: string }
763
-
764
- export type CameraModule = ModuleDef<CameraRig>;
1
+ // Collision, real physics, camera.
2
+ import type { Object3D, Vector3, DirXZ, Vec3Like, Ease, Handle, PositionLike } from './common';
3
+ import type { Engine, ModuleDef } from './core';
4
+ import type { Input } from './generated/core/input/Input';
5
+ import type { Character } from './gameplay';
6
+
7
+ // ======================================================================
8
+ // Lightweight collision collision() → engine.collision
9
+ // ======================================================================
10
+
11
+ export interface CollisionOptions {
12
+ /** Max walkable slope (height difference / horizontal distance), default 1.1 */
13
+ maxClimb?: number;
14
+ /** A camera above this height (meters) is not considered blocked by trees, default 5 */
15
+ canopyHeight?: number;
16
+ /** Margin between the camera and obstacles (meters), default 0.5 @experimental */
17
+ cameraPad?: number;
18
+ /** Nearest camera distance (meters), default 1.5 */
19
+ cameraMin?: number;
20
+ /** Height above the water surface (meters) at which it counts as walkable, default 0.2 @experimental */
21
+ walkableWaterMargin?: number;
22
+ /** What camera occlusion checks: 'both' (default) | 'colliders' | 'meshes' = static meshes registered with engine.rays.addStatic(mesh, { occluder: true }) */
23
+ cameraOcclusion?: 'colliders' | 'meshes' | 'both';
24
+ }
25
+ /** Circle collider: center x/z, radius r, height h (meters), occ false when added with occluder: false */
26
+ export interface CircleCollider { x: number; z: number; r: number; h: number; occ: boolean }
27
+ /** Box collider: center x/z, half width hw, half depth hd, rotation around Y rot (radians), height h, bottom height y (meters), occ as in CircleCollider */
28
+ export interface BoxCollider { x: number; z: number; hw: number; hd: number; rot: number; h: number; y?: number; occ: boolean; [k: string]: any }
29
+
30
+ /** Parameters of addCircle() (meters) */
31
+ export interface CircleColliderOptions {
32
+ /** Radius, default 0.5 */
33
+ radius?: number;
34
+ /** Height, default 6 */
35
+ height?: number;
36
+ /** false: walkers are still stopped but the follow camera's occlusion check ignores it (forest trunks the camera may pass through). Default true */
37
+ occluder?: boolean;
38
+ }
39
+ /** Parameters of addBox() (meters, radians) */
40
+ export interface BoxColliderOptions {
41
+ /** Half width (X direction), default 1 */
42
+ halfWidth?: number;
43
+ /** Half depth (Z direction), default 1 */
44
+ halfDepth?: number;
45
+ /** Rotation around the Y axis (radians), default 0 */
46
+ rotation?: number;
47
+ /** Height, default 6 */
48
+ height?: number;
49
+ /** Bottom height of the box; if omitted it sits on the ground (give it for walls placed on platforms in a level) */
50
+ y?: number;
51
+ /** false: walkers are still stopped but the follow camera's occlusion check ignores it (forest trunks the camera may pass through). Default true */
52
+ occluder?: boolean;
53
+ }
54
+
55
+ /** engine.collision (lightweight collision: no walking through things, the camera is not blocked). Real physics is a separate module, engine.rigid */
56
+ export interface Collision {
57
+ /** @experimental */ maxClimb: number;
58
+ /** @experimental */ canopyHeight: number;
59
+ /** @experimental */ cameraPad: number;
60
+ /** @experimental */ cameraMin: number;
61
+ /** @experimental */ walkableWaterMargin: number;
62
+ /** What camera occlusion checks (see CollisionOptions.cameraOcclusion) @experimental */
63
+ cameraOcclusion: 'colliders' | 'meshes' | 'both';
64
+ /** +1 each time a static collider is added or removed @experimental */
65
+ version: number;
66
+ /** Add a circle collider (pillar, campfire): position is the center, e.g. addCircle(mesh, { radius: 1 }). Returns a handle { remove() } */
67
+ addCircle(position: PositionLike, opts?: CircleColliderOptions): Handle;
68
+ /** Add a box collider (house, fence): position is the center, e.g. addBox(house, { halfWidth: 3, halfDepth: 2, rotation: 0.3 }). Returns a handle { remove() } */
69
+ addBox(position: PositionLike, opts?: BoxColliderOptions): Handle;
70
+ /** Add a thin wall along a -> b (fence). Options: thickness (default 0.3), height, y, occluder (as in addBox). A gap between segments is a gate. Returns a handle { remove() } */
71
+ addSegment(a: PositionLike, b: PositionLike, opts?: { thickness?: number; height?: number; y?: number; occluder?: boolean }): Handle;
72
+ /** Mark ground impassable where fn(x, z) is true (river, lava); fn must be pure (no side effects, same answer for the same (x, z)); reading engine.ground in it is fine. findPathAsync caches the answers, so after the ground or your own state changes, remove() and add the field again. bounds { minX, maxX, minZ, maxZ } (world metres, the field's x / z extent) skips fn outside it; give it to keep findPathAsync's ground sampling cheap. Returns a handle { remove() } */
73
+ addBlocked(fn: (x: number, z: number) => boolean, opts?: { bounds?: { minX: number; maxX: number; minZ: number; maxZ: number } }): Handle;
74
+ /** Is a character of this radius touching addBlocked ground at (x, z) @experimental */
75
+ blockedAt(x: number, z: number, radius?: number): boolean;
76
+ /** Add a collider from an object's bounding box, pad expands outward (meters), occluder as in addBox. Returns a handle { remove() } */
77
+ addObject(obj: Object3D, opts?: { pad?: number; occluder?: boolean }): Handle;
78
+ /** Iterate all static colliders added by hand @experimental */
79
+ forEachStatic(fn: (type: 'box' | 'circle', data: any) => void): void;
80
+ /** Keep an outside copy of the static colliders in step (physics colliders, navmesh obstacles): add builds one piece, remove drops one; sync() diffs only when colliders changed and returns whether it compared; clear() forgets every piece without remove (the outside world was thrown away) @experimental */
81
+ mirror<P>(fns: { add(type: 'box' | 'circle', data: any): P; remove(piece: P, data: any): void }): { sync(): boolean; clear(): void; readonly size: number };
82
+ /** Whether someone can stand at this position (for pathfinding): not in water, not too steep, not inside an obstacle. radius is the character radius (meters, default engine.movement.radius) */
83
+ walkable(position: PositionLike, opts?: { radius?: number }): boolean;
84
+ /** walkable with plain numbers, allocating nothing (A* inner loops); radius defaults to engine.movement.radius */
85
+ walkableAt(x: number, z: number, radius?: number): boolean;
86
+ /** Line of sight with height: is the 3D segment a -> b free of boxes, circles and terrain trees? radius fattens the line; addBlocked water is ignored. Give eye heights in a / b */
87
+ lineClear(a: PositionLike, b: PositionLike, opts?: { radius?: number; /** who is looking (names the line in the event trace) */ who?: string }): boolean;
88
+ }
89
+
90
+ // ======================================================================
91
+ // Real physics rigid() → engine.rigid
92
+ // ======================================================================
93
+
94
+ export interface RigidOptions {
95
+ /** Gravity (m/s², negative points down), default -9.81 */
96
+ gravity?: number;
97
+ /** How many rings of chunks around the player get terrain colliders, default 1. A body outside them freezes until the player comes near (entry.enabled false, describe().rigid.frozen), because it would fall through the ground: raise this for a car or ball that must keep moving far away */
98
+ terrainRing?: number;
99
+ /** Whether there is buoyancy, default true */
100
+ buoyancy?: boolean;
101
+ /** Buoyancy strength (1 = just floats), default 1.6 @experimental */
102
+ buoyancyForce?: number;
103
+ /** Drag in water, default 2.5 @experimental */
104
+ waterDrag?: number;
105
+ /** Buoyancy "waterline": an object starts floating when its center is this many meters below the water surface, default 0.3 @experimental */
106
+ floatLine?: number;
107
+ /** Buoyancy reaches its maximum this many meters further down, default 0.8 @experimental */
108
+ floatDepth?: number;
109
+ /** Height (meters) of vegetation collision pillars (tree trunks), default 6 @experimental */
110
+ treeColliderHeight?: number;
111
+ /** Trunks get collision cylinders only in chunks within this many meters of the player or a moving rigid body (the rest are covered by engine.collision for characters), default 16 @experimental */
112
+ treeRadius?: number;
113
+ /** Player capsule size (meters), default computed from engine.movement radius / height @experimental */
114
+ playerCapsule?: { halfHeight: number; radius: number };
115
+ /** The flat plane at y = 0 when the ground has no collision of its own, default true. false: only your own bodies and colliders are there (a sky of islands) */
116
+ fallbackFloor?: boolean;
117
+ }
118
+ /** Parameters for adding a physics body */
119
+ export interface RigidBodyOptions {
120
+ /** Stable id (e.g. the world record id): saves keep this body's pose, rotation, velocities and sleep under it, and a load hands them back to the body with this id, also one built after the load. Without an id the body is not saved. Unique among live bodies and vehicles */
121
+ id?: string;
122
+ /** Mass (kilograms), default 1 */
123
+ mass?: number;
124
+ /** Friction, default 0.7 */
125
+ friction?: number;
126
+ /** Restitution 0–1, default 0.1 */
127
+ restitution?: number;
128
+ /** Linear damping, default 0.05 */
129
+ damping?: number;
130
+ /** Angular damping, default 0.1 */
131
+ angularDamping?: number;
132
+ /** Fixed in place (only blocks other things) */
133
+ fixed?: boolean;
134
+ }
135
+ /** Parameters of addBox() */
136
+ export interface RigidBoxOptions extends RigidBodyOptions {
137
+ /** Size [width, height, depth] (meters); if omitted, taken from the model's bounding box */
138
+ size?: number[];
139
+ }
140
+ /** Parameters of addBall() */
141
+ export interface RigidBallOptions extends RigidBodyOptions {
142
+ /** Radius (meters); if omitted, taken from the model's bounding box */
143
+ radius?: number;
144
+ }
145
+ /** A physics body (the handle returned by addBox / addBall / addHull) */
146
+ export interface RigidEntry extends Handle {
147
+ /** The id it was added with (saves name it by this), undefined without one */
148
+ readonly id?: string;
149
+ /** Rapier rigid body (translation(), mass(), setLinvel()…); newGame / a load rebuild the world, so read entry.body again instead of keeping it */
150
+ body: any;
151
+ /** Rapier collider */
152
+ collider: any;
153
+ /** The matching three.js model (position is written by physics every step) */
154
+ mesh: Object3D;
155
+ /** Same as mesh */
156
+ object: Object3D;
157
+ /** Whether it is being simulated: false while it is outside the terrain colliders (rigid({ terrainRing })), where it would fall through the ground */
158
+ enabled: boolean;
159
+ /** Volume (cubic meters, used for buoyancy) */
160
+ volume: number;
161
+ damping: number;
162
+ angularDamping: number;
163
+ wet?: boolean;
164
+ /** Remove this rigid body (the model was passed in by you and is not deleted; call engine.remove(entry.object) when done). Casting / receiving shadows follows the model's own castShadow / receiveShadow */
165
+ remove(): void;
166
+ }
167
+
168
+ /** Options of engine.rigid.ragdoll @experimental */
169
+ export interface RagdollOptions {
170
+ /** A push (kg*m/s) on the part nearest position, else on the root part. A hit stronger than the part can take spreads to the whole body, total momentum unchanged */
171
+ impulse?: Vec3Like;
172
+ /** Where the push lands (world) */
173
+ position?: PositionLike;
174
+ /** Humanoid graph only: part -> bone name or bone, over the auto-detection. Parts: hips, chest, head, upperArmL, lowerArmL, upperArmR, lowerArmR, upperLegL, lowerLegL, upperLegR, lowerLegR */
175
+ bones?: Record<string, string | Object3D>;
176
+ /** Part or kind ('lowerLeg', 'upperArm', 'chest', 'head'...) -> [min, max] radians from the bind pose: bend forward (a knee: backward), side, twist along the bone */
177
+ limits?: Record<string, { bend?: [number, number]; side?: [number, number]; twist?: [number, number] }>;
178
+ /** Whole body, kg (default the graph's; humanoid 70). The graph's proportions stay */
179
+ mass?: number;
180
+ }
181
+
182
+ /** One part of a ragdoll graph, the value of the rule 'ragdoll.graph': { body: { bone: 'Spine' }, tail: { bone: 'Tail1', parent: 'body', mass: 2 } } @experimental */
183
+ export interface RagdollPart {
184
+ /** Bone name or bone */
185
+ bone: string | Object3D;
186
+ /** The part this one hangs from; its bone must be above this bone. Exactly one part has none: the root, which leads the body */
187
+ parent?: string;
188
+ /** Range of motion, [min, max] radians from the bind pose; default loose (45° bend and side, 30° twist) */
189
+ limits?: { bend?: [number, number]; side?: [number, number]; twist?: [number, number] };
190
+ /** kg; default 70 shared equally */
191
+ mass?: number;
192
+ /** The part this bone points at; default the middle of its child parts, then its first child bone. 'top' measures it from the mesh along up (a head) */
193
+ end?: string;
194
+ /** Which way a positive bend moves the tip, in bind space; default [0, 0, 1] */
195
+ forward?: Vec3Like;
196
+ /** Fallback for forward and the direction of end: 'top'; default [0, 1, 0] */
197
+ up?: Vec3Like;
198
+ /** Name shared by several parts, so one limits entry of rigid.ragdoll covers them ('leg') */
199
+ kind?: string;
200
+ }
201
+
202
+ /** What engine.rigid.ragdoll returns. remove() gives the character back; safe to call twice @experimental */
203
+ export interface Ragdoll extends Handle {
204
+ /** False once removed (remove(), a load, the character deleted) */
205
+ readonly active: boolean;
206
+ /** Every part is at rest (asleep or frozen). Nothing is written to the bones then, so a game's own bone write stays */
207
+ readonly settled: boolean;
208
+ /** Part name -> its rigid entry: entry.body for forces, entry.object is the bone; engine.raycast hits carry the same entry. The bones stay plain three.js */
209
+ readonly parts: Record<string, RigidEntry>;
210
+ }
211
+
212
+ /** A hit of Collider3D.sweep */
213
+ export interface SweepHit {
214
+ /** The ball's center at the hit */
215
+ point: Vector3;
216
+ /** World direction out of what it hit */
217
+ normal: Vector3;
218
+ /** How far the ball got (meters) */
219
+ distance: number;
220
+ }
221
+ /** engine.collider3d: collision on all three axes (modules/rigid/collider3d.contract.js). rigid provides it; engine.use(mine(), { replaces: 'collider3d' }) swaps in your own @experimental */
222
+ export interface Collider3D {
223
+ /** A fixed solid turned any way. size [x, y, z] for a box or radius for a ball; rotation [x, y, z] radians or a quaternion. Callable before start(); newGame and a load keep it. engine.collision does not know it */
224
+ addSolid(opts: { position: PositionLike; size?: number[]; radius?: number; rotation?: number[] | { x: number; y: number; z: number; w: number }; friction?: number }): Handle;
225
+ /** Is a ball here inside something solid. Skips the player's capsule */
226
+ overlap(position: PositionLike, radius?: number): boolean;
227
+ /** Move a ball from there to there: null when clear, else the first hit. Skips the player's capsule */
228
+ sweep(from: PositionLike, to: PositionLike, radius?: number): SweepHit | null;
229
+ }
230
+
231
+ /** engine.rigid (real physics; bodies can only be added after start(), or in the engine:ready event) */
232
+ export interface RigidBodies {
233
+ /** Is the physics engine ready (downloaded and initialized at start()) */
234
+ readonly ready: boolean;
235
+ /** All physics bodies */
236
+ bodies: RigidEntry[];
237
+ gravity: number;
238
+ /** @experimental */ terrainRing: number;
239
+ /** @experimental */ buoyancy: boolean;
240
+ /** @experimental */ buoyancyForce: number;
241
+ /** @experimental */ waterDrag: number;
242
+ /** @experimental */ floatLine: number;
243
+ /** @experimental */ floatDepth: number;
244
+ /** @experimental */ treeColliderHeight: number;
245
+ /** @experimental */ treeRadius: number;
246
+ /** The Rapier library itself: its shape follows the Rapier version @experimental */
247
+ rapier: any;
248
+ /** The Rapier world: its shape follows the Rapier version @experimental */
249
+ world: any;
250
+ /** Add a box (crate). Physics is ready after engine.start() (or on engine:ready): called before, it throws in development, a release build warns once and returns null */
251
+ addBox(mesh: Object3D, opts?: RigidBoxOptions): RigidEntry | null;
252
+ /** Add a ball; null only as in addBox: a release build, called before physics is ready @experimental */
253
+ addBall(mesh: Object3D, opts?: RigidBallOptions): RigidEntry | null;
254
+ /** Add a convex hull (irregular objects such as rocks and barrels); null only as in addBox: a release build, called before physics is ready @experimental */
255
+ addHull(mesh: Object3D, opts?: RigidBodyOptions): RigidEntry | null;
256
+ /**
257
+ * Turn a skinned character limp in one call; rd.remove() returns it to animation. who: a Character, an NPC handle, a character id or a skinned Object3D.
258
+ * Its mover, animator, capsule and camera yield until then; calling again on the same one pushes it again and returns the same ragdoll.
259
+ * Not saved: any load ends it. A skeleton it cannot read throws, naming the missing parts. The rule 'ragdoll.graph' (per character id) gives the parts: 'humanoid' (default),
260
+ * Record<string, RagdollPart> for any other body, a function (facts: { character, root, mesh }, engine) => one of those, or false for no ragdoll (returns null). @experimental
261
+ */
262
+ ragdoll(who: any, opts?: RagdollOptions): Ragdoll | null;
263
+ /** Give it a push: impulse vector impulse (Vector3 / [x, y, z] / { x, y, z }), e.g. impulse(ball, [0, 3, 5]) */
264
+ impulse(entry: RigidEntry, impulse: Vec3Like): void;
265
+ /** Teleport to position (velocity is zeroed) */
266
+ setPosition(entry: RigidEntry, position: PositionLike): void;
267
+ /** The player's Rapier kinematic body and capsule collider (follow the player position every step; used for collision when mover: 'rapier'; the capsule is off while driving) @experimental */
268
+ playerBody: any;
269
+ /** The capsule collider on playerBody @experimental */
270
+ playerCollider: any;
271
+ /** Player capsule size (meters) @experimental */
272
+ playerCapsule: { halfHeight: number; radius: number };
273
+ /** All vehicles @experimental */
274
+ vehicles: Vehicle[];
275
+ /**
276
+ * Turn a model into a wheeled vehicle (Rapier ray-cast vehicle controller: cars, karts, carts); remove it with vehicle.remove() (anyone inside gets out
277
+ * first). Before physics is ready it throws in development (release: warns, null), like addBox. Boats, mounts and mechs are the game's own objects with the same seat interface
278
+ */
279
+ addWheeled(mesh: Object3D, opts: VehicleOptions): Vehicle | null;
280
+ /** Statistics */
281
+ readonly stats: { bodies: number; active: number; colliders: number };
282
+ }
283
+
284
+ // ---------- Vehicles ----------
285
+ /** A wheel: position relative to the body (meters), radius (meters), steer can steer, drive is powered, object is the wheel model that spins */
286
+ export interface VehicleWheel { position: Vec3Like; radius: number; steer?: boolean; drive?: boolean; object?: Object3D }
287
+ /** Parameters of rigid.addWheeled() */
288
+ export interface VehicleOptions {
289
+ /** Stable id (default 'vehicle1', 'vehicle2'... in creation order): saves name the player's vehicle and the vehicle's body state by it; give one when the creation order varies */
290
+ id?: string;
291
+ /** Wheels (at least 3) */
292
+ wheels: VehicleWheel[];
293
+ /** Mass (kilograms) */
294
+ mass?: number;
295
+ /** Throttle force, default 800 */
296
+ engineForce?: number;
297
+ /** Brake force, default 20 */
298
+ brakeForce?: number;
299
+ /** Max steering angle (radians), default 0.5 */
300
+ maxSteer?: number;
301
+ /** Suspension: rest natural length (meters), stiffness, damping */
302
+ suspension?: { rest?: number; stiffness?: number; damping?: number };
303
+ /** Seat positions relative to the body (meters): the first drives, the rest ride; each gets out beside its own seat. Default one at the body center */
304
+ seats?: Vec3Like[];
305
+ /** Hide whoever sits in it, default true; false keeps riders visible on their seats, turning with the vehicle (bikes, open carts, karts) */
306
+ hideDriver?: boolean;
307
+ /** Camera distance and height while driving (meters) */
308
+ camera?: { distance?: number; height?: number };
309
+ /** Body collision box size [width, height, depth] (meters); if omitted, taken from the model's bounding box (wheels excluded) */
310
+ size?: number[];
311
+ /** Tire grip, default 1.5 */
312
+ friction?: number;
313
+ /** Distance from the side of the body when getting out (meters), default 0.8 */
314
+ exitOffset?: number;
315
+ }
316
+ /** A vehicle (returned by rigid.addWheeled, faces the model's +Z). player.enter(vehicle) gets in; with interactions installed, press the interact key nearby to get in / out */
317
+ export interface Vehicle extends RigidEntry, Rideable {
318
+ /** Stable id (rigid.addWheeled({ id })); saves name the player's vehicle by it */
319
+ readonly id: string;
320
+ /** Body model (the mesh you passed in) */
321
+ object: Object3D;
322
+ /** Rapier rigid body */
323
+ body: any;
324
+ /** Rapier vehicle controller (DynamicRayCastVehicleController) */
325
+ controller: any;
326
+ wheels: VehicleWheel[];
327
+ seats: number;
328
+ passengers: Character[];
329
+ hideDriver: boolean;
330
+ /** World position of a seat (default 0, the driver's) */
331
+ seatPosition(seat?: number): Vector3;
332
+ /** Where to get out of a seat (outside the door on that seat's side, world coordinates) */
333
+ exitPosition(seat?: number, n?: number): Vector3;
334
+ }
335
+ /**
336
+ * What character.enter(vehicle) needs from anything it rides (modules/characters/vehicle.contract.js): rigid.addWheeled's car passes it, and so does a
337
+ * game's own boat, horse, mech or lift built on three.js or another physics library.
338
+ */
339
+ export interface Rideable {
340
+ /** Stable id when saves should put the player back in it (rigid vehicles have one) */
341
+ readonly id?: string;
342
+ /** What the camera follows while driving */
343
+ object: Object3D;
344
+ /** Current speed (m/s): the driver's moveAmount (animation, describe) */
345
+ readonly speed: number;
346
+ /** Who is driving (null if nobody); character.enter / exit set it */
347
+ driver: Character | null;
348
+ /** Number of seats, driver included (default 1); enter takes the driver seat, else the first free passenger seat */
349
+ seats?: number;
350
+ /** Who rides in the other seats (enter creates the list when missing) */
351
+ passengers?: Character[];
352
+ /** false keeps riders visible on their seats (bikes, open carts); default hidden */
353
+ hideDriver?: boolean;
354
+ /** Camera parameters while driving */
355
+ camera?: { distance?: number; height?: number };
356
+ /** Controls, called every fixed step while driven: throttle -1..1, steer -1..1 (right is positive), brake 0–1; exit calls drive(0, 0, 1) */
357
+ drive(throttle: number, steer: number, brake?: number): void;
358
+ /** World position of a seat (default 0, the driver's; a rider is kept there) */
359
+ seatPosition(seat?: number): Vector3 | Vec3Like;
360
+ /** Where to get out of a seat (world coordinates; rigid cars: outside the door on that seat's side) */
361
+ exitPosition(seat?: number, n?: number): Vector3 | Vec3Like;
362
+ }
363
+
364
+ // ======================================================================
365
+ // Skeletal animation state machine Animator (returned by engine.assets.animate)
366
+ // ======================================================================
367
+
368
+ /** An animation state: clip is the clip name; or blend is a blend tree (blends several clips by the param parameter); loop: false is a one-shot clip */
369
+ export interface AnimatorState {
370
+ /** Clip name (the clip name in the glTF) */
371
+ clip?: string;
372
+ /** Blend tree: at the parameter value at it is fully this clip, in between they blend proportionally, e.g. [{ clip: 'Walk', at: 1.5 }, { clip: 'Run', at: 6 }] */
373
+ blend?: { clip: string; at: number }[];
374
+ /** Which parameter the blend tree reads (set by anim.set), default 'speed' */
375
+ param?: string;
376
+ /** Align the strides of blended clips, default true */
377
+ sync?: boolean;
378
+ /** Loop, default true; with false the anim:end event fires when it finishes */
379
+ loop?: boolean;
380
+ /** Which state a one-shot clip goes to when it finishes */
381
+ then?: string;
382
+ /** go() cannot interrupt it while playing */
383
+ lock?: boolean;
384
+ /**
385
+ * For sync(): gameplay seconds -> clip seconds. A number = the gameplay length the whole clip is stretched over;
386
+ * [[gameT, clipT], ...] = piecewise linear (land the swing on the hit phase). Without it clip seconds = t
387
+ */
388
+ timing?: number | [number, number][];
389
+ }
390
+ /** What an Animator is showing (anim.describe(), describe().player.anim) */
391
+ export interface AnimatorInfo {
392
+ state: string | null;
393
+ /** Clip name as written in the state */
394
+ clip: string | null;
395
+ /** Clip seconds */
396
+ time: number;
397
+ /** 0-1 through the clip */
398
+ progress: number;
399
+ /** true while sync() drives it */
400
+ driven: boolean;
401
+ /** Last gameplay t passed to sync (only while driven) */
402
+ t?: number;
403
+ /** Share of each fading state (sums to 1) */
404
+ weights: Record<string, number>;
405
+ }
406
+ /** Animation state machine parameters */
407
+ export interface AnimatorOptions {
408
+ /** Default transition seconds, default 0.25 (characters({ animation: { fade } }) for every character) */
409
+ fade?: number;
410
+ /** States: name → state */
411
+ states?: Record<string, AnimatorState>;
412
+ /** Transition seconds for specific pairs: { 'jump>fall': 0.1, '*>idle': 0.3 } */
413
+ transitions?: Record<string, number>;
414
+ /** Initial parameter values */
415
+ params?: Record<string, number>;
416
+ }
417
+ /** Skeletal animation state machine (returned by engine.assets.animate(model, config)) */
418
+ export declare class Animator {
419
+ constructor(engine: Engine, root: Object3D, opts?: AnimatorOptions);
420
+ /** The animated object */
421
+ root: Object3D;
422
+ /** three.js AnimationMixer */
423
+ mixer: any;
424
+ /** clip name → three.js AnimationAction */
425
+ actions: Map<string, any>;
426
+ /** Current state name */
427
+ state: string | null;
428
+ /** State configuration (states can be added directly) */
429
+ states: Record<string, AnimatorState>;
430
+ /** Parameters (used by blend trees) */
431
+ params: Record<string, number>;
432
+ /** Set a parameter, e.g. set('speed', 3) */
433
+ set(param: string, value: number): this;
434
+ /** Switch to a state ({ fade }: transition seconds); null (dev warning) if there is no such state / clip; ignored while sync() drives a state */
435
+ go(state: string, opts?: { fade?: number }): any;
436
+ /** One-shot clip: state name or clip name, returns to then or the previous state when done; go() cannot interrupt it while playing */
437
+ action(name: string, opts?: { fade?: number }): any;
438
+ /**
439
+ * Gameplay drives the clock: show state at gameplay time t (fixed-step seconds) through its timing.
440
+ * The clip never advances or ends by itself and go() leaves it alone; sync(null) hands control back
441
+ */
442
+ sync(state: string | null, t?: number): any;
443
+ /** What is showing: state, clip, clip time, progress, driven, weights */
444
+ describe(): AnimatorInfo;
445
+ /**
446
+ * Check the mapping against the action names the game plays: each problem as text with its fix ([] = all will play).
447
+ * @example anim.check(['idle', 'walk', 'attack', 'hurt'])
448
+ */
449
+ check(actions?: string[]): string[];
450
+ /** Stop the per-frame update when no longer needed */
451
+ dispose(): void;
452
+ }
453
+
454
+ // ======================================================================
455
+ // Camera → engine.cameraRig (install one kind, switch at runtime with engine.setCamera)
456
+ // ======================================================================
457
+
458
+ /** Camera kinds: 'follow' third person | 'firstPerson' first person | 'fixed' fixed shot | 'rts' strategy top-down */
459
+ export type CameraKind = 'follow' | 'firstPerson' | 'fixed' | 'rts';
460
+
461
+ /** Interface shared by all cameras */
462
+ export interface CameraRigBase {
463
+ /** Current kind (the first argument of engine.setCamera) */
464
+ kind: CameraKind;
465
+ /** The object being followed */
466
+ target: Object3D | null;
467
+ /** The pixelSnap option at work, or null: grid (give it to pixelSprite), error (last rounding in art pixels), agrees (false: something else set the view height, rounding stopped) */
468
+ pixelSnap?: { readonly grid: import('./pixel').PixelGrid; readonly error: { x: number; y: number }; readonly agrees: boolean; bounds: import('./pixel').PixelBounds | null } | null;
469
+ /** Follow someone (called automatically when the player is created), null to cancel. opts temporarily changes distance / height (used while driving), restored when the target changes */
470
+ follow(obj: Object3D | null, opts?: { distance?: number; height?: number }): void;
471
+ /** The "forward" direction on the horizontal plane (player movement is relative to it) */
472
+ forward(): DirXZ;
473
+ /** The "right" direction on the horizontal plane */
474
+ right(): DirXZ;
475
+ /** Where the world loads around (the followed object's position, else the camera's) */
476
+ focusPoint(): Vector3;
477
+ /** Screen coordinates (-1..1, engine.input.pointer.ndcX / ndcY) → the point on the ground under it, null if nothing is hit (every camera kind) */
478
+ screenToGround(ndcX: number, ndcY: number): Vector3 | null;
479
+ /** Update the camera every frame */
480
+ update(dt: number, input: Input): void;
481
+ /** Called when a cutscene takeover starts / ends */
482
+ onOverride?(on: boolean): void;
483
+ /** Called when this camera is switched in (switched: switched at runtime) */
484
+ onEnter?(switched?: boolean): void;
485
+ /** Called when this camera is switched out */
486
+ onExit?(): void;
487
+ }
488
+
489
+ export interface FollowCameraOptions {
490
+ /** 'orthographic' draws without perspective (isometric / 2.5D; the wheel then changes size); default 'perspective' */
491
+ projection?: 'perspective' | 'orthographic';
492
+ /** With projection 'orthographic': world units of view height, default 20 */
493
+ size?: number;
494
+ /** Which side of the focus the camera sits on (radians), default 0.8: camera = focus + (sin yaw, cos yaw) × distance, it looks along forward() = -(sin yaw, cos yaw). Behind a character facing f: yaw = f + PI */
495
+ yaw?: number;
496
+ /** Pitch angle (radians), default 0.42. Positive = camera above the look point, looking down: the opposite of firstPersonCamera's pitch */
497
+ pitch?: number;
498
+ /** Distance (meters), default 13 */
499
+ distance?: number;
500
+ /** Zoom range (meters) */
501
+ minDistance?: number;
502
+ maxDistance?: number;
503
+ /** How high above the character to look at (meters), default 1.4 */
504
+ height?: number;
505
+ /** Follow smoothing, default 10 @experimental */
506
+ smoothing?: number;
507
+ /** Drag sensitivity, default 1 */
508
+ sensitivity?: number;
509
+ /** Pitch range (radians), default 0.05 to 1.35. The camera never goes below the look point, so the view cannot look up (a tall building's roof stays out of sight); a negative minPitch looks up (recipe 21 section 4b) */
510
+ minPitch?: number;
511
+ /** Upper pitch limit (looking down), default 1.35 (about 77 degrees, not straight down) @experimental */ maxPitch?: number;
512
+ /** Zoom ratio per wheel notch, default 0.1 @experimental */
513
+ zoomStep?: number;
514
+ /** Minimum camera height above the ground (meters), default 1.2 @experimental */
515
+ groundClearance?: number;
516
+ /** Invert vertical @experimental */
517
+ invertY?: boolean;
518
+ /** Lock the pitch angle (top-down games) */
519
+ lockPitch?: boolean;
520
+ /** Over-the-shoulder offset: meters to the right of the target the camera aims (negative = left shoulder), default 0 */
521
+ shoulder?: number;
522
+ /** Click locks the mouse; mouse motion turns the view without dragging (Esc releases), default false */
523
+ pointerLock?: boolean;
524
+ /** The press that locks the mouse is not delivered as Mouse0 / a click (default true); false delivers it too */
525
+ swallowLockClick?: boolean;
526
+ /**
527
+ * What happens when the camera would go below the ground. 'raise': lift it (the view direction changes, so you cannot look up from flat ground);
528
+ * 'shorten': pull it along the arm toward the look point (the view direction is kept, a negative minPitch really looks up); 'none': leave it;
529
+ * a function gets the facts and returns the camera position (or null to keep it). Default: 'shorten' when minPitch < 0, else 'raise'
530
+ */
531
+ ground?: 'raise' | 'shorten' | 'none' | ((facts: FollowCameraGroundFacts) => Vec3Like | null | void);
532
+ /** false: the built-in mouse / stick look and wheel zoom are off, the game drives the view with setView() (default true) */
533
+ mouseLook?: boolean;
534
+ /** Hide the followed object from the camera when the camera is closer than this to the look point (meters, 0 = never; default 0.9). The shadow stays */
535
+ hideTargetNear?: number;
536
+ /** Layer used to hide the followed object (0-31), default 30 */
537
+ hideLayer?: number;
538
+ /** Art-pixel rounding, orthographic only: rounds the camera on screen axes, clamps to bounds there first, and decides the view height (buffer height / pixelsPerMeter), so no size with it. Recipe 62 section 4b */
539
+ pixelSnap?: { pixelsPerMeter: number; bounds?: import('./pixel').PixelBounds | null };
540
+ }
541
+ /** What a followCamera({ ground: fn }) function receives each frame */
542
+ export interface FollowCameraGroundFacts {
543
+ /** Camera position after wall avoidance (a copy) */
544
+ position: Vector3;
545
+ /** The point the camera looks at (target + height + shoulder) */
546
+ lookPoint: Vector3;
547
+ /** Unit arm direction, look point -> camera */
548
+ dir: Vec3Like;
549
+ /** Arm length after walls (m); distance is the wanted one */
550
+ arm: number;
551
+ distance: number;
552
+ /** Ground height under the camera, groundClearance, and a ground query (x, z) => height */
553
+ groundY: number;
554
+ clearance: number;
555
+ surface(x: number, z: number): number;
556
+ rig: FollowCamera;
557
+ }
558
+ /** followCamera getView() */
559
+ export interface FollowCameraView {
560
+ yaw: number;
561
+ /** Positive = camera above the look point looking down; negative = looking up */
562
+ pitch: number;
563
+ /** Wanted distance; arm is the actual one this frame (after walls and ground) */
564
+ distance: number;
565
+ arm: number;
566
+ lookPoint: Vec3Like;
567
+ /** Unit 3D direction the camera looks along */
568
+ look: Vec3Like;
569
+ }
570
+ /** Third-person follow camera */
571
+ export interface FollowCamera extends CameraRigBase, Required<Omit<FollowCameraOptions, 'lockPitch' | 'pixelSnap'>> {
572
+ /** Smoothed follow point */
573
+ focus: Vector3;
574
+ lockPitch?: boolean;
575
+ /** false: no occlusion handling */
576
+ avoidOcclusion?: boolean;
577
+ /** Lock-on framing set by frame() */
578
+ framing: { target: Object3D | Vec3Like; strength: number } | null;
579
+ /** Lock-on framing: turn yaw each frame toward "behind the followed object, looking at target"; mouse yaw is ignored meanwhile; null hands yaw back. strength default 6 (1/s) */
580
+ frame(target: Object3D | Vec3Like | null, opts?: { strength?: number }): void;
581
+ /** Set the view from game code: pitch is clamped to minPitch..maxPitch, distance to the zoom range. Negative pitch looks up. Pair with mouseLook: false to own it every frame */
582
+ setView(view: { yaw?: number; pitch?: number; distance?: number }): this;
583
+ /** The current view: angles, wanted / actual arm, look point and 3D look direction */
584
+ getView(): FollowCameraView;
585
+ /** Actual arm length last frame (after walls and ground), meters */
586
+ readonly arm: number;
587
+ }
588
+
589
+ export interface FirstPersonCameraOptions {
590
+ /** Eye height above the feet (meters), default 1.6 */
591
+ height?: number;
592
+ /** Mouse sensitivity, default 1 */
593
+ sensitivity?: number;
594
+ /** Field of view (degrees); unchanged if omitted */
595
+ fov?: number | null;
596
+ /** Walking bob amplitude (meters), 0 off, default 0.04 */
597
+ headBob?: number;
598
+ /** Bobs per meter @experimental */
599
+ bobFrequency?: number;
600
+ /** Hide the character itself (its shadow remains), default true @experimental */
601
+ hideTarget?: boolean;
602
+ /** Layer number used for hiding 0–31 */
603
+ hideLayer?: number;
604
+ /** Click to lock the mouse, default true */
605
+ pointerLock?: boolean;
606
+ /** The press that locks the mouse is not delivered as Mouse0 / a click (default true); false delivers it too */
607
+ swallowLockClick?: boolean;
608
+ /** Initial heading (radians) */
609
+ yaw?: number;
610
+ /** Initial look angle (radians), default 0 = level. Positive looks up, negative down: the opposite of followCamera's pitch */
611
+ pitch?: number;
612
+ /** Look down / up limit (radians), default -1.45 / 1.45 */
613
+ minPitch?: number;
614
+ /** @experimental */ maxPitch?: number;
615
+ /** Turn range left / right [min, max] (radians), unlimited by default @experimental */
616
+ yawLimits?: number[] | null;
617
+ /** Smoothing of the camera following the body @experimental */
618
+ smoothing?: number;
619
+ /** Invert vertical @experimental */
620
+ invertY?: boolean;
621
+ }
622
+ /** First-person camera */
623
+ export interface FirstPersonCamera extends CameraRigBase, Required<Omit<FirstPersonCameraOptions, 'fov'>> {
624
+ /** Eye position */
625
+ eye: Vector3;
626
+ /** Turn toward a world position (Vector3 / object / [x, y, z] / { x, y, z }) */
627
+ lookAt(position: PositionLike): void;
628
+ }
629
+
630
+ /** Fixed shot */
631
+ export interface CameraShot {
632
+ /** Camera position */
633
+ position: Vec3Like;
634
+ /** Fixed point to look at (if omitted, it turns its head with the player) */
635
+ lookAt?: Vec3Like;
636
+ /** Turn its head with the player */
637
+ track?: boolean;
638
+ /** Field of view (degrees) */
639
+ fov?: number;
640
+ /** Position used to judge the "nearest shot", defaults to position */
641
+ at?: Vec3Like;
642
+ /** How high above the character to look at (meters) */
643
+ trackHeight?: number;
644
+ /** 'orthographic' draws this shot without perspective (isometric / 2.5D); default 'perspective' */
645
+ projection?: 'perspective' | 'orthographic';
646
+ /** With projection 'orthographic' (required there): world units of view height; the width follows the aspect */
647
+ size?: number;
648
+ }
649
+ /** fixedCamera / setCamera('fixed', ...) options; the shot fields (position, lookAt, projection, size...) at the top level are a one-shot form: shots = { main: them } */
650
+ export interface FixedCameraOptions extends Partial<CameraShot> {
651
+ /** Art-pixel rounding, orthographic only: rounds the camera on screen axes, clamps to bounds there first, and decides the view height (buffer height / pixelsPerMeter), so no size with it. Recipe 62 section 4b */
652
+ pixelSnap?: { pixelsPerMeter: number; bounds?: import('./pixel').PixelBounds | null };
653
+ /** Shots: name → shot */
654
+ shots?: Record<string, CameraShot>;
655
+ /** Initial shot name */
656
+ start?: string | null;
657
+ /** Automatic switching: false | 'nearest' (pick the one nearest to the player) */
658
+ auto?: false | 'nearest';
659
+ /** Check interval for automatic switching (seconds) @experimental */
660
+ autoInterval?: number;
661
+ /** How many meters closer a new shot must be to switch (prevents flipping back and forth) */
662
+ hysteresis?: number;
663
+ /** Transition seconds for trigger-zone switches (0 = hard cut) @experimental */
664
+ triggerBlend?: number;
665
+ /** How high above the character a track shot looks (meters) @experimental */
666
+ trackHeight?: number;
667
+ /** Head-follow smoothing @experimental */
668
+ trackSmoothing?: number;
669
+ /** Keep the direction when switching shots until the direction key is released @experimental */
670
+ holdDirection?: boolean;
671
+ /** Transition easing */
672
+ ease?: Ease;
673
+ }
674
+ /** Fixed-shot camera */
675
+ export interface FixedCamera extends CameraRigBase {
676
+ /** All shots. A shot stays where it was placed: for a view that pans at a fixed angle use followCamera({ mouseLook: false }) (recipe 21 section 6) */
677
+ shots: Record<string, any>;
678
+ /** Current shot name */
679
+ current: string | null;
680
+ auto: false | 'nearest';
681
+ autoInterval: number;
682
+ hysteresis: number;
683
+ triggerBlend: number;
684
+ trackHeight: number;
685
+ trackSmoothing: number;
686
+ holdDirection: boolean;
687
+ ease: Ease;
688
+ /** Add / replace a shot */
689
+ add(name: string, shot: CameraShot): this;
690
+ /** Cut to a shot immediately */
691
+ cut(name: string): void;
692
+ /** Transition smoothly to a shot ({ seconds = 1, ease }); the Promise resolves when done */
693
+ blend(name: string, opts?: { seconds?: number; ease?: Ease }): Promise<void>;
694
+ /** Name of the shot nearest to a point */
695
+ nearest(p: Vector3): string | null;
696
+ }
697
+
698
+ export interface RtsCameraOptions {
699
+ /** Camera height above the focus (meters), default 30 */
700
+ height?: number;
701
+ /** Zoom range (meters) */
702
+ minHeight?: number;
703
+ maxHeight?: number;
704
+ /** Pitch down angle (radians, π/2 = straight down), default 0.95 */
705
+ pitch?: number;
706
+ /** Initial horizontal heading (radians) */
707
+ yaw?: number;
708
+ /** Pan speed multiplier @experimental */
709
+ panSpeed?: number;
710
+ /** Drag with the mouse to pan, default true @experimental */
711
+ dragPan?: boolean;
712
+ /** Pan at the screen edge, default false @experimental */
713
+ edgePan?: boolean;
714
+ /** Edge width (fraction of the screen) @experimental */
715
+ edgeSize?: number;
716
+ /** Focus range (meters) */
717
+ bounds?: { minX?: number; maxX?: number; minZ?: number; maxZ?: number } | null;
718
+ /** false: no turning. Default true: declares the actions rotateLeft / rotateRight (no keys; presets.bindings.rtsRotate binds Q / R) */
719
+ rotate?: boolean;
720
+ /** Rotation speed (radians/second) @experimental */
721
+ rotateSpeed?: number;
722
+ /** Zoom ratio per wheel notch @experimental */
723
+ zoomStep?: number;
724
+ /** Smoothing @experimental */
725
+ smoothing?: number;
726
+ /** Field of view (degrees); unchanged if omitted */
727
+ fov?: number | null;
728
+ /** Manual panning is not allowed while following @experimental */
729
+ followLock?: boolean;
730
+ /** Initial focus (position) */
731
+ start?: PositionLike | null;
732
+ }
733
+ /** Strategy top-down camera */
734
+ export interface RtsCamera extends CameraRigBase, Required<Omit<RtsCameraOptions, 'rotate' | 'fov' | 'start'>> {
735
+ /** Is it following target */
736
+ following: boolean;
737
+ /** Focus (on the ground) */
738
+ focus: Vector3;
739
+ /** Can it rotate */
740
+ rotate: boolean;
741
+ /** Move the view to position (instant: true skips smoothing) */
742
+ moveTo(position: PositionLike, opts?: { instant?: boolean }): void;
743
+ }
744
+
745
+ /**
746
+ * engine.cameraRig: one of four cameras. The shared methods (follow, forward, right) always work;
747
+ * properties specific to one camera (distance, cut(), moveTo()…) only exist when that camera is installed.
748
+ */
749
+ export type CameraRig = CameraRigBase
750
+ & Partial<Omit<FollowCamera, keyof CameraRigBase>>
751
+ & Partial<Omit<FirstPersonCamera, keyof CameraRigBase | 'height' | 'smoothing'>>
752
+ & Partial<Omit<FixedCamera, keyof CameraRigBase | 'trackHeight' | 'add' | 'ease' | 'auto'>>
753
+ & Partial<Omit<RtsCamera, keyof CameraRigBase | 'height' | 'smoothing' | 'focus'>>
754
+ & {
755
+ /** Fixed shot: add a shot */
756
+ add?(name: string, shot: CameraShot): any;
757
+ ease?: Ease;
758
+ auto?: false | 'nearest';
759
+ };
760
+
761
+ /** Fixed-shot switch event */
762
+ export interface CameraShotEvent { name: string }
763
+
764
+ export type CameraModule = ModuleDef<CameraRig>;