lecodes-sdk 0.20.0 → 1.0.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.
Files changed (114) hide show
  1. package/dist/global.d.ts +48 -5
  2. package/dist/inject.js +361 -260
  3. package/dist/types/audio/Bus.d.ts +45 -0
  4. package/dist/types/audio/Sound.d.ts +28 -0
  5. package/dist/types/audio/Voice.d.ts +27 -0
  6. package/dist/types/audio/audio.d.ts +83 -0
  7. package/dist/types/audio/support.d.ts +1 -0
  8. package/dist/types/canvas/Canvas.d.ts +2 -0
  9. package/dist/types/gl/DecalSet.d.ts +148 -0
  10. package/dist/types/gl/Geometry.d.ts +17 -0
  11. package/dist/types/gl/Light.d.ts +7 -0
  12. package/dist/types/gl/Lightmap.d.ts +9 -0
  13. package/dist/types/gl/Material.d.ts +90 -2
  14. package/dist/types/gl/Mesh.d.ts +18 -1
  15. package/dist/types/gl/Model.d.ts +34 -0
  16. package/dist/types/gl/Particles.d.ts +13 -0
  17. package/dist/types/gl/Scene.d.ts +23 -0
  18. package/dist/types/gl/Texture.d.ts +29 -1
  19. package/dist/types/gl/animation/AnimationClip.d.ts +25 -12
  20. package/dist/types/gl/animation/DynamicBone.d.ts +173 -0
  21. package/dist/types/gl/{IK.d.ts → animation/IK.d.ts} +4 -4
  22. package/dist/types/gl/{Locomotion.d.ts → animation/Locomotion.d.ts} +6 -6
  23. package/dist/types/gl/animation/core.d.ts +15 -10
  24. package/dist/types/gl/audio/AudioSource.d.ts +60 -0
  25. package/dist/types/gl/audio/AudioZone.d.ts +32 -0
  26. package/dist/types/gl/audio/SceneAudio.d.ts +11 -0
  27. package/dist/types/gl/{NavAgent.d.ts → nav/NavAgent.d.ts} +4 -4
  28. package/dist/types/gl/{NavMesh.d.ts → nav/NavMesh.d.ts} +4 -4
  29. package/dist/types/gl/{CharacterController.d.ts → physics/CharacterController.d.ts} +5 -5
  30. package/dist/types/gl/{Physics.d.ts → physics/Physics.d.ts} +6 -5
  31. package/dist/types/gl/{Ragdoll.d.ts → physics/Ragdoll.d.ts} +4 -4
  32. package/dist/types/gl/{Shape.d.ts → physics/Shape.d.ts} +3 -3
  33. package/dist/types/gl/{Trigger.d.ts → physics/Trigger.d.ts} +2 -2
  34. package/dist/types/gl/state.d.ts +0 -1
  35. package/dist/types/gl/{Terrain.d.ts → terrain/Terrain.d.ts} +6 -6
  36. package/dist/types/gl/{terrainMesh.d.ts → terrain/terrainMesh.d.ts} +1 -1
  37. package/dist/types/gl/vehicle/Vehicle.d.ts +300 -0
  38. package/dist/types/gl/vehicle/Wheel.d.ts +147 -0
  39. package/dist/types/inject.d.ts +33 -21
  40. package/dist/types/runtime/files.d.ts +24 -1
  41. package/dist/types/runtime/input.d.ts +11 -0
  42. package/dist/types/scene/defineScene.d.ts +10 -3
  43. package/dist/types/ui/UIImage.d.ts +15 -5
  44. package/dist/types.json +1 -1
  45. package/package.json +1 -1
  46. package/prompts/README.md +142 -142
  47. package/prompts/dist/2d-game.md +408 -197
  48. package/prompts/dist/3d-app.md +491 -166
  49. package/prompts/dist/ar-app.md +373 -163
  50. package/prompts/dist/design.md +83 -87
  51. package/prompts/dist/ui-app.md +325 -136
  52. package/src/audio/Bus.ts +102 -0
  53. package/src/audio/Sound.ts +96 -0
  54. package/src/audio/Voice.ts +102 -0
  55. package/src/audio/audio.ts +161 -0
  56. package/src/audio/support.ts +6 -0
  57. package/src/bridges.d.ts +279 -32
  58. package/src/canvas/Canvas.ts +21 -0
  59. package/src/compile/__tests__/compile.test.ts +11 -0
  60. package/src/compile/compileProject.ts +30 -15
  61. package/src/compile/header.ts +6 -3
  62. package/src/compile/index.ts +4 -0
  63. package/src/compile/sceneEditor.ts +42 -1
  64. package/src/core/Aspect.ts +33 -8
  65. package/src/g2/Scene2D.ts +7 -0
  66. package/src/gl/CameraPlace.ts +52 -52
  67. package/src/gl/DecalSet.ts +360 -0
  68. package/src/gl/Geometry.ts +348 -279
  69. package/src/gl/Light.ts +16 -0
  70. package/src/gl/Lightmap.ts +35 -7
  71. package/src/gl/Material.ts +173 -4
  72. package/src/gl/Mesh.ts +120 -83
  73. package/src/gl/Model.ts +33 -1
  74. package/src/gl/Node.ts +1 -1
  75. package/src/gl/Particles.ts +21 -3
  76. package/src/gl/Scene.ts +41 -7
  77. package/src/gl/Texture.ts +43 -3
  78. package/src/gl/animation/AnimationClip.ts +43 -20
  79. package/src/gl/animation/Animator.ts +4 -3
  80. package/src/gl/animation/DynamicBone.ts +459 -0
  81. package/src/gl/{IK.ts → animation/IK.ts} +4 -4
  82. package/src/gl/{Locomotion.ts → animation/Locomotion.ts} +7 -7
  83. package/src/gl/animation/core.ts +20 -15
  84. package/src/gl/audio/AudioSource.ts +113 -0
  85. package/src/gl/audio/AudioZone.ts +75 -0
  86. package/src/gl/audio/SceneAudio.ts +26 -0
  87. package/src/gl/{NavAgent.ts → nav/NavAgent.ts} +5 -5
  88. package/src/gl/{NavMesh.ts → nav/NavMesh.ts} +8 -8
  89. package/src/gl/{CharacterController.ts → physics/CharacterController.ts} +5 -5
  90. package/src/gl/{Physics.ts → physics/Physics.ts} +12 -5
  91. package/src/gl/{Ragdoll.ts → physics/Ragdoll.ts} +272 -270
  92. package/src/gl/{Shape.ts → physics/Shape.ts} +3 -3
  93. package/src/gl/{Trigger.ts → physics/Trigger.ts} +2 -2
  94. package/src/gl/{physicsEvents.ts → physics/physicsEvents.ts} +1 -1
  95. package/src/gl/scenarios.ts +291 -291
  96. package/src/gl/state.ts +1 -1
  97. package/src/gl/{Terrain.ts → terrain/Terrain.ts} +10 -10
  98. package/src/gl/{terrainMesh.ts → terrain/terrainMesh.ts} +1 -1
  99. package/src/gl/vehicle/Vehicle.ts +666 -0
  100. package/src/gl/vehicle/Wheel.ts +290 -0
  101. package/src/inject.ts +226 -212
  102. package/src/runtime/files.ts +32 -2
  103. package/src/runtime/input.ts +6 -1
  104. package/src/scene/defineScene.ts +26 -10
  105. package/src/scene/gizmos.ts +148 -148
  106. package/src/scene/level.ts +2 -2
  107. package/src/ui/UIImage.ts +21 -7
  108. package/dist/types/gl/Gearbox.d.ts +0 -86
  109. package/dist/types/gl/Vehicle.d.ts +0 -191
  110. package/dist/types/gl/Wheel.d.ts +0 -95
  111. package/src/gl/Gearbox.ts +0 -212
  112. package/src/gl/Vehicle.ts +0 -473
  113. package/src/gl/Wheel.ts +0 -240
  114. /package/dist/types/gl/{physicsEvents.d.ts → physics/physicsEvents.d.ts} +0 -0
@@ -1,191 +0,0 @@
1
- import { Aspect } from "../core/Aspect";
2
- import type { FieldMeta } from "../core/fields";
3
- import { Vec3, type Vec3Like } from "../math/vec";
4
- import { type QuatLike } from "../math/quat";
5
- import { Node } from "./Node";
6
- import { Wheel } from "./Wheel";
7
- /** Which axle the engine drives. A wheel's own `drive` overrides it. */
8
- export type DriveLayout = "rear" | "front" | "all";
9
- /**
10
- * How an axle's two wheels share torque.
11
- * - `lsd` — limited slip (Jolt's 1.4 ratio), the sane default.
12
- * - `open` — fully open: a lifted or spinning wheel takes ALL the torque.
13
- * - `locked` — both wheels forced to the same speed. Breaks traction predictably: the drift diff.
14
- * A number is the raw max/min wheel-speed ratio (> 1; smaller is more locked).
15
- */
16
- export type DifferentialMode = "lsd" | "open" | "locked";
17
- export interface EngineConfig {
18
- /** Peak torque in N·m (default 500). The single biggest "how fast is it" knob. */
19
- torque?: number;
20
- /** Redline in RPM (default 6000). */
21
- maxRpm?: number;
22
- /** Idle RPM (default 1000) — the engine never falls below it. */
23
- idleRpm?: number;
24
- /**
25
- * The engine's CHARACTER: a flat list `[rpm, torque, rpm, torque, …]` in NORMALISED units — x is
26
- * a fraction of the redline, y a fraction of `torque`. Left out, Jolt's own broad curve is used.
27
- *
28
- * `[0, 0.8, 0.66, 1, 1, 0.8]` is an ordinary petrol engine (peak two thirds up, falling to the
29
- * redline); `[0, 1, 1, 1]` is flat, which is what an electric motor feels like.
30
- */
31
- curve?: number[];
32
- /** Moment of inertia in kg·m² (default 0.5) — how eagerly it revs when the clutch is out. */
33
- inertia?: number;
34
- /** Engine braking: angular damping of the engine itself (default 0.2). */
35
- braking?: number;
36
- }
37
- export interface SteeringConfig {
38
- /** Steering lock in degrees at a standstill (default 35). */
39
- lock?: number;
40
- /**
41
- * The lock still available, in degrees, once the car reaches `speed` (default 10) — what stops a
42
- * car over-driving its own front tires.
43
- *
44
- * A tire makes its peak grip at a few degrees of slip angle, and the steering angle a corner needs
45
- * falls with the SQUARE of speed. Holding full lock at 100 km/h therefore asks the front for
46
- * several times what it can give: the tires saturate, the car ploughs on, and the wheel stops
47
- * answering. In between the lock eases on `(1 − v/speed)²`, which tracks the real curve closely.
48
- * `0` turns the taper off — full lock at any speed.
49
- */
50
- atSpeed?: number;
51
- /** The speed in m/s at which the lock has fallen to `atSpeed` (default 30 ≈ 108 km/h). */
52
- speed?: number;
53
- /** How fast the front wheels may turn, in degrees per second (default 220). A keyboard asks for
54
- * full lock in one frame, which no steering wheel can do, and that step alone snaps a tire past
55
- * its peak. `0` = instantly. */
56
- rate?: number;
57
- }
58
- /**
59
- * Aerodynamics. Both numbers are quoted the same way — **a fraction of the car's own weight at
60
- * 30 m/s (108 km/h)** — and both grow with the SQUARE of speed from there, so `0.5` at 30 m/s is
61
- * `2.0` at 60 m/s. One mental model for both, and no drag coefficients or frontal areas to invent.
62
- */
63
- export interface AeroConfig {
64
- /**
65
- * Downforce (default 0 — a car with no wing). The knob that decides whether a car corners better
66
- * or worse the faster it goes: tire grip is a constant, but the force a corner demands grows with
67
- * v², so with no downforce every car runs out of road at speed. `0.6` roughly doubles a car's
68
- * cornering at 150 km/h; a road car is nearer `0.1`, a race car well past `1`.
69
- *
70
- * It presses along the CHASSIS' own down axis (that is what keeps a car planted over a crest) and
71
- * only while a wheel is on the ground — a car on its roof is never launched by its own wing.
72
- */
73
- downforce?: number;
74
- /** Air resistance (default 0.03 — an ordinary car). What gives a car a top speed at all. */
75
- drag?: number;
76
- }
77
- export declare class Vehicle extends Aspect<"vehicle", Node> {
78
- static readonly aspect = "vehicle";
79
- /** Chassis mass in kg (default 1200). Wheels are massless in this model. */
80
- mass: number;
81
- /** Centre of mass height in chassis space (metres, negative = lower). Left out, it drops to halfway
82
- * down the chassis shape — a car with its mass at the shape's centre tips over. */
83
- centerOfMass?: number;
84
- /** Which axle the engine drives (default "rear"). A wheel's own `drive` overrides it. */
85
- driveAxle: DriveLayout;
86
- /** Differential lock across each driven axle. `locked` is the drift setup — both wheels turn
87
- * together, so the pair lets go as a pair. Live: re-configure the aspect to switch it mid-drive. */
88
- differential: DifferentialMode | number;
89
- /**
90
- * Anti-roll bars between each axle's wheels — what stops a car rolling onto its inside wheels in a
91
- * fast corner. `true` (default) is a bar 0.01 as stiff as the wheel's own spring; a number is that
92
- * ratio directly, and `0` / `false` removes the bars.
93
- *
94
- * **The numbers are far smaller than they look and the gain is steep** — Jolt's bar feeds
95
- * `lengthDifference × stiffness × dt` as a bias into the suspension's own soft constraint, so 4%
96
- * of the spring already flattens the body. Measured on a 1250 kg car: `0` → 1.3° of roll at 0.86 g,
97
- * `0.01` → 0.6°, `0.15` → 0.2° (flat), `0.5` → the car HOPS.
98
- *
99
- * This is the knob for how much a car visibly LEANS, not for wheel lift: bars change how far the
100
- * body tips, not how much load transfers. For lift, lower `centerOfMass`.
101
- */
102
- antiRoll: boolean | number;
103
- /** Pitch/roll limit in degrees (default 60) before the constraint rights the car. 180 turns it off. */
104
- maxTilt: number;
105
- /** Friction of the CHASSIS body itself — how it slides when it lands on its roof or side. Nothing
106
- * to do with the tires; those are the `Wheel`'s `tire.grip` × the ground's friction. */
107
- friction: number;
108
- /** Strength of the clutch when fully engaged (default 10). Small values slip; large ones weld the
109
- * engine to the wheels. The `Gearbox` scales it 0..1 while shifting. */
110
- clutchStrength: number;
111
- engine: EngineConfig;
112
- steering: SteeringConfig;
113
- aero: AeroConfig;
114
- /** Scene-editor inspector: the flat, tunable half. The grouped objects are edited in code. */
115
- static fields: FieldMeta<Vehicle>;
116
- static editor: {
117
- rebuild: boolean;
118
- };
119
- private _id;
120
- private _bodyId;
121
- private _builtMass;
122
- private _wheels;
123
- private _state;
124
- private _stateFrame;
125
- private _throttle;
126
- private _steer;
127
- private _brake;
128
- private _handbrake;
129
- onAttach(): void;
130
- onDetach(): void;
131
- /**
132
- * Re-configuring an attached vehicle retunes it in place — the way a drift button switches the
133
- * differential without the car so much as blinking:
134
- *
135
- * car.aspect(Vehicle, { differential: drift ? 'locked' : 'lsd' })
136
- *
137
- * Live: `differential`, `engine`, `steering`, `aero`, `maxTilt`, `friction`, `clutchStrength`, and
138
- * every `Wheel`'s `tire.grip` and brake torques. Everything else describes the car's STRUCTURE —
139
- * `mass`, `centerOfMass`, which wheels exist and where, their suspension, `driveAxle`, `antiRoll` — and
140
- * is baked into the constraint at attach; to change one of those, re-attach the aspect.
141
- */
142
- onReconfigure(): void;
143
- /** Native vehicle id (0 until attached / no physics support). */
144
- get id(): number;
145
- /** The chassis rigid-body id — the same handle the plain body calls take. */
146
- get bodyId(): number;
147
- /** The wheels, in blob order (front axle first). */
148
- get wheels(): readonly Wheel[];
149
- /**
150
- * The driver's controls, all in [-1, 1] (brakes in [0, 1]). Sticky: the last values keep applying
151
- * until the next call, so a held key does not need re-sending. `forward < 0` asks for reverse; the
152
- * `Gearbox` engages it once the car has stopped.
153
- */
154
- drive(forward: number, steer?: number, brake?: number, handbrake?: number): this;
155
- /** Teleport upright and clear all motion (velocity, engine, gearbox, wheel spin). Defaults to the
156
- * chassis node's current pose — `reset()` alone un-flips a car where it lies. */
157
- reset(position?: Vec3Like, rotation?: QuatLike): this;
158
- /** Push the chassis (a boost pad, an explosion) — an instantaneous impulse in kg·m/s. */
159
- applyImpulse(v: Vec3Like): this;
160
- private _read;
161
- /** Speed along the car's forward axis in m/s — negative when reversing (× 3.6 for km/h). */
162
- get speed(): number;
163
- /** Engine revolutions per minute. */
164
- get rpm(): number;
165
- /** How many wheels are touching the ground. */
166
- get wheelsOnGround(): number;
167
- /** Any wheel on the ground — false while airborne. */
168
- get grounded(): boolean;
169
- /** Chassis velocity in world units/s (fresh Vec3). */
170
- get velocity(): Vec3;
171
- /** The last throttle handed to `drive()` — what the gearbox reads to know which way you want to go. */
172
- get throttle(): number;
173
- /** The last steer input handed to `drive()`, [-1, 1]. */
174
- get steerInput(): number;
175
- /** The last foot-brake input handed to `drive()`, [0, 1] — the pedal, not the resulting force. */
176
- get brake(): number;
177
- /** The last handbrake input handed to `drive()`, [0, 1]. */
178
- get handbrake(): number;
179
- /** Current gear from the attached `Gearbox`: −1 reverse, 0 neutral, 1… forward. */
180
- get gear(): number;
181
- /** The steering lock, in degrees, the car is allowed at its current speed — the full lock at rest,
182
- * falling to `steering.atSpeed`. The same curve the engine applies; useful on a HUD. */
183
- get steerLock(): number;
184
- /** Every Wheel under the chassis, ordered front axle first, with its axle group resolved. */
185
- private _collectWheels;
186
- /** Pack the whole configuration into the one blob the host ABI takes (see bridges.d.ts). */
187
- private _buildSettings;
188
- /** Edit mode: which way the chassis faces. Each wheel draws its own circle and travel range — see
189
- * `Wheel.rebuild()`. Play mode never calls this. */
190
- rebuild(): void;
191
- }
@@ -1,95 +0,0 @@
1
- import { Aspect } from "../core/Aspect";
2
- import type { FieldMeta } from "../core/fields";
3
- import { type Vec3Like } from "../math/vec";
4
- import { Node } from "./Node";
5
- /** Floats `vehicleGetState` writes before the per-wheel block: speed, rpm, contacts, vx, vy, vz. */
6
- export declare const STATE_HEADER = 6;
7
- /** Floats per wheel: contact, slip, slipAngle, suspensionLength, steerDeg, spin. */
8
- export declare const WHEEL_STATE = 6;
9
- /** How a tire behaves past its grip peak. `road` is Jolt's own curve — grip falls off after the peak,
10
- * so the car can be made to let go. `arcade` holds the peak all the way out: much harder to spin. */
11
- export type TireCurve = "road" | "arcade";
12
- export interface WheelSuspension {
13
- /** Total travel in metres, full droop to fully compressed (default 0.4). */
14
- travel?: number;
15
- /** Spring frequency in Hz — bigger is stiffer (default 1.4; a race car ~2.5, a truck ~1). It also
16
- * sets the ride-height sag, and the sag is how far the wheel can still extend DOWN. */
17
- stiffness?: number;
18
- /** Damping ratio 0..1 (default 0.5). Low values pogo. */
19
- damping?: number;
20
- }
21
- export interface WheelTire {
22
- /** Grip multiplier on the friction curves (default 1). The grip a wheel actually gets is combined
23
- * with the ground it stands on as `sqrt(tire × groundFriction)`, and a body's friction defaults to
24
- * 0.6 — so a road a car should really corner on wants `Physics { friction: 1 }`. */
25
- grip?: number;
26
- /** Which friction curve (default `road`). */
27
- curve?: TireCurve;
28
- }
29
- export interface WheelVisual {
30
- /** The MODEL's axle direction in its own space (default `[1, 0, 0]`). Set it instead of parenting
31
- * the mesh under a corrective node when the art points another way. */
32
- axis?: Vec3Like;
33
- /** Drawn radius, if the art is not exactly the physical `radius` — sinks a wheel into its arch or
34
- * lets a fat tire overhang, with no effect on the simulation. Default: the physical radius. */
35
- radius?: number;
36
- /** Let the model spin (default true). `false` keeps the steer angle and suspension travel but not
37
- * the rotation — a brake caliper. */
38
- spin?: boolean;
39
- }
40
- export declare class Wheel extends Aspect<"wheel", Node> {
41
- static readonly aspect = "wheel";
42
- /** Wheel radius in metres. Default: measured from the node's rendered bounds, else 0.35. Too small
43
- * and the car scrapes, too large and it floats. */
44
- radius?: number;
45
- /** Wheel width in metres. Default: measured, else 0.25. */
46
- width?: number;
47
- /** Does this wheel steer? Default: the wheels on the front axle. */
48
- steer?: boolean;
49
- /** Does the engine drive it? Default: from the vehicle's `drive` layout. */
50
- drive?: boolean;
51
- /** Foot brake on this wheel. */
52
- brake: boolean;
53
- /** Handbrake on this wheel. Default: every non-steering wheel (locking the front wheels of a moving
54
- * car is not a handbrake turn, it is a crash). */
55
- handbrake?: boolean;
56
- /** Axle group, front to back. Default: derived from Z. Set it for a car whose wheels are not in neat
57
- * left/right pairs — an axle's wheels are paired for the differential and the anti-roll bar. */
58
- axle?: number;
59
- /** Foot-brake torque in N·m (default 1500); the handbrake pulls 3× on the wheels that have it. */
60
- brakeTorque: number;
61
- suspension: WheelSuspension;
62
- tire: WheelTire;
63
- visual: WheelVisual;
64
- /** Scene-editor inspector. `steer` / `drive` / `handbrake` are deliberately absent: they are
65
- * tri-state (undefined = derive it from the axle), which a switch cannot express. */
66
- static fields: FieldMeta<Wheel>;
67
- static editor: {
68
- rebuild: boolean;
69
- };
70
- private _angle;
71
- private _scale;
72
- private _local;
73
- onAttach(): void;
74
- onDetach(): void;
75
- private _state;
76
- /** Touching the ground this step. */
77
- get contact(): boolean;
78
- /** Longitudinal slip RATIO: 0 = rolling in sync with the ground, ~1 = spinning up or locked.
79
- * Unsigned — smoke, tire marks and wheelspin sound key off this. */
80
- get slip(): number;
81
- /** Slip ANGLE in degrees: how far the tire's travel direction is off from where it points.
82
- * Unsigned, 0..90 — past the curve's peak (~3°) the tire is sliding sideways. Drift particles. */
83
- get slipAngle(): number;
84
- /** Steer angle in degrees, positive to the right. */
85
- get steerAngle(): number;
86
- /** Wheel spin in rad/s (× radius ≈ the speed the tire is laying down). */
87
- get spin(): number;
88
- /** Suspension compression, 0 = fully extended (drooping) … 1 = fully compressed. */
89
- get compression(): number;
90
- /** LATE phase: after the step and the transform sync, right before the frame draws. */
91
- update(dt: number): void;
92
- /** Edit mode: this wheel's own circle at its resting height, its travel range, and a mark when the
93
- * engine drives it — enough to place a wheel without running the game. */
94
- rebuild(): void;
95
- }
package/src/gl/Gearbox.ts DELETED
@@ -1,212 +0,0 @@
1
- // The gearbox of a `Vehicle`, as an aspect on the same node. It is deliberately NOT in the engine:
2
- // picking a gear is policy, not physics — two RPM thresholds and a latency timer — and every game
3
- // wants its own. The engine keeps only the physical half (the clutch's stiffness and the coupled
4
- // engine/wheel solve), and is told one ratio and one clutch scalar per frame.
5
- //
6
- // car.aspect(Gearbox, { ratios: [2.66, 1.78, 1.3, 1.0, 0.74], reverse: -2.9 })
7
- //
8
- // A `Vehicle` with no `Gearbox` attaches this one with its defaults, so a car that never mentions
9
- // gears still drives.
10
- //
11
- // Custom behaviour is a subclass overriding ONE method:
12
- //
13
- // class SportBox extends Gearbox {
14
- // select(v: Vehicle): number { return v.rpm > 6200 ? this.gear + 1 : this.gear }
15
- // }
16
- //
17
- // The clutch is two things multiplied. The SHIFT envelope (`shiftTime`/`clutchTime`) stays with the
18
- // base class on purpose: a forgotten ramp breaks a car silently — no drive at all, or a slammed
19
- // clutch. The TAKE-UP (`takeUp`) is the left-foot half, and is overridable for a car that launches
20
- // unusually — a torque converter, a rally launch control.
21
-
22
- import { Aspect } from "../core/Aspect"
23
- import type { FieldMeta } from "../core/fields"
24
- import type { Node } from "./Node"
25
- import type { Vehicle } from "./Vehicle"
26
-
27
- // How far above idle counts as "revs to spare". A simulated engine cannot fall below its idle — the
28
- // physics clamps it — so being AT idle is the observable form of "the wheels are dragging me under".
29
- // This is the tolerance for reading that clamp, not a tuning knob.
30
- const IDLE_MARGIN = 1.05
31
-
32
- // The car this gearbox belongs to. Read through the aspect accessor rather than node.get(Vehicle),
33
- // so this file needs Vehicle only as a TYPE and the two do not import each other at runtime.
34
- const carOf = (n: Node): Vehicle | null => (n as unknown as { vehicle?: Vehicle }).vehicle ?? null
35
-
36
- export class Gearbox extends Aspect<"gearbox", Node> {
37
- static readonly aspect = "gearbox"
38
-
39
- /** Forward gear ratios, first gear first. Engine RPM = wheel speed × ratio × the differential. */
40
- ratios: number[] = [ 2.66, 1.78, 1.3, 1.0, 0.74 ]
41
- /** Reverse ratio — negative, because a ratio's SIGN is what reverse means to the engine. */
42
- reverse = -2.9
43
- /** Shift up when the engine passes this fraction of its redline. */
44
- shiftUp = 0.67
45
- /** Shift down when it falls below this fraction. */
46
- shiftDown = 0.33
47
- /** How long a shift takes, in seconds — the clutch is out for this long. */
48
- shiftTime = 0.2
49
- /** How long the clutch takes to re-engage afterwards. */
50
- clutchTime = 0.3
51
- /** How long to wait after a shift before another is allowed — without it a car sitting on a
52
- * threshold hunts between two gears. */
53
- latency = 0.5
54
-
55
- /** How far the clutch bites the instant drive is asked for from rest, 0..1. It only has to COUPLE
56
- * the shafts — how much torque that passes is the engine's business, so a feathered throttle
57
- * still pulls away gently at the same bite point. */
58
- bite = 0.4
59
-
60
- static fields: FieldMeta<Gearbox> = {
61
- reverse: { max: -0.1, step: 0.1 },
62
- shiftUp: { min: 0.1, max: 1, step: 0.01 },
63
- shiftDown: { min: 0, max: 0.9, step: 0.01 },
64
- shiftTime: { min: 0, max: 3, step: 0.05 },
65
- clutchTime: { min: 0, max: 3, step: 0.05 },
66
- latency: { min: 0, max: 3, step: 0.05 },
67
- bite: { min: 0, max: 1, step: 0.05 },
68
- ratios: { hidden: true },
69
- }
70
-
71
- /** Current gear: −1 reverse, 0 neutral, 1… forward. Read it for a HUD. */
72
- gear = 0
73
- /** True while a shift is in progress — the clutch is out and the engine is not driving the wheels. */
74
- get shifting(): boolean { return this._shiftLeft > 0 }
75
-
76
- private _shiftLeft = 0 // seconds of clutch-out left
77
- private _engageLeft = 0 // seconds of clutch re-engagement left
78
- private _waitLeft = 0 // anti-hunting
79
- private _take = 0 // how far the CAR's own state wants the clutch in, latched per frame
80
-
81
- /** EARLY phase: the pair has to be latched before this frame's step consumes it. */
82
- updateBefore(dt: number): void {
83
- const v = carOf(this.node)
84
- if (!v || !v.id) return
85
-
86
- this._waitLeft = Math.max(0, this._waitLeft - dt)
87
-
88
- if (this._shiftLeft > 0) {
89
- // Mid-shift: clutch fully out, and the moment it ends the re-engagement ramp starts.
90
- this._shiftLeft = Math.max(0, this._shiftLeft - dt)
91
- if (this._shiftLeft === 0) this._engageLeft = this.clutchTime
92
- } else {
93
- const want = this.select(v)
94
- if (want !== this.gear) this.shift(want)
95
- else this._engageLeft = Math.max(0, this._engageLeft - dt)
96
- }
97
-
98
- // The pedal only moves while no shift is in flight. During one the revs say nothing about
99
- // whether the wheels can sustain them: an engine still spinning down from the last gear reads as
100
- // "revs to spare" and would drop the clutch straight back in — enough to shove a stopped car
101
- // several km/h with no throttle at all. Freezing it is what a driver does anyway; the foot is
102
- // already down, and the envelope owns the clutch until the gear is in.
103
- if (this._shiftLeft === 0 && this._engageLeft === 0) {
104
- this._take = Math.max(0, Math.min(1, this.takeUp(v, dt)))
105
- }
106
-
107
- v._setTransmission(this.ratio, this.clutch)
108
- }
109
-
110
- /**
111
- * The driver's left foot: where the clutch pedal is, ignoring shifts. Returns the new engagement.
112
- *
113
- * A driver does not compute anything. They watch the tacho: **revs sinking to idle means the
114
- * wheels are about to drag the engine under, and that is when you push the clutch in.** That
115
- * single test replaces every ratio and threshold — the crossover it finds is the exact speed where
116
- * engine braking stops and the engine would start PUSHING instead, and it finds it per gear
117
- * without being told the gear.
118
- *
119
- * The pedal comes back UP only for the throttle. Healthy revs are not on their own a reason to
120
- * engage: a car standing still shows healthy revs too — the wheels simply are not turning to say
121
- * otherwise — and a clutch dropped on that evidence lurches the car off with no throttle at all.
122
- *
123
- * Three things fall out of it for free:
124
- *
125
- * - **A braked car stops.** The engine cannot stall, so a clutch left in at 0 km/h feeds idle
126
- * torque to the wheels forever and the car creeps against its own brakes. Here the revs pin at
127
- * idle, so the pedal goes down and the brakes have nothing to fight.
128
- * - **Reverse is not a special case.** No ratio takes part, so it needs no separate number — which
129
- * is exactly why a fixed road-speed threshold got reverse wrong.
130
- * - **Hill starts judder instead of stalling.** Let the pedal out, the load pulls the revs down,
131
- * the rule pushes it straight back in, and the clutch sits slipping at the bite point until the
132
- * car moves. So the test deliberately ignores the throttle — gating it on "no throttle" would
133
- * stall the car under load. Throttle only holds the floor at `bite`.
134
- *
135
- * The cost is honest and small: once the pedal is down the revs sit at idle and cannot rise on
136
- * their own, so **coasting downhill gives no engine braking until you touch the throttle** — which
137
- * is precisely what a car with the clutch in does. Slipping it permanently to keep listening would
138
- * bring the creep straight back.
139
- */
140
- protected takeUp(v: Vehicle, dt: number): number {
141
- if (this.gear === 0) return 0
142
- const idle = v.engine.idleRpm ?? 1000
143
- const step = dt / Math.max(this.clutchTime, dt)
144
- const asked = v.throttle !== 0
145
- let take = this._take
146
- if (v.rpm <= idle * IDLE_MARGIN) take -= step // being dragged under: pedal goes down
147
- else if (asked) take += step // revs to spare AND somewhere to go: let it up
148
- // Asking for drive also holds the pedal at the bite point however far down the rule wants it;
149
- // that is what makes a launch — and a hill start — slip instead of collapsing to nothing.
150
- return asked ? Math.max(take, this.bite) : take
151
- }
152
-
153
- /**
154
- * Which gear the car should be in. The default is an ordinary automatic: pull away from neutral in
155
- * the direction of the throttle, shift up past `shiftUp` of the redline and down below `shiftDown`,
156
- * and refuse to shift again for `latency` seconds. Override this and nothing else.
157
- */
158
- select(v: Vehicle): number {
159
- const throttle = v.throttle
160
- // Neutral, or asked to go the other way: engage once the car has (nearly) stopped.
161
- if (this.gear === 0 || throttle * this.gear < 0) {
162
- if (Math.abs(v.speed) > 1 && this.gear !== 0) return this.gear
163
- return throttle > 0 ? 1 : throttle < 0 ? -1 : this.gear
164
- }
165
- if (this.gear < 0 || this._waitLeft > 0 || this.shifting) return this.gear
166
- const rpm = v.rpm
167
- const max = v.engine.maxRpm ?? 6000
168
- // Upshifting needs COUPLED revs. With the clutch out the engine is free, so a blip at a
169
- // standstill reads as 6000 rpm and the box would climb to top gear without the car moving —
170
- // then launch in it. Downshifting stays open either way: it can only take you to a lower gear,
171
- // which is where a car with dying revs belongs.
172
- if (rpm > max * this.shiftUp && this.clutch >= 1 && this.gear < this.ratios.length) return this.gear + 1
173
- if (rpm < max * this.shiftDown && this.gear > 1) return this.gear - 1
174
- return this.gear
175
- }
176
-
177
- /** Change gear now, with the clutch envelope. Safe to call from `select()` or from game code
178
- * (a sequential manual is `if (Input.key('KeyE')) car.gearbox.shift(car.gearbox.gear + 1)`). */
179
- shift(gear: number): void {
180
- const clamped = Math.max(-1, Math.min(this.ratios.length, Math.round(gear)))
181
- if (clamped === this.gear) return
182
- // The envelope is for swapping one ENGAGED gear for another. If nothing is coupled there is
183
- // nothing to disengage, so it is skipped: neutral at either end, and equally a car sitting still
184
- // with the pedal already down — picking reverse there should pull away the moment it is asked
185
- // to, not sit out a shift it never had to make.
186
- const swapping = this.gear !== 0 && clamped !== 0 && this._take > 0
187
- this.gear = clamped
188
- this._shiftLeft = swapping ? this.shiftTime : 0
189
- this._engageLeft = swapping ? this.clutchTime : 0
190
- this._waitLeft = this.latency + this._shiftLeft
191
- }
192
-
193
- /** The ratio the engine should be running: 0 in neutral, negative in reverse. */
194
- get ratio(): number {
195
- if (this.gear === 0) return 0
196
- if (this.gear < 0) return this.reverse
197
- return this.ratios[this.gear - 1] ?? 1
198
- }
199
-
200
- /**
201
- * The clutch scalar 0..1 the engine is given: the SHIFT envelope (out during a shift, ramping back
202
- * over `clutchTime`) times the driver's pedal (`takeUp`). Two independent reasons for the clutch
203
- * to be out, so they multiply: mid-shift is out however healthy the revs are, and an engine being
204
- * dragged to idle is out whatever gear it just picked.
205
- */
206
- get clutch(): number {
207
- if (this._shiftLeft > 0) return 0
208
- const envelope =
209
- this._engageLeft > 0 && this.clutchTime > 0 ? 1 - this._engageLeft / this.clutchTime : 1
210
- return envelope * this._take
211
- }
212
- }