@pinkaphant/ecctrl 0.0.0-stage → 2.0.4-beta.1

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 (117) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE +10 -0
  4. package/dist/Color-V9u0UyNg.cjs +81 -0
  5. package/dist/Color-V9u0UyNg.cjs.map +1 -0
  6. package/dist/Color-rCfz0rNn.js +28 -0
  7. package/dist/Color-rCfz0rNn.js.map +1 -0
  8. package/dist/CurveLUT-BfMhx3LX.js +88 -0
  9. package/dist/CurveLUT-BfMhx3LX.js.map +1 -0
  10. package/dist/CurveLUT-Ck18ZlkK.cjs +99 -0
  11. package/dist/CurveLUT-Ck18ZlkK.cjs.map +1 -0
  12. package/dist/EcctrlAnimationStateController-41Cm1Tt1.cjs +111 -0
  13. package/dist/EcctrlAnimationStateController-41Cm1Tt1.cjs.map +1 -0
  14. package/dist/EcctrlAnimationStateController-Bb2fARWF.js +94 -0
  15. package/dist/EcctrlAnimationStateController-Bb2fARWF.js.map +1 -0
  16. package/dist/Math-BkrN2TZK.js +49 -0
  17. package/dist/Math-BkrN2TZK.js.map +1 -0
  18. package/dist/Math-ByyUpUHB.cjs +68 -0
  19. package/dist/Math-ByyUpUHB.cjs.map +1 -0
  20. package/dist/all.cjs +52 -0
  21. package/dist/all.cjs.map +1 -0
  22. package/dist/all.d.ts +16 -0
  23. package/dist/all.js +32 -0
  24. package/dist/all.js.map +1 -0
  25. package/dist/animation.cjs +23 -0
  26. package/dist/animation.cjs.map +1 -0
  27. package/dist/animation.d.ts +8 -0
  28. package/dist/animation.js +20 -0
  29. package/dist/animation.js.map +1 -0
  30. package/dist/camera-B_UgIm14.js +71 -0
  31. package/dist/camera-B_UgIm14.js.map +1 -0
  32. package/dist/camera-CzMKt9dI.cjs +79 -0
  33. package/dist/camera-CzMKt9dI.cjs.map +1 -0
  34. package/dist/camera.cjs +10 -0
  35. package/dist/camera.d.ts +9 -0
  36. package/dist/camera.js +9 -0
  37. package/dist/character/Ecctrl.d.ts +105 -0
  38. package/dist/character/animation/EcctrlAnimationStateController.d.ts +17 -0
  39. package/dist/character/animation/index.d.ts +13 -0
  40. package/dist/character/animation/resolveAnimationState.d.ts +9 -0
  41. package/dist/character/animation/types.d.ts +19 -0
  42. package/dist/character/animation/useEcctrlAnimationStore.d.ts +21 -0
  43. package/dist/character/types.d.ts +27 -0
  44. package/dist/chunk-D6vf50IK.cjs +35 -0
  45. package/dist/curves/CurveLUT.d.ts +27 -0
  46. package/dist/curves.cjs +22 -0
  47. package/dist/curves.cjs.map +1 -0
  48. package/dist/curves.d.ts +9 -0
  49. package/dist/curves.js +20 -0
  50. package/dist/curves.js.map +1 -0
  51. package/dist/gravity/EcctrlCameraControls.d.ts +28 -0
  52. package/dist/gravity/useCustomGravity.d.ts +23 -0
  53. package/dist/gravity.cjs +21 -0
  54. package/dist/gravity.cjs.map +1 -0
  55. package/dist/gravity.d.ts +9 -0
  56. package/dist/gravity.js +20 -0
  57. package/dist/gravity.js.map +1 -0
  58. package/dist/index.cjs +14 -0
  59. package/dist/index.d.ts +12 -0
  60. package/dist/index.js +10 -0
  61. package/dist/input/Joystick.d.ts +18 -0
  62. package/dist/input/VirtualButton.d.ts +17 -0
  63. package/dist/input/stores/useButtonStore.d.ts +21 -0
  64. package/dist/input/stores/useJoystickStore.d.ts +26 -0
  65. package/dist/input-CrNBMRxm.js +315 -0
  66. package/dist/input-CrNBMRxm.js.map +1 -0
  67. package/dist/input-DBhf3WZe.cjs +340 -0
  68. package/dist/input-DBhf3WZe.cjs.map +1 -0
  69. package/dist/input.cjs +13 -0
  70. package/dist/input.d.ts +15 -0
  71. package/dist/input.js +9 -0
  72. package/dist/leva--ZV58vPr.cjs +771 -0
  73. package/dist/leva--ZV58vPr.cjs.map +1 -0
  74. package/dist/leva-BjLuypTs.js +764 -0
  75. package/dist/leva-BjLuypTs.js.map +1 -0
  76. package/dist/leva.cjs +10 -0
  77. package/dist/leva.d.ts +9 -0
  78. package/dist/leva.js +9 -0
  79. package/dist/plugins/leva/CurveEditorPlugin.d.ts +72 -0
  80. package/dist/shared/Math.d.ts +11 -0
  81. package/dist/shared/constants/Color.d.ts +16 -0
  82. package/dist/shared/types.d.ts +16 -0
  83. package/dist/src-Cz0JLHDZ.js +1164 -0
  84. package/dist/src-Cz0JLHDZ.js.map +1 -0
  85. package/dist/src-Qj3Pzy6X.cjs +1172 -0
  86. package/dist/src-Qj3Pzy6X.cjs.map +1 -0
  87. package/dist/time/TimeControl.d.ts +16 -0
  88. package/dist/time-CHRDN3n2.cjs +48 -0
  89. package/dist/time-CHRDN3n2.cjs.map +1 -0
  90. package/dist/time-D3dS_ohx.js +43 -0
  91. package/dist/time-D3dS_ohx.js.map +1 -0
  92. package/dist/time.cjs +10 -0
  93. package/dist/time.d.ts +9 -0
  94. package/dist/time.js +9 -0
  95. package/dist/useCustomGravity-B35U0d4V.cjs +45 -0
  96. package/dist/useCustomGravity-B35U0d4V.cjs.map +1 -0
  97. package/dist/useCustomGravity-elzlTR6Y.js +38 -0
  98. package/dist/useCustomGravity-elzlTR6Y.js.map +1 -0
  99. package/dist/utils.cjs +23 -0
  100. package/dist/utils.cjs.map +1 -0
  101. package/dist/utils.d.ts +8 -0
  102. package/dist/utils.js +20 -0
  103. package/dist/utils.js.map +1 -0
  104. package/dist/vehicle-B8WqQHee.js +2069 -0
  105. package/dist/vehicle-B8WqQHee.js.map +1 -0
  106. package/dist/vehicle-DYwDt5rB.cjs +2089 -0
  107. package/dist/vehicle-DYwDt5rB.cjs.map +1 -0
  108. package/dist/vehicle.cjs +12 -0
  109. package/dist/vehicle.d.ts +14 -0
  110. package/dist/vehicle.js +9 -0
  111. package/dist/vehicles/EcctrlVehicle.d.ts +109 -0
  112. package/dist/vehicles/components/ShapeCastWheel.d.ts +107 -0
  113. package/dist/vehicles/components/ThrustPropeller.d.ts +50 -0
  114. package/dist/vehicles/types.d.ts +39 -0
  115. package/package.json +155 -4
  116. package/readme.md +737 -0
  117. package/README.md +0 -3
@@ -0,0 +1,2069 @@
1
+ /*!
2
+ * Ecctrl
3
+ * https://github.com/pmndrs/ecctrl
4
+ *
5
+ * SPDX-FileCopyrightText: 2023-2026 Erdong Chen
6
+ * SPDX-License-Identifier: MIT
7
+ */
8
+ import { t as useCustomGravity } from "./useCustomGravity-elzlTR6Y.js";
9
+ import { n as evaluateCurveLUT, t as bakeCurveLUT } from "./CurveLUT-BfMhx3LX.js";
10
+ import { r as remap, t as createSlerpVec3 } from "./Math-BkrN2TZK.js";
11
+ import { a as EC_GREEN, c as EC_PURPLE, l as EC_RED, n as EC_BLUE, s as EC_MED_PURPLE, t as EC_AZURE } from "./Color-rCfz0rNn.js";
12
+ import * as THREE from "three";
13
+ import { useFrame } from "@react-three/fiber";
14
+ import { RigidBody, useRapier } from "@react-three/rapier";
15
+ import React, { createContext, forwardRef, useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef } from "react";
16
+ import { QueryFilterFlags } from "@dimforge/rapier3d-compat";
17
+ import { clamp, generateUUID, lerp } from "three/src/math/MathUtils.js";
18
+ //#region src/vehicles/EcctrlVehicle.tsx
19
+ /*!
20
+ * Ecctrl
21
+ * https://github.com/pmndrs/ecctrl
22
+ *
23
+ * SPDX-FileCopyrightText: 2023-2026 Erdong Chen
24
+ * SPDX-License-Identifier: MIT
25
+ */
26
+ var DEFAULT_CAR_CONFIG = {
27
+ controlMode: "VELOCITY",
28
+ engineHorsepower: 6,
29
+ engineMaxRPM: 6e3,
30
+ gearRatios: [10],
31
+ finalDriveRatio: 1,
32
+ transmissionMode: "auto",
33
+ shiftUpRPM: 5200,
34
+ shiftDownRPM: 2200,
35
+ shiftCooldown: .35,
36
+ steerRate: Math.PI * 2,
37
+ maxSteerAngle: Math.PI / 6,
38
+ reverseTorqueScale: 1,
39
+ reverseRPMScale: .3,
40
+ engineTorqueCurveData: {
41
+ points: [{
42
+ x: 0,
43
+ y: 1,
44
+ r_out: 0
45
+ }, {
46
+ x: 1,
47
+ y: 0,
48
+ r_in: 0
49
+ }],
50
+ samples: 50
51
+ },
52
+ steerAngleCurveData: {
53
+ points: [
54
+ {
55
+ x: 0,
56
+ y: 1,
57
+ r_out: 0
58
+ },
59
+ {
60
+ x: .2,
61
+ y: 1,
62
+ r_in: 0,
63
+ r_out: 0
64
+ },
65
+ {
66
+ x: 1,
67
+ y: .4,
68
+ r_in: 0
69
+ }
70
+ ],
71
+ samples: 50
72
+ }
73
+ };
74
+ var DEFAULT_DRONE_CONFIG = {
75
+ controlMode: "VELOCITY",
76
+ maxYawRate: 2,
77
+ maxHorizSpeed: 30,
78
+ maxVertSpeed: 8,
79
+ maxTiltAngle: Math.PI / 4,
80
+ airDragFactor: .2,
81
+ TILT_P: 15,
82
+ TILT_D: 3,
83
+ YAW_POS_P: 6,
84
+ YAW_VEL_P: 4,
85
+ VERT_POS_P: 9,
86
+ VERT_POS_D: 7,
87
+ HORIZ_POS_P: 5,
88
+ HORIZ_POS_D: 5.5,
89
+ HORIZ_VEL_P: 1,
90
+ VERT_VEL_P: 2
91
+ };
92
+ var getDriveRatio = (gearRatios, gearIndex, finalDriveRatio) => {
93
+ var _ref, _gearRatios$gearIndex;
94
+ return ((_ref = (_gearRatios$gearIndex = gearRatios[gearIndex]) !== null && _gearRatios$gearIndex !== void 0 ? _gearRatios$gearIndex : gearRatios[0]) !== null && _ref !== void 0 ? _ref : 0) * finalDriveRatio;
95
+ };
96
+ var getMaxWheelAngVel = (engineMaxRPM, driveRatio) => driveRatio !== 0 ? engineMaxRPM / driveRatio * (2 * Math.PI / 60) : 0;
97
+ var VehicleContext = createContext(null);
98
+ var EcctrlVehicle = /* @__PURE__ */ forwardRef(({ children, enable = true, carConfig = {}, droneConfig = {}, enableCustomGravity = false, gravityDirLerpSpeed = 6, ...props }, ref) => {
99
+ /**
100
+ * Rapier preset
101
+ */
102
+ const { rapier, world } = useRapier();
103
+ /**
104
+ * Vehicle controls preset
105
+ */
106
+ const carControlConfig = useMemo(() => ({
107
+ ...DEFAULT_CAR_CONFIG,
108
+ ...carConfig
109
+ }), [carConfig]);
110
+ const droneControlConfig = useMemo(() => ({
111
+ ...DEFAULT_DRONE_CONFIG,
112
+ ...droneConfig
113
+ }), [droneConfig]);
114
+ /**
115
+ * Car controller preset
116
+ */
117
+ const engineMaxTorque = useRef(0);
118
+ engineMaxTorque.current = carControlConfig.engineMaxRPM !== 0 ? carControlConfig.engineHorsepower * 7022 / carControlConfig.engineMaxRPM : 0;
119
+ const gearRatios = Array.isArray(carControlConfig.gearRatios) && carControlConfig.gearRatios.length > 0 ? carControlConfig.gearRatios : DEFAULT_CAR_CONFIG.gearRatios;
120
+ const gearIndex = useRef(0);
121
+ gearIndex.current = clamp(Math.floor(gearIndex.current), 0, gearRatios.length - 1);
122
+ const driveRatio = useRef(getDriveRatio(gearRatios, gearIndex.current, carControlConfig.finalDriveRatio));
123
+ driveRatio.current = getDriveRatio(gearRatios, gearIndex.current, carControlConfig.finalDriveRatio);
124
+ const engineRPM = useRef(0);
125
+ const shiftCooldownTimer = useRef(0);
126
+ const engineTorqueCurve = useMemo(() => {
127
+ var _carControlConfig$eng;
128
+ return bakeCurveLUT(carControlConfig.engineTorqueCurveData.points, (_carControlConfig$eng = carControlConfig.engineTorqueCurveData.samples) !== null && _carControlConfig$eng !== void 0 ? _carControlConfig$eng : 50);
129
+ }, [carControlConfig.engineTorqueCurveData]);
130
+ const steerAngleCurve = useMemo(() => {
131
+ var _carControlConfig$ste;
132
+ return bakeCurveLUT(carControlConfig.steerAngleCurveData.points || [], (_carControlConfig$ste = carControlConfig.steerAngleCurveData.samples) !== null && _carControlConfig$ste !== void 0 ? _carControlConfig$ste : 50);
133
+ }, [carControlConfig.steerAngleCurveData]);
134
+ const maxWheelAngVel = useRef(getMaxWheelAngVel(carControlConfig.engineMaxRPM, driveRatio.current));
135
+ maxWheelAngVel.current = getMaxWheelAngVel(carControlConfig.engineMaxRPM, driveRatio.current);
136
+ const driveWheelConfig = useRef({
137
+ maxDriveTorque: 0,
138
+ maxWheelAngVel: maxWheelAngVel.current,
139
+ engineTorqueCurve,
140
+ reverseTorqueScale: carControlConfig.reverseTorqueScale,
141
+ reverseRPMScale: carControlConfig.reverseRPMScale,
142
+ driveRatio: driveRatio.current
143
+ });
144
+ driveWheelConfig.current.maxWheelAngVel = maxWheelAngVel.current;
145
+ driveWheelConfig.current.engineTorqueCurve = engineTorqueCurve;
146
+ driveWheelConfig.current.reverseTorqueScale = carControlConfig.reverseTorqueScale;
147
+ driveWheelConfig.current.reverseRPMScale = carControlConfig.reverseRPMScale;
148
+ driveWheelConfig.current.driveRatio = driveRatio.current;
149
+ const steerWheelConfig = useRef({
150
+ steerAngleCurve,
151
+ steerRate: carControlConfig.steerRate,
152
+ maxSteerAngle: carControlConfig.maxSteerAngle,
153
+ maxWheelAngVel: maxWheelAngVel.current
154
+ });
155
+ steerWheelConfig.current.steerAngleCurve = steerAngleCurve;
156
+ steerWheelConfig.current.steerRate = carControlConfig.steerRate;
157
+ steerWheelConfig.current.maxSteerAngle = carControlConfig.maxSteerAngle;
158
+ steerWheelConfig.current.maxWheelAngVel = maxWheelAngVel.current;
159
+ const syncTransmissionConfig = useCallback(() => {
160
+ driveRatio.current = getDriveRatio(gearRatios, gearIndex.current, carControlConfig.finalDriveRatio);
161
+ maxWheelAngVel.current = getMaxWheelAngVel(carControlConfig.engineMaxRPM, driveRatio.current);
162
+ driveWheelConfig.current.driveRatio = driveRatio.current;
163
+ driveWheelConfig.current.maxWheelAngVel = maxWheelAngVel.current;
164
+ steerWheelConfig.current.maxWheelAngVel = maxWheelAngVel.current;
165
+ }, [
166
+ carControlConfig.engineMaxRPM,
167
+ carControlConfig.finalDriveRatio,
168
+ gearRatios
169
+ ]);
170
+ /**
171
+ * Drone controller preset
172
+ */
173
+ const maxTiltTan = useMemo(() => Math.tan(droneControlConfig.maxTiltAngle), [droneControlConfig.maxTiltAngle]);
174
+ const hoverThrottle = useRef(0);
175
+ const targetUp = useRef(new THREE.Vector3());
176
+ const tiltError = useRef(new THREE.Vector3());
177
+ const tiltAngVel = useRef(new THREE.Vector3());
178
+ const torqueWorld = useRef(new THREE.Vector3());
179
+ const torqueBody = useRef(new THREE.Vector3());
180
+ const airDragImpulse = useRef(new THREE.Vector3());
181
+ const worldThrustDir = useRef(new THREE.Vector3());
182
+ const worldThrustPos = useRef(new THREE.Vector3());
183
+ const worldTorqueDir = useRef(new THREE.Vector3());
184
+ const targetPosition = useRef(new THREE.Vector3());
185
+ const targetHeading = useRef(new THREE.Vector3());
186
+ const targetFwd = useRef(new THREE.Vector3());
187
+ const currentFwd = useRef(new THREE.Vector3());
188
+ const posError = useRef(new THREE.Vector3());
189
+ const horizPosError = useRef(new THREE.Vector3());
190
+ const horizLinVel = useRef(new THREE.Vector3());
191
+ const horizForce = useRef(new THREE.Vector3());
192
+ const worldXAxis = useRef(new THREE.Vector3());
193
+ const worldZAxis = useRef(new THREE.Vector3());
194
+ const vertAccCmd = useRef(0);
195
+ const horizAccCmd = useRef(new THREE.Vector3());
196
+ const targetLinVel = useRef(new THREE.Vector3());
197
+ const linVelError = useRef(new THREE.Vector3());
198
+ /**
199
+ * Gravity controls preset
200
+ */
201
+ const gravityField = useCustomGravity((state) => state.gravityField);
202
+ const applyGravityField = useCustomGravity((state) => state.applyGravityField);
203
+ const upAxis = useRef(new THREE.Vector3());
204
+ const referenceGravity = useRef(new THREE.Vector3());
205
+ const referenceGravityMag = useRef(0);
206
+ const referenceGravityDir = useRef(new THREE.Vector3());
207
+ const gravityDir = useRef(new THREE.Vector3());
208
+ const slerpRef = useRef(createSlerpVec3());
209
+ /**
210
+ * User controls setup
211
+ */
212
+ const movementState = useRef({
213
+ forward: false,
214
+ backward: false,
215
+ steerLeft: false,
216
+ steerRight: false,
217
+ brake: false,
218
+ throttleUp: false,
219
+ throttleDown: false,
220
+ yawLeft: false,
221
+ yawRight: false,
222
+ pitchForward: false,
223
+ pitchBackward: false,
224
+ rollLeft: false,
225
+ rollRight: false,
226
+ joystickL: {
227
+ x: 0,
228
+ y: 0
229
+ },
230
+ joystickR: {
231
+ x: 0,
232
+ y: 0
233
+ }
234
+ });
235
+ /**
236
+ * Vehicle collider/model preset
237
+ */
238
+ const vehicleRef = useRef(null);
239
+ const vehiclePos = useRef(new THREE.Vector3());
240
+ const vehicleQuat = useRef(new THREE.Quaternion());
241
+ const vehicleInvertQuat = useRef(new THREE.Quaternion());
242
+ const vehicleLinVel = useRef(new THREE.Vector3());
243
+ const vehicleAngVel = useRef(new THREE.Vector3());
244
+ const vehicleXAxis = useRef(new THREE.Vector3());
245
+ const vehicleYAxis = useRef(new THREE.Vector3());
246
+ const vehicleZAxis = useRef(new THREE.Vector3());
247
+ const setMovement = useCallback((movement) => {
248
+ if (movement.forward !== void 0) movementState.current.forward = movement.forward;
249
+ if (movement.backward !== void 0) movementState.current.backward = movement.backward;
250
+ if (movement.steerLeft !== void 0) movementState.current.steerLeft = movement.steerLeft;
251
+ if (movement.steerRight !== void 0) movementState.current.steerRight = movement.steerRight;
252
+ if (movement.brake !== void 0) movementState.current.brake = movement.brake;
253
+ if (movement.throttleUp !== void 0) movementState.current.throttleUp = movement.throttleUp;
254
+ if (movement.throttleDown !== void 0) movementState.current.throttleDown = movement.throttleDown;
255
+ if (movement.yawLeft !== void 0) movementState.current.yawLeft = movement.yawLeft;
256
+ if (movement.yawRight !== void 0) movementState.current.yawRight = movement.yawRight;
257
+ if (movement.pitchForward !== void 0) movementState.current.pitchForward = movement.pitchForward;
258
+ if (movement.pitchBackward !== void 0) movementState.current.pitchBackward = movement.pitchBackward;
259
+ if (movement.rollLeft !== void 0) movementState.current.rollLeft = movement.rollLeft;
260
+ if (movement.rollRight !== void 0) movementState.current.rollRight = movement.rollRight;
261
+ if (movement.joystickL) {
262
+ movementState.current.joystickL.x = movement.joystickL.x;
263
+ movementState.current.joystickL.y = movement.joystickL.y;
264
+ }
265
+ if (movement.joystickR) {
266
+ movementState.current.joystickR.x = movement.joystickR.x;
267
+ movementState.current.joystickR.y = movement.joystickR.y;
268
+ }
269
+ }, []);
270
+ const setTarget = useCallback((pos, dir) => {
271
+ if (pos) targetPosition.current.copy(pos);
272
+ if (dir) targetHeading.current.copy(dir);
273
+ }, []);
274
+ /**
275
+ * Register/unregister wheels information
276
+ */
277
+ const wheelsInfo = useRef(/* @__PURE__ */ new Map());
278
+ const syncWheelConfig = useCallback(() => {
279
+ let totalDriveTorqueWeight = 0;
280
+ wheelsInfo.current.forEach((wheelInfo) => {
281
+ var _wheelInfo$current$dr;
282
+ if (!wheelInfo.current.driveWheel) return;
283
+ totalDriveTorqueWeight += Math.max(0, (_wheelInfo$current$dr = wheelInfo.current.driveTorqueWeight) !== null && _wheelInfo$current$dr !== void 0 ? _wheelInfo$current$dr : 1);
284
+ });
285
+ wheelsInfo.current.forEach((wheelInfo) => {
286
+ var _wheelInfo$current$se2, _wheelInfo$current2;
287
+ if (wheelInfo.current.driveWheel) {
288
+ var _wheelInfo$current$dr2, _wheelInfo$current$se, _wheelInfo$current;
289
+ const driveTorqueWeight = Math.max(0, (_wheelInfo$current$dr2 = wheelInfo.current.driveTorqueWeight) !== null && _wheelInfo$current$dr2 !== void 0 ? _wheelInfo$current$dr2 : 1);
290
+ (_wheelInfo$current$se = (_wheelInfo$current = wheelInfo.current).setDriveWheelConfig) === null || _wheelInfo$current$se === void 0 || _wheelInfo$current$se.call(_wheelInfo$current, {
291
+ ...driveWheelConfig.current,
292
+ maxDriveTorque: totalDriveTorqueWeight > 0 ? engineMaxTorque.current * driveTorqueWeight / totalDriveTorqueWeight : 0
293
+ });
294
+ }
295
+ if (wheelInfo.current.steerWheel) (_wheelInfo$current$se2 = (_wheelInfo$current2 = wheelInfo.current).setSteerWheelConfig) === null || _wheelInfo$current$se2 === void 0 || _wheelInfo$current$se2.call(_wheelInfo$current2, steerWheelConfig.current);
296
+ });
297
+ }, []);
298
+ const regWheel = useCallback((wheelInfo) => {
299
+ const id = wheelInfo.current.id;
300
+ if (!wheelsInfo.current.has(id)) {
301
+ wheelsInfo.current.set(id, wheelInfo);
302
+ syncWheelConfig();
303
+ }
304
+ }, [syncWheelConfig]);
305
+ const unregWheel = useCallback((id) => {
306
+ if (wheelsInfo.current.delete(id)) syncWheelConfig();
307
+ }, [syncWheelConfig]);
308
+ const setGear = useCallback((index) => {
309
+ const nextGearIndex = clamp(Math.floor(index), 0, gearRatios.length - 1);
310
+ if (gearIndex.current === nextGearIndex) return;
311
+ gearIndex.current = nextGearIndex;
312
+ shiftCooldownTimer.current = carControlConfig.shiftCooldown;
313
+ syncTransmissionConfig();
314
+ syncWheelConfig();
315
+ }, [
316
+ carControlConfig.shiftCooldown,
317
+ gearRatios.length,
318
+ syncTransmissionConfig,
319
+ syncWheelConfig
320
+ ]);
321
+ useEffect(() => {
322
+ syncTransmissionConfig();
323
+ syncWheelConfig();
324
+ }, [
325
+ carControlConfig.engineHorsepower,
326
+ carControlConfig.engineMaxRPM,
327
+ carControlConfig.finalDriveRatio,
328
+ carControlConfig.maxSteerAngle,
329
+ carControlConfig.reverseRPMScale,
330
+ carControlConfig.reverseTorqueScale,
331
+ carControlConfig.steerRate,
332
+ engineTorqueCurve,
333
+ gearRatios,
334
+ steerAngleCurve,
335
+ syncTransmissionConfig,
336
+ syncWheelConfig
337
+ ]);
338
+ /**
339
+ * Register/unregister propellers information
340
+ */
341
+ const propellersInfo = useRef(/* @__PURE__ */ new Map());
342
+ const regPropeller = useCallback((propellerInfo) => {
343
+ const id = propellerInfo.current.id;
344
+ if (!propellersInfo.current.has(id)) propellersInfo.current.set(id, propellerInfo);
345
+ }, []);
346
+ const unregPropeller = useCallback((id) => propellersInfo.current.delete(id), []);
347
+ /**
348
+ * Expose vehicle info and control functions to children via ref and context
349
+ */
350
+ useImperativeHandle(ref, () => ({
351
+ get body() {
352
+ return vehicleRef.current;
353
+ },
354
+ get upAxis() {
355
+ return upAxis.current;
356
+ },
357
+ get gravityDir() {
358
+ return gravityDir.current;
359
+ },
360
+ get gravityMag() {
361
+ return referenceGravityMag.current;
362
+ },
363
+ get currPos() {
364
+ return vehiclePos.current;
365
+ },
366
+ get currQuat() {
367
+ return vehicleQuat.current;
368
+ },
369
+ get currLinVel() {
370
+ return vehicleLinVel.current;
371
+ },
372
+ get currAngVel() {
373
+ return vehicleAngVel.current;
374
+ },
375
+ get bodyXAxis() {
376
+ return vehicleXAxis.current;
377
+ },
378
+ get bodyYAxis() {
379
+ return vehicleYAxis.current;
380
+ },
381
+ get bodyZAxis() {
382
+ return vehicleZAxis.current;
383
+ },
384
+ get targetPos() {
385
+ return targetPosition.current;
386
+ },
387
+ get targetFwd() {
388
+ return targetHeading.current;
389
+ },
390
+ get input() {
391
+ return movementState.current;
392
+ },
393
+ get wheelsInfo() {
394
+ return wheelsInfo.current;
395
+ },
396
+ get propellersInfo() {
397
+ return propellersInfo.current;
398
+ },
399
+ get gearIndex() {
400
+ return gearIndex.current;
401
+ },
402
+ get driveRatio() {
403
+ return driveRatio.current;
404
+ },
405
+ get engineRPM() {
406
+ return engineRPM.current;
407
+ },
408
+ setMovement,
409
+ setTarget,
410
+ setGear
411
+ }), [
412
+ setGear,
413
+ setMovement,
414
+ setTarget
415
+ ]);
416
+ /**
417
+ *
418
+ *
419
+ *
420
+ *
421
+ *
422
+ *
423
+ *
424
+ *
425
+ *
426
+ *
427
+ *
428
+ *
429
+ *
430
+ *
431
+ *
432
+ *
433
+ *
434
+ *
435
+ *
436
+ *
437
+ *
438
+ *
439
+ *
440
+ *
441
+ *
442
+ */
443
+ /**
444
+ * Update vehicle info function
445
+ */
446
+ const updateVehicleInfo = useCallback((body) => {
447
+ vehiclePos.current.copy(body.translation());
448
+ vehicleQuat.current.copy(body.rotation());
449
+ vehicleInvertQuat.current.copy(vehicleQuat.current).invert();
450
+ vehicleLinVel.current.copy(body.linvel());
451
+ vehicleAngVel.current.copy(body.angvel());
452
+ vehicleYAxis.current.set(0, 1, 0).applyQuaternion(vehicleQuat.current);
453
+ vehicleXAxis.current.set(1, 0, 0).applyQuaternion(vehicleQuat.current);
454
+ vehicleZAxis.current.set(0, 0, 1).applyQuaternion(vehicleQuat.current);
455
+ }, []);
456
+ /**
457
+ * Update gravity/upAxis direction and value
458
+ */
459
+ const updateGravityInfo = useCallback((body) => {
460
+ if (enableCustomGravity) {
461
+ referenceGravity.current.copy(gravityField(vehiclePos.current));
462
+ applyGravityField(body, world.timestep);
463
+ } else referenceGravity.current.copy(world.gravity);
464
+ referenceGravityMag.current = referenceGravity.current.length();
465
+ referenceGravityDir.current.copy(referenceGravity.current).normalize();
466
+ if (referenceGravityDir.current.lengthSq() === 0) referenceGravityDir.current.copy(vehicleYAxis.current).negate();
467
+ gravityDir.current.copy(slerpRef.current(gravityDir.current, referenceGravityDir.current, 1 - Math.exp(-gravityDirLerpSpeed * world.timestep), vehicleZAxis.current));
468
+ upAxis.current.copy(gravityDir.current).negate();
469
+ }, [
470
+ enableCustomGravity,
471
+ gravityDirLerpSpeed,
472
+ gravityField,
473
+ applyGravityField
474
+ ]);
475
+ /**
476
+ *
477
+ *
478
+ *
479
+ *
480
+ *
481
+ *
482
+ *
483
+ *
484
+ *
485
+ *
486
+ *
487
+ *
488
+ *
489
+ *
490
+ *
491
+ *
492
+ *
493
+ *
494
+ *
495
+ *
496
+ *
497
+ *
498
+ *
499
+ *
500
+ *
501
+ */
502
+ /**
503
+ * Car overall control logics
504
+ */
505
+ const updateTransmission = useCallback((wheels) => {
506
+ let totalWheelRPM = 0;
507
+ let totalDriveTorqueWeight = 0;
508
+ wheels.forEach((wheel) => {
509
+ var _wheel$current$driveT;
510
+ if (!wheel.current.driveWheel) return;
511
+ const driveTorqueWeight = Math.max(0, (_wheel$current$driveT = wheel.current.driveTorqueWeight) !== null && _wheel$current$driveT !== void 0 ? _wheel$current$driveT : 1);
512
+ totalWheelRPM += Math.abs(wheel.current.wheelAngVel) * 60 / (Math.PI * 2) * driveTorqueWeight;
513
+ totalDriveTorqueWeight += driveTorqueWeight;
514
+ });
515
+ engineRPM.current = (totalDriveTorqueWeight > 0 ? totalWheelRPM / totalDriveTorqueWeight : 0) * Math.abs(driveRatio.current);
516
+ if (carControlConfig.transmissionMode !== "auto" || gearRatios.length <= 1) return;
517
+ if (shiftCooldownTimer.current > 0) {
518
+ shiftCooldownTimer.current = Math.max(0, shiftCooldownTimer.current - world.timestep);
519
+ return;
520
+ }
521
+ if (engineRPM.current > carControlConfig.shiftUpRPM && gearIndex.current < gearRatios.length - 1) setGear(gearIndex.current + 1);
522
+ else if (engineRPM.current < carControlConfig.shiftDownRPM && gearIndex.current > 0) setGear(gearIndex.current - 1);
523
+ }, [
524
+ carControlConfig.shiftDownRPM,
525
+ carControlConfig.shiftUpRPM,
526
+ carControlConfig.transmissionMode,
527
+ gearRatios.length,
528
+ setGear,
529
+ world.timestep
530
+ ]);
531
+ const velocityBasedCarControl = useCallback((input, wheels) => {
532
+ var _input$joystickL$x, _input$joystickL;
533
+ const driveIn = clamp((input.forward ? 1 : 0) - (input.backward ? 1 : 0), -1, 1);
534
+ const steerIn = clamp((input.steerLeft ? 1 : 0) - (input.steerRight ? 1 : 0) - ((_input$joystickL$x = (_input$joystickL = input.joystickL) === null || _input$joystickL === void 0 ? void 0 : _input$joystickL.x) !== null && _input$joystickL$x !== void 0 ? _input$joystickL$x : 0), -1, 1);
535
+ const brakeIn = input.brake ? 1 : 0;
536
+ wheels.forEach((wheel) => {
537
+ if (wheel.current.driveWheel && wheel.current.setDriveDemand) wheel.current.setDriveDemand(driveIn);
538
+ if (wheel.current.brakeWheel && wheel.current.setBrakeDemand) wheel.current.setBrakeDemand(brakeIn);
539
+ if (wheel.current.steerWheel && wheel.current.setSteerDemand) wheel.current.setSteerDemand(steerIn);
540
+ });
541
+ }, []);
542
+ const applyWheelImpulse = useCallback((wheels, body) => {
543
+ if (!body) return;
544
+ if (body.isSleeping()) {
545
+ let shouldWake = false;
546
+ for (const wheel of wheels.values()) {
547
+ const w = wheel.current;
548
+ if (!w.rayHit) continue;
549
+ if (w.isOnPlatform || Math.abs(w.wheelLinVel) > 1e-4) {
550
+ shouldWake = true;
551
+ break;
552
+ }
553
+ }
554
+ if (!shouldWake) return;
555
+ body.wakeUp();
556
+ return;
557
+ }
558
+ wheels.forEach((wheel) => {
559
+ if (!wheel.current.rayHit) return;
560
+ body.applyImpulseAtPoint(wheel.current.floatImp, wheel.current.supPos, false);
561
+ body.applyImpulseAtPoint(wheel.current.lngFricImp, wheel.current.rayHitPos, false);
562
+ body.applyImpulseAtPoint(wheel.current.latFricImp, wheel.current.rayHitPos, false);
563
+ });
564
+ }, []);
565
+ const applyCarControl = useCallback((wheels, body, input) => {
566
+ if (!body) return;
567
+ updateTransmission(wheels);
568
+ velocityBasedCarControl(input, wheels);
569
+ applyWheelImpulse(wheels, body);
570
+ }, [
571
+ applyWheelImpulse,
572
+ updateTransmission,
573
+ velocityBasedCarControl
574
+ ]);
575
+ /**
576
+ *
577
+ *
578
+ *
579
+ *
580
+ *
581
+ *
582
+ *
583
+ *
584
+ *
585
+ *
586
+ *
587
+ *
588
+ *
589
+ *
590
+ *
591
+ *
592
+ *
593
+ *
594
+ *
595
+ *
596
+ *
597
+ *
598
+ *
599
+ *
600
+ *
601
+ *
602
+ */
603
+ /**
604
+ * Drone overall control logics
605
+ */
606
+ const propellerPotential = useRef({
607
+ sumLX: 0,
608
+ sumLY: 0,
609
+ sumLZ: 0,
610
+ sumAX: 0,
611
+ sumAY: 0,
612
+ sumAZ: 0
613
+ });
614
+ const computePropellerPotential = useCallback((propellers) => {
615
+ let sumLX = 0, sumLY = 0, sumLZ = 0;
616
+ let sumAX = 0, sumAY = 0, sumAZ = 0;
617
+ propellers.forEach((p) => {
618
+ sumLX += p.current.lx;
619
+ sumLY += p.current.ly;
620
+ sumLZ += p.current.lz;
621
+ sumAX += Math.abs(p.current.ax);
622
+ sumAY += Math.abs(p.current.ay);
623
+ sumAZ += Math.abs(p.current.az);
624
+ });
625
+ propellerPotential.current.sumLX = sumLX;
626
+ propellerPotential.current.sumLY = sumLY;
627
+ propellerPotential.current.sumLZ = sumLZ;
628
+ propellerPotential.current.sumAX = sumAX;
629
+ propellerPotential.current.sumAY = sumAY;
630
+ propellerPotential.current.sumAZ = sumAZ;
631
+ }, []);
632
+ const positionBasedDroneControl = useCallback((weight, sumWorldLY) => {
633
+ posError.current.subVectors(targetPosition.current, vehiclePos.current);
634
+ const vertPosErrorMag = posError.current.dot(upAxis.current);
635
+ horizPosError.current.copy(posError.current).projectOnPlane(upAxis.current);
636
+ const vertLinVelMag = vehicleLinVel.current.dot(upAxis.current);
637
+ horizLinVel.current.copy(vehicleLinVel.current).projectOnPlane(upAxis.current);
638
+ const vertForceMag = weight + clamp(vertPosErrorMag * droneControlConfig.VERT_POS_P, -droneControlConfig.VERT_POS_D * droneControlConfig.maxVertSpeed, droneControlConfig.VERT_POS_D * droneControlConfig.maxVertSpeed) - vertLinVelMag * droneControlConfig.VERT_POS_D;
639
+ hoverThrottle.current = Math.max(0, vertForceMag / (sumWorldLY || 1));
640
+ horizForce.current.set(0, 0, 0).addScaledVector(horizPosError.current, droneControlConfig.HORIZ_POS_P).addScaledVector(horizLinVel.current, -droneControlConfig.HORIZ_POS_D).clampLength(0, droneControlConfig.HORIZ_POS_D * droneControlConfig.maxHorizSpeed);
641
+ targetUp.current.copy(upAxis.current).multiplyScalar(weight).add(horizForce.current.clampLength(0, weight * maxTiltTan)).normalize();
642
+ tiltError.current.crossVectors(vehicleYAxis.current, targetUp.current);
643
+ tiltAngVel.current.copy(vehicleAngVel.current).projectOnPlane(upAxis.current);
644
+ targetFwd.current.copy(targetHeading.current).projectOnPlane(upAxis.current).normalize();
645
+ currentFwd.current.copy(vehicleZAxis.current).projectOnPlane(upAxis.current).normalize();
646
+ const yawError = targetFwd.current.angleTo(currentFwd.current) * Math.sign(currentFwd.current.cross(targetFwd.current).dot(upAxis.current));
647
+ const currentYawRate = vehicleAngVel.current.dot(upAxis.current);
648
+ const yawRateError = clamp(yawError * droneControlConfig.YAW_POS_P, -droneControlConfig.maxYawRate, droneControlConfig.maxYawRate) - currentYawRate;
649
+ torqueWorld.current.set(0, 0, 0).addScaledVector(tiltError.current, droneControlConfig.TILT_P).addScaledVector(tiltAngVel.current, -droneControlConfig.TILT_D).addScaledVector(upAxis.current, yawRateError * droneControlConfig.YAW_VEL_P);
650
+ torqueBody.current.copy(torqueWorld.current).applyQuaternion(vehicleInvertQuat.current);
651
+ }, [droneControlConfig, maxTiltTan]);
652
+ const velocityBasedDroneControl = useCallback((input, body, weight, sumWorldLY) => {
653
+ var _input$joystickL$y, _input$joystickL2, _input$joystickL$x2, _input$joystickL3, _input$joystickR$y, _input$joystickR, _input$joystickR$x, _input$joystickR2;
654
+ const throttleIn = clamp((input.throttleUp ? 1 : 0) - (input.throttleDown ? 1 : 0) + ((_input$joystickL$y = (_input$joystickL2 = input.joystickL) === null || _input$joystickL2 === void 0 ? void 0 : _input$joystickL2.y) !== null && _input$joystickL$y !== void 0 ? _input$joystickL$y : 0), -1, 1);
655
+ const yawIn = clamp((input.yawLeft ? 1 : 0) - (input.yawRight ? 1 : 0) - ((_input$joystickL$x2 = (_input$joystickL3 = input.joystickL) === null || _input$joystickL3 === void 0 ? void 0 : _input$joystickL3.x) !== null && _input$joystickL$x2 !== void 0 ? _input$joystickL$x2 : 0), -1, 1);
656
+ const pitchIn = clamp((input.pitchForward ? 1 : 0) - (input.pitchBackward ? 1 : 0) + ((_input$joystickR$y = (_input$joystickR = input.joystickR) === null || _input$joystickR === void 0 ? void 0 : _input$joystickR.y) !== null && _input$joystickR$y !== void 0 ? _input$joystickR$y : 0), -1, 1);
657
+ const rollIn = clamp((input.rollRight ? 1 : 0) - (input.rollLeft ? 1 : 0) + ((_input$joystickR$x = (_input$joystickR2 = input.joystickR) === null || _input$joystickR2 === void 0 ? void 0 : _input$joystickR2.x) !== null && _input$joystickR$x !== void 0 ? _input$joystickR$x : 0), -1, 1);
658
+ worldXAxis.current.copy(vehicleXAxis.current).projectOnPlane(upAxis.current).normalize();
659
+ worldZAxis.current.copy(vehicleZAxis.current).projectOnPlane(upAxis.current).normalize();
660
+ targetLinVel.current.set(0, 0, 0).addScaledVector(worldXAxis.current, -rollIn * droneControlConfig.maxHorizSpeed).addScaledVector(worldZAxis.current, pitchIn * droneControlConfig.maxHorizSpeed).addScaledVector(upAxis.current, throttleIn * droneControlConfig.maxVertSpeed);
661
+ linVelError.current.subVectors(targetLinVel.current, vehicleLinVel.current);
662
+ vertAccCmd.current = clamp(linVelError.current.dot(upAxis.current) * droneControlConfig.VERT_VEL_P, -referenceGravityMag.current, referenceGravityMag.current);
663
+ horizAccCmd.current.copy(linVelError.current).projectOnPlane(upAxis.current).multiplyScalar(droneControlConfig.HORIZ_VEL_P).clampLength(0, referenceGravityMag.current * maxTiltTan);
664
+ const verticalForceMag = weight + vertAccCmd.current * body.mass();
665
+ hoverThrottle.current = Math.max(0, verticalForceMag / (sumWorldLY || 1));
666
+ targetUp.current.copy(upAxis.current).multiplyScalar(referenceGravityMag.current).add(horizAccCmd.current).normalize();
667
+ tiltError.current.crossVectors(vehicleYAxis.current, targetUp.current);
668
+ tiltAngVel.current.copy(vehicleAngVel.current).projectOnPlane(upAxis.current);
669
+ const currentYawRate = vehicleAngVel.current.dot(upAxis.current);
670
+ const yawRateError = yawIn * droneControlConfig.maxYawRate - currentYawRate;
671
+ torqueWorld.current.set(0, 0, 0).addScaledVector(tiltError.current, droneControlConfig.TILT_P).addScaledVector(tiltAngVel.current, -droneControlConfig.TILT_D).addScaledVector(upAxis.current, yawRateError * droneControlConfig.YAW_VEL_P);
672
+ torqueBody.current.copy(torqueWorld.current).applyQuaternion(vehicleInvertQuat.current);
673
+ }, [droneControlConfig, maxTiltTan]);
674
+ const computePropellerFinalThrottle = useCallback((propeller, maxSafeMix) => {
675
+ const mix = torqueBody.current.x * propeller.ax / (propellerPotential.current.sumAX || 1) + torqueBody.current.z * propeller.az / (propellerPotential.current.sumAZ || 1) + torqueBody.current.y * propeller.ay / (propellerPotential.current.sumAY || 1);
676
+ return clamp(hoverThrottle.current + clamp(mix, -maxSafeMix, maxSafeMix), 0, 1);
677
+ }, []);
678
+ const applyMixerImpulse = useCallback((propellers, body) => {
679
+ const maxSafeMix = Math.min(1 - hoverThrottle.current, hoverThrottle.current);
680
+ if (body.isSleeping()) {
681
+ let shouldWake = false;
682
+ for (const propeller of propellers.values()) {
683
+ const info = propeller.current;
684
+ const finalThrottle = computePropellerFinalThrottle(info, maxSafeMix);
685
+ if (Math.abs(finalThrottle - info.throttle) > 1e-4) {
686
+ shouldWake = true;
687
+ break;
688
+ }
689
+ }
690
+ if (!shouldWake) return;
691
+ body.wakeUp();
692
+ }
693
+ propellers.forEach((propeller) => {
694
+ const info = propeller.current;
695
+ const finalThrottle = computePropellerFinalThrottle(info, maxSafeMix);
696
+ info.finalThrottle = finalThrottle;
697
+ if (info.setThrottle) info.setThrottle(finalThrottle);
698
+ worldThrustDir.current.copy(info.thrustDir).applyQuaternion(vehicleQuat.current).normalize();
699
+ worldThrustPos.current.copy(info.thrustPos).applyQuaternion(vehicleQuat.current).add(vehiclePos.current);
700
+ worldTorqueDir.current.copy(info.torqueDir).applyQuaternion(vehicleQuat.current).normalize();
701
+ info.worldThrustDir.copy(worldThrustDir.current);
702
+ info.worldThrustPos.copy(worldThrustPos.current);
703
+ info.worldTorqueDir.copy(worldTorqueDir.current);
704
+ info.thrustImpulse.copy(worldThrustDir.current).multiplyScalar(info.maxThrust * finalThrottle * world.timestep);
705
+ info.torqueImpulse.copy(worldTorqueDir.current).multiplyScalar(info.maxThrust * finalThrottle * world.timestep * info.torqueRatio);
706
+ body.applyImpulseAtPoint(info.thrustImpulse, info.worldThrustPos, false);
707
+ body.applyTorqueImpulse(info.torqueImpulse, false);
708
+ });
709
+ }, [computePropellerFinalThrottle]);
710
+ const applyAirDrag = useCallback((body) => {
711
+ airDragImpulse.current.copy(vehicleLinVel.current).multiplyScalar(-droneControlConfig.airDragFactor * world.timestep);
712
+ body.applyImpulse(airDragImpulse.current, false);
713
+ }, [droneControlConfig.airDragFactor, world.timestep]);
714
+ const applyDroneControl = useCallback((propellers, body, input) => {
715
+ if (!body) return;
716
+ computePropellerPotential(propellers);
717
+ const sumWorldLY = propellerPotential.current.sumLX * vehicleXAxis.current.dot(upAxis.current) + propellerPotential.current.sumLY * vehicleYAxis.current.dot(upAxis.current) + propellerPotential.current.sumLZ * vehicleZAxis.current.dot(upAxis.current);
718
+ const weight = body.mass() * referenceGravityMag.current;
719
+ switch (droneControlConfig.controlMode) {
720
+ case "POSITION":
721
+ positionBasedDroneControl(weight, sumWorldLY);
722
+ break;
723
+ case "VELOCITY":
724
+ velocityBasedDroneControl(input, body, weight, sumWorldLY);
725
+ break;
726
+ }
727
+ applyMixerImpulse(propellers, body);
728
+ applyAirDrag(body);
729
+ }, [
730
+ computePropellerPotential,
731
+ positionBasedDroneControl,
732
+ velocityBasedDroneControl,
733
+ droneControlConfig.controlMode,
734
+ applyMixerImpulse,
735
+ applyAirDrag
736
+ ]);
737
+ /**
738
+ *
739
+ *
740
+ *
741
+ *
742
+ *
743
+ *
744
+ *
745
+ *
746
+ *
747
+ *
748
+ *
749
+ *
750
+ *
751
+ *
752
+ *
753
+ *
754
+ *
755
+ *
756
+ *
757
+ */
758
+ useFrame(() => {
759
+ if (!enable || !vehicleRef.current) return;
760
+ /**
761
+ * Update when character is not sleeping
762
+ */
763
+ if (!vehicleRef.current.isSleeping()) {
764
+ updateVehicleInfo(vehicleRef.current);
765
+ updateGravityInfo(vehicleRef.current);
766
+ }
767
+ /**
768
+ * Apply drive/brake/friction impulse from shape cast wheels
769
+ * whenever there is a wheel component
770
+ */
771
+ if (wheelsInfo.current.size > 0) applyCarControl(wheelsInfo.current, vehicleRef.current, movementState.current);
772
+ /**
773
+ * Apply drone control logics
774
+ * whenever there is a propeller component
775
+ */
776
+ if (propellersInfo.current.size > 0) applyDroneControl(propellersInfo.current, vehicleRef.current, movementState.current);
777
+ });
778
+ /**
779
+ *
780
+ *
781
+ *
782
+ *
783
+ *
784
+ *
785
+ *
786
+ *
787
+ *
788
+ *
789
+ *
790
+ *
791
+ */
792
+ const vehicleContextValue = useMemo(() => ({
793
+ body: vehicleRef,
794
+ upAxis,
795
+ gravityDir,
796
+ gravityMag: referenceGravityMag,
797
+ currPos: vehiclePos,
798
+ currQuat: vehicleQuat,
799
+ currLinvel: vehicleLinVel,
800
+ currAngvel: vehicleAngVel,
801
+ bodyXAxis: vehicleXAxis,
802
+ bodyYAxis: vehicleYAxis,
803
+ bodyZAxis: vehicleZAxis,
804
+ movementState,
805
+ wheelsInfo,
806
+ propellersInfo,
807
+ regWheel,
808
+ unregWheel,
809
+ regPropeller,
810
+ unregPropeller
811
+ }), [
812
+ regWheel,
813
+ unregWheel,
814
+ regPropeller,
815
+ unregPropeller
816
+ ]);
817
+ return /* @__PURE__ */ React.createElement(VehicleContext.Provider, { value: vehicleContextValue }, /* @__PURE__ */ React.createElement(RigidBody, {
818
+ colliders: false,
819
+ ref: vehicleRef,
820
+ ...props
821
+ }, children));
822
+ });
823
+ var EcctrlVehicle_default = React.memo(EcctrlVehicle);
824
+ //#endregion
825
+ //#region src/vehicles/components/ShapeCastWheel.tsx
826
+ /*!
827
+ * Ecctrl
828
+ * https://github.com/pmndrs/ecctrl
829
+ *
830
+ * SPDX-FileCopyrightText: 2023-2026 Erdong Chen
831
+ * SPDX-License-Identifier: MIT
832
+ */
833
+ var ShapeCastWheel = /* @__PURE__ */ forwardRef(({ children, debug = false, enable = true, name = "", groundDetection = "shapeCast", rayShapeR = .5, rayShapeH = .15, rayLength = .5, springK = 180, dampingC = 16, driveInvert = false, driveWheel = false, driveTorqueWeight = 1, steerInvert = false, steerWheel = false, brakeWheel = false, maxBrakeTorque = 40, rollingResistanceCoef = .007, lowVelThreshold = .4, tireGripFactor = 1.5, lngFrictionEllipseScale = 1, latFrictionEllipseScale = 1, relaxLngRate = .05, relaxLatRate = .1, minLngRelaxCoeff = .3, minLatRelaxCoeff = .3, lngSlipRatioCurveData = { points: [
834
+ {
835
+ x: 0,
836
+ y: 0,
837
+ r_out: 1.45
838
+ },
839
+ {
840
+ x: .25,
841
+ y: 1,
842
+ r_in: 0,
843
+ r_out: 0
844
+ },
845
+ {
846
+ x: 1,
847
+ y: .7,
848
+ r_in: 0
849
+ }
850
+ ] }, latSlipRatioCurveData = { points: [
851
+ {
852
+ x: 0,
853
+ y: 0,
854
+ r_out: 1.45
855
+ },
856
+ {
857
+ x: .15,
858
+ y: 1,
859
+ r_in: 0,
860
+ r_out: 0
861
+ },
862
+ {
863
+ x: 1,
864
+ y: .9,
865
+ r_in: 0
866
+ }
867
+ ] }, followPlatform = true, massRatioFallOffCurveData = { points: [
868
+ {
869
+ x: 0,
870
+ y: .5,
871
+ r_out: 0
872
+ },
873
+ {
874
+ x: .5,
875
+ y: 1,
876
+ r_out: 0
877
+ },
878
+ {
879
+ x: 1,
880
+ y: 1,
881
+ r_in: 0
882
+ }
883
+ ] }, applyCounterMass = true, applyCounterFriction = true, showWheelModel = true, wheelModelDensity = 1.5, wheelModelUpdate = true, wheelModelRadius = .5, wheelModelLerpPosRate = 10, wheelModelReversRotation = false, debuggerArrowScale = 10, ...props }, ref) => {
884
+ /**
885
+ * Rapier preset
886
+ */
887
+ const { rapier, world } = useRapier();
888
+ /**
889
+ * Retrieve context object from ecctrl vehicle
890
+ */
891
+ const vehicleValue = useContext(VehicleContext);
892
+ const fixedScale = useMemo(() => new THREE.Vector3(1, 1, 1), []);
893
+ useMemo(() => new THREE.Vector3(0, 0, 0), []);
894
+ useMemo(() => new THREE.Vector3(1, 0, 0), []);
895
+ useMemo(() => new THREE.Vector3(0, 1, 0), []);
896
+ const fixedZAxis = useMemo(() => new THREE.Vector3(0, 0, 1), []);
897
+ const vehiclePos = useRef(new THREE.Vector3());
898
+ const vehicleQuat = useRef(new THREE.Quaternion());
899
+ const vehicleInvertQuat = useRef(new THREE.Quaternion());
900
+ const vehicleMatrix = useRef(new THREE.Matrix4());
901
+ const vehicleInvertMatrix = useRef(new THREE.Matrix4());
902
+ const vehicleLinVel = useRef(new THREE.Vector3());
903
+ const vehicleAngVel = useRef(new THREE.Vector3());
904
+ const vehicleXAxis = useRef(new THREE.Vector3());
905
+ const vehicleYAxis = useRef(new THREE.Vector3());
906
+ const vehicleZAxis = useRef(new THREE.Vector3());
907
+ /**
908
+ * Wheel physical properties and states
909
+ */
910
+ const effectiveInertia = useRef(0);
911
+ const wheelAngVel = useRef(0);
912
+ const supportPoint = useRef(new THREE.Vector3());
913
+ const wheelVolume = useMemo(() => Math.PI * rayShapeR * rayShapeR * (rayShapeH * 2), [rayShapeR, rayShapeH]);
914
+ const wheelMass = useMemo(() => wheelModelDensity * wheelVolume, [wheelModelDensity, wheelVolume]);
915
+ const wheelInertia = useMemo(() => .5 * wheelMass * rayShapeR * rayShapeR, [wheelMass, rayShapeR]);
916
+ /**
917
+ * Control preset
918
+ */
919
+ const frictionCoef = useRef(0);
920
+ const lngAxis = useRef(new THREE.Vector3());
921
+ const latAxis = useRef(new THREE.Vector3());
922
+ const lngFrictionImp = useRef(new THREE.Vector3());
923
+ const latFrictionImp = useRef(new THREE.Vector3());
924
+ const lngSlipRatioCurve = useMemo(() => {
925
+ var _lngSlipRatioCurveDat;
926
+ return bakeCurveLUT(lngSlipRatioCurveData.points, (_lngSlipRatioCurveDat = lngSlipRatioCurveData.samples) !== null && _lngSlipRatioCurveDat !== void 0 ? _lngSlipRatioCurveDat : 50);
927
+ }, [lngSlipRatioCurveData]);
928
+ const latSlipRatioCurve = useMemo(() => {
929
+ var _latSlipRatioCurveDat;
930
+ return bakeCurveLUT(latSlipRatioCurveData.points, (_latSlipRatioCurveDat = latSlipRatioCurveData.samples) !== null && _latSlipRatioCurveDat !== void 0 ? _latSlipRatioCurveDat : 50);
931
+ }, [latSlipRatioCurveData]);
932
+ const lngSlipRatio = useRef(0);
933
+ const latSlipRatio = useRef(0);
934
+ const slipStrength = useRef(0);
935
+ const smoothedLngImpulse = useRef(0);
936
+ const smoothedLatImpulse = useRef(0);
937
+ const desiredLngImpulse = useRef(0);
938
+ const desiredLatImpulse = useRef(0);
939
+ const steerAngle = useRef(0);
940
+ const steerTarget = useRef(0);
941
+ const steerIncrement = useRef(0);
942
+ const steerDemand = useRef(0);
943
+ const steerWheelConfig = useRef(null);
944
+ const setSteerDemand = useCallback((value) => steerDemand.current = value, []);
945
+ const setSteerWheelConfig = useCallback((value) => steerWheelConfig.current = value, []);
946
+ const driveTorque = useRef(0);
947
+ const driveDemand = useRef(0);
948
+ const driveWheelConfig = useRef(null);
949
+ const setDriveDemand = useCallback((value) => driveDemand.current = value, []);
950
+ const setDriveWheelConfig = useCallback((value) => driveWheelConfig.current = value, []);
951
+ const brakeTorque = useRef(0);
952
+ const brakeDemand = useRef(0);
953
+ const setBrakeDemand = useCallback((value) => brakeDemand.current = value, []);
954
+ /**
955
+ * Shape cast preset
956
+ */
957
+ const distFromRayOriginToVehicle = useRef(new THREE.Vector3());
958
+ const angvelToLinvel = useRef(new THREE.Vector3());
959
+ const floatingImpulse = useRef(new THREE.Vector3());
960
+ const rayOrigin = useRef(new THREE.Vector3());
961
+ const rayRotation = useRef(new THREE.Quaternion());
962
+ const rayDirection = useRef(new THREE.Vector3());
963
+ const rayOriginVel = useRef(new THREE.Vector3());
964
+ const rayUpAxis = useRef(new THREE.Vector3());
965
+ const rayFWDAxis = useRef(new THREE.Vector3());
966
+ const rayBWDAxis = useRef(new THREE.Vector3());
967
+ const rayLeftAxis = useRef(new THREE.Vector3());
968
+ const rayShape = useMemo(() => new rapier.Cylinder(rayShapeH, rayShapeR), [rayShapeH, rayShapeR]);
969
+ const rotZ90 = useMemo(() => new THREE.Quaternion().setFromAxisAngle(fixedZAxis, Math.PI / 2), []);
970
+ const shapeRayHit = useRef(null);
971
+ const rayHit = useRef(null);
972
+ const rayCast = useMemo(() => new rapier.Ray(rayOrigin.current, rayDirection.current), [rapier]);
973
+ const suspensionToi = useRef(0);
974
+ const rayHitBody = useRef(null);
975
+ const rayShapeCenter = useRef(new THREE.Vector3());
976
+ const stableRayHitPoint = useRef(new THREE.Vector3());
977
+ const targetRayHitPoint = useRef(new THREE.Vector3());
978
+ const rayHitPointOffset = useRef(new THREE.Vector3());
979
+ const rayHitPointPosition = useRef(new THREE.Vector3());
980
+ const rayHitPointVelocity = useRef(new THREE.Vector3());
981
+ const rayHitPointVelOnPlane = useRef(new THREE.Vector3());
982
+ const rayHitPointNormal = useRef(new THREE.Vector3());
983
+ const rayHitPointFriction = useRef(0);
984
+ useEffect(() => {
985
+ if (groundDetection === "rayCast") shapeRayHit.current = null;
986
+ else rayHit.current = null;
987
+ }, [groundDetection]);
988
+ /**
989
+ * Moving platform preset
990
+ */
991
+ const massRatio = useRef(1);
992
+ const isOnMovingObject = useRef(false);
993
+ const wheelSupportForceMag = useRef(0);
994
+ const wheelSupportImpulse = useRef(new THREE.Vector3());
995
+ const wheelFrictionImpulse = useRef(new THREE.Vector3());
996
+ const movingObjectPosition = useRef(new THREE.Vector3());
997
+ const movingObjectVelocity = useRef(new THREE.Vector3());
998
+ const movingObjectVelocityOnPlane = useRef(new THREE.Vector3());
999
+ const movingObjectLinearVelocity = useRef(new THREE.Vector3());
1000
+ const movingObjectAngularVelocity = useRef(new THREE.Vector3());
1001
+ const distanceFromOriginToObjectPoint = useRef(new THREE.Vector3());
1002
+ const movingObjectAngvelToLinvel = useRef(new THREE.Vector3());
1003
+ const massRatioFallOffCurve = useMemo(() => {
1004
+ var _massRatioFallOffCurv;
1005
+ return bakeCurveLUT(massRatioFallOffCurveData.points, (_massRatioFallOffCurv = massRatioFallOffCurveData.samples) !== null && _massRatioFallOffCurv !== void 0 ? _massRatioFallOffCurv : 50);
1006
+ }, [massRatioFallOffCurveData]);
1007
+ /**
1008
+ * Wheel ref preset and handles
1009
+ */
1010
+ const shapeCastWheelRef = useRef(null);
1011
+ const modelRef = useRef(null);
1012
+ const wheelRef = useRef(null);
1013
+ const worldPos = useRef(new THREE.Vector3());
1014
+ const worldQuat = useRef(new THREE.Quaternion());
1015
+ useImperativeHandle(ref, () => shapeCastWheelRef.current, []);
1016
+ /**
1017
+ * Register wheel information
1018
+ */
1019
+ const wheelId = useMemo(() => {
1020
+ var _props$id;
1021
+ return String((_props$id = props.id) !== null && _props$id !== void 0 ? _props$id : generateUUID());
1022
+ }, [props.id]);
1023
+ const wheelInfo = useRef({
1024
+ id: wheelId,
1025
+ name,
1026
+ enable,
1027
+ debug,
1028
+ rayShapeR,
1029
+ rayShapeH,
1030
+ rayLength,
1031
+ springK,
1032
+ dampingC,
1033
+ steerInvert,
1034
+ steerWheel,
1035
+ driveInvert,
1036
+ driveWheel,
1037
+ driveTorqueWeight,
1038
+ brakeWheel,
1039
+ maxBrakeTorque,
1040
+ rollingResistanceCoef,
1041
+ lowVelThreshold,
1042
+ tireGripFactor,
1043
+ lngFrictionEllipseScale,
1044
+ latFrictionEllipseScale,
1045
+ relaxLngRate,
1046
+ relaxLatRate,
1047
+ minLngRelaxCoeff,
1048
+ minLatRelaxCoeff,
1049
+ followPlatform,
1050
+ applyCounterMass,
1051
+ applyCounterFriction,
1052
+ showWheelModel,
1053
+ wheelModelDensity,
1054
+ wheelModelUpdate,
1055
+ wheelModelRadius,
1056
+ wheelModelLerpPosRate,
1057
+ wheelModelReversRotation,
1058
+ debuggerArrowScale,
1059
+ rayPos: new THREE.Vector3(),
1060
+ rayDir: new THREE.Vector3(),
1061
+ rayRot: new THREE.Quaternion(),
1062
+ rayUpDir: new THREE.Vector3(),
1063
+ rayFwdDir: new THREE.Vector3(),
1064
+ rayLeftDir: new THREE.Vector3(),
1065
+ floatImp: new THREE.Vector3(),
1066
+ rayHit: null,
1067
+ rayHitBody: null,
1068
+ rayHitPos: new THREE.Vector3(),
1069
+ rayHitNormal: new THREE.Vector3(),
1070
+ rayHitFriciton: 0,
1071
+ rayOriginVel: new THREE.Vector3(),
1072
+ rayHitPointVel: new THREE.Vector3(),
1073
+ isOnPlatform: false,
1074
+ lngSlipRatio: 0,
1075
+ latSlipRatio: 0,
1076
+ slipStrength: 0,
1077
+ lngAxis: new THREE.Vector3(),
1078
+ latAxis: new THREE.Vector3(),
1079
+ lngFricImp: new THREE.Vector3(),
1080
+ latFricImp: new THREE.Vector3(),
1081
+ effInertia: 0,
1082
+ supPos: new THREE.Vector3(),
1083
+ steerAngle: 0,
1084
+ driveTorque: 0,
1085
+ brakeTorque: 0,
1086
+ wheelLinVel: 0,
1087
+ wheelAngVel: 0,
1088
+ setDriveDemand,
1089
+ setBrakeDemand,
1090
+ setSteerDemand,
1091
+ setDriveWheelConfig,
1092
+ setSteerWheelConfig
1093
+ });
1094
+ wheelInfo.current.driveWheel = driveWheel;
1095
+ wheelInfo.current.driveTorqueWeight = driveTorqueWeight;
1096
+ wheelInfo.current.steerWheel = steerWheel;
1097
+ /**
1098
+ * Register the wheel to vehicle on mount, and unregister on unmount
1099
+ */
1100
+ useEffect(() => {
1101
+ vehicleValue === null || vehicleValue === void 0 || vehicleValue.regWheel(wheelInfo);
1102
+ return () => vehicleValue === null || vehicleValue === void 0 ? void 0 : vehicleValue.unregWheel(wheelId);
1103
+ }, [
1104
+ vehicleValue,
1105
+ wheelId,
1106
+ driveWheel,
1107
+ driveTorqueWeight,
1108
+ steerWheel
1109
+ ]);
1110
+ /**
1111
+ * Debug indicators preset
1112
+ */
1113
+ const forwardIndicatorRef = useRef(null);
1114
+ const rayHitPointRef = useRef(null);
1115
+ const xAxisPointRef = useRef(null);
1116
+ const yAxisPointRef = useRef(null);
1117
+ const zAxisPointRef = useRef(null);
1118
+ const currFloatArrowRef = useRef(null);
1119
+ const currFloatArrowDir = useRef(new THREE.Vector3());
1120
+ const currDriftArrowRef = useRef(null);
1121
+ const currDriftArrowDir = useRef(new THREE.Vector3());
1122
+ const currEngineArrowRef = useRef(null);
1123
+ const currEngineArrowDir = useRef(new THREE.Vector3());
1124
+ const debugAssets = useMemo(() => {
1125
+ if (!debug) return null;
1126
+ return {
1127
+ forwardRingGeo: new THREE.RingGeometry(rayShapeH * 1.6, rayShapeH * 2, 12),
1128
+ forwardPointerGeo: new THREE.PlaneGeometry(rayShapeH, rayShapeH),
1129
+ forwardIndicatorMat: new THREE.MeshBasicMaterial({
1130
+ color: EC_AZURE,
1131
+ side: THREE.DoubleSide
1132
+ }),
1133
+ rayCastGeo: new THREE.CircleGeometry(rayShapeH * .5, 12),
1134
+ rayCastHalfGeo: new THREE.CylinderGeometry(rayShapeR, rayShapeR, rayShapeH * 2, 12, 1, true, 0, -Math.PI),
1135
+ rayCastMat: new THREE.MeshBasicMaterial({
1136
+ color: EC_MED_PURPLE,
1137
+ side: THREE.DoubleSide,
1138
+ transparent: true,
1139
+ opacity: .5
1140
+ }),
1141
+ standingGeo: new THREE.OctahedronGeometry(rayShapeH * .5, 3),
1142
+ standingMat: new THREE.MeshBasicMaterial({
1143
+ color: EC_PURPLE,
1144
+ transparent: true,
1145
+ opacity: .5
1146
+ }),
1147
+ xAxisPointMat: new THREE.MeshBasicMaterial({
1148
+ color: EC_GREEN,
1149
+ transparent: true,
1150
+ opacity: 1
1151
+ }),
1152
+ yAxisPointMat: new THREE.MeshBasicMaterial({
1153
+ color: EC_BLUE,
1154
+ transparent: true,
1155
+ opacity: 1
1156
+ }),
1157
+ zAxisPointMat: new THREE.MeshBasicMaterial({
1158
+ color: EC_RED,
1159
+ transparent: true,
1160
+ opacity: 1
1161
+ })
1162
+ };
1163
+ }, [
1164
+ debug,
1165
+ rayShapeR,
1166
+ rayShapeH
1167
+ ]);
1168
+ useEffect(() => {
1169
+ return () => {
1170
+ if (!debugAssets) return;
1171
+ for (const key in debugAssets) {
1172
+ const item = debugAssets[key];
1173
+ if ("dispose" in item && typeof item.dispose === "function") item.dispose();
1174
+ }
1175
+ };
1176
+ }, [debugAssets]);
1177
+ /**
1178
+ *
1179
+ *
1180
+ *
1181
+ *
1182
+ *
1183
+ *
1184
+ *
1185
+ *
1186
+ *
1187
+ *
1188
+ *
1189
+ *
1190
+ *
1191
+ *
1192
+ *
1193
+ *
1194
+ *
1195
+ *
1196
+ *
1197
+ *
1198
+ *
1199
+ *
1200
+ *
1201
+ *
1202
+ *
1203
+ *
1204
+ *
1205
+ *
1206
+ *
1207
+ */
1208
+ /**
1209
+ * Update vehicle/wheel info function
1210
+ * (needs to recompute vehicle's info for each wheel, to gain the most updated info)
1211
+ */
1212
+ const updateVehicleInfo = useCallback((body) => {
1213
+ vehiclePos.current.copy(body.translation());
1214
+ vehicleQuat.current.copy(body.rotation());
1215
+ vehicleMatrix.current.compose(vehiclePos.current, vehicleQuat.current, fixedScale);
1216
+ vehicleYAxis.current.set(0, 1, 0).applyQuaternion(vehicleQuat.current);
1217
+ vehicleXAxis.current.set(1, 0, 0).applyQuaternion(vehicleQuat.current);
1218
+ vehicleZAxis.current.set(0, 0, 1).applyQuaternion(vehicleQuat.current);
1219
+ vehicleLinVel.current.copy(body.linvel());
1220
+ vehicleAngVel.current.copy(body.angvel());
1221
+ wheelInfo.current.rayPos = rayOrigin.current;
1222
+ wheelInfo.current.rayDir = rayDirection.current;
1223
+ wheelInfo.current.rayRot = rayRotation.current;
1224
+ wheelInfo.current.rayUpDir = rayUpAxis.current;
1225
+ wheelInfo.current.rayFwdDir = rayFWDAxis.current;
1226
+ wheelInfo.current.rayLeftDir = rayLeftAxis.current;
1227
+ wheelInfo.current.rayHit = groundDetection === "rayCast" ? rayHit.current : shapeRayHit.current;
1228
+ wheelInfo.current.rayHitBody = rayHitBody.current;
1229
+ wheelInfo.current.rayHitPos = rayHitPointPosition.current;
1230
+ wheelInfo.current.rayHitNormal = rayHitPointNormal.current;
1231
+ wheelInfo.current.rayHitFriciton = rayHitPointFriction.current;
1232
+ wheelInfo.current.rayOriginVel = rayOriginVel.current;
1233
+ wheelInfo.current.rayHitPointVel = rayHitPointVelocity.current;
1234
+ wheelInfo.current.isOnPlatform = isOnMovingObject.current;
1235
+ wheelInfo.current.floatImp = floatingImpulse.current;
1236
+ wheelInfo.current.lngSlipRatio = lngSlipRatio.current;
1237
+ wheelInfo.current.latSlipRatio = latSlipRatio.current;
1238
+ wheelInfo.current.slipStrength = slipStrength.current;
1239
+ wheelInfo.current.lngAxis = lngAxis.current;
1240
+ wheelInfo.current.latAxis = latAxis.current;
1241
+ wheelInfo.current.lngFricImp = lngFrictionImp.current;
1242
+ wheelInfo.current.latFricImp = latFrictionImp.current;
1243
+ wheelInfo.current.effInertia = effectiveInertia.current;
1244
+ wheelInfo.current.supPos = supportPoint.current;
1245
+ wheelInfo.current.steerAngle = steerAngle.current;
1246
+ wheelInfo.current.driveTorque = driveTorque.current;
1247
+ wheelInfo.current.brakeTorque = brakeTorque.current;
1248
+ wheelInfo.current.wheelAngVel = wheelAngVel.current;
1249
+ wheelInfo.current.wheelLinVel = wheelAngVel.current * rayShapeR;
1250
+ }, [groundDetection, rayShapeR]);
1251
+ /**
1252
+ * Compute ray hit point relative velocity
1253
+ */
1254
+ const computeRelativeVelocity = useCallback(() => {
1255
+ rayHitPointVelocity.current.copy(rayOriginVel.current);
1256
+ rayHitPointVelOnPlane.current.copy(rayHitPointVelocity.current).projectOnPlane(rayHitPointNormal.current);
1257
+ if (isOnMovingObject.current && followPlatform) {
1258
+ rayHitPointVelocity.current.sub(movingObjectVelocity.current);
1259
+ rayHitPointVelOnPlane.current.sub(movingObjectVelocityOnPlane.current);
1260
+ }
1261
+ }, [followPlatform]);
1262
+ /**
1263
+ * Update shape cast info
1264
+ */
1265
+ const updateShapeCastDir = useCallback(() => {
1266
+ if (!shapeCastWheelRef.current) return;
1267
+ if (steerWheel) shapeCastWheelRef.current.rotateY(steerIncrement.current);
1268
+ shapeCastWheelRef.current.getWorldPosition(worldPos.current);
1269
+ shapeCastWheelRef.current.getWorldQuaternion(worldQuat.current);
1270
+ rayOrigin.current.copy(worldPos.current);
1271
+ rayDirection.current.set(0, -1, 0).applyQuaternion(worldQuat.current);
1272
+ rayUpAxis.current.copy(rayDirection.current).negate();
1273
+ rayFWDAxis.current.set(0, 0, 1).applyQuaternion(worldQuat.current);
1274
+ rayBWDAxis.current.copy(rayFWDAxis.current).negate();
1275
+ rayLeftAxis.current.crossVectors(rayUpAxis.current, rayFWDAxis.current).normalize();
1276
+ distFromRayOriginToVehicle.current.copy(rayOrigin.current).sub(vehiclePos.current);
1277
+ angvelToLinvel.current.crossVectors(vehicleAngVel.current, distFromRayOriginToVehicle.current);
1278
+ rayOriginVel.current.copy(vehicleLinVel.current).add(angvelToLinvel.current);
1279
+ }, [steerWheel]);
1280
+ /**
1281
+ * Floating function
1282
+ */
1283
+ const ecctrlVehicleRayFilter = useCallback((collider) => {
1284
+ var _collider$parent, _userData$ecctrl, _userData$ecctrl2;
1285
+ const userData = (_collider$parent = collider.parent) === null || _collider$parent === void 0 || (_collider$parent = _collider$parent.call(collider)) === null || _collider$parent === void 0 ? void 0 : _collider$parent.userData;
1286
+ return !((userData === null || userData === void 0 || (_userData$ecctrl = userData.ecctrl) === null || _userData$ecctrl === void 0 ? void 0 : _userData$ecctrl.excludeRay) || (userData === null || userData === void 0 || (_userData$ecctrl2 = userData.ecctrl) === null || _userData$ecctrl2 === void 0 ? void 0 : _userData$ecctrl2.excludeVehicleRay));
1287
+ }, []);
1288
+ const floatVehicle = useCallback((body) => {
1289
+ var _rayHit$current, _shapeRayHit$current, _rayHit$current2, _shapeRayHit$current2;
1290
+ if (groundDetection === "rayCast") rayHit.current = world.castRayAndGetNormal(rayCast, rayLength + rayShapeR, false, QueryFilterFlags.EXCLUDE_SENSORS, void 0, void 0, body, ecctrlVehicleRayFilter);
1291
+ else shapeRayHit.current = world.castShape(rayOrigin.current, rayRotation.current.copy(worldQuat.current).multiply(rotZ90), rayDirection.current, rayShape, 0, rayLength, false, QueryFilterFlags.EXCLUDE_SENSORS, void 0, void 0, body, ecctrlVehicleRayFilter);
1292
+ const hitCollider = groundDetection === "rayCast" ? (_rayHit$current = rayHit.current) === null || _rayHit$current === void 0 ? void 0 : _rayHit$current.collider : (_shapeRayHit$current = shapeRayHit.current) === null || _shapeRayHit$current === void 0 ? void 0 : _shapeRayHit$current.collider;
1293
+ const hitDistance = groundDetection === "rayCast" ? (_rayHit$current2 = rayHit.current) === null || _rayHit$current2 === void 0 ? void 0 : _rayHit$current2.timeOfImpact : (_shapeRayHit$current2 = shapeRayHit.current) === null || _shapeRayHit$current2 === void 0 ? void 0 : _shapeRayHit$current2.time_of_impact;
1294
+ if (hitCollider && hitDistance != null) {
1295
+ var _hitCollider$friction;
1296
+ suspensionToi.current = groundDetection === "rayCast" ? Math.max(0, hitDistance - rayShapeR) : hitDistance;
1297
+ rayHitBody.current = hitCollider.parent();
1298
+ if (groundDetection === "rayCast") targetRayHitPoint.current.copy(rayOrigin.current).addScaledVector(rayDirection.current, hitDistance);
1299
+ else targetRayHitPoint.current.copy(shapeRayHit.current.witness1);
1300
+ rayHitPointNormal.current.copy(groundDetection === "rayCast" ? rayHit.current.normal : shapeRayHit.current.normal1).normalize();
1301
+ rayShapeCenter.current.copy(rayOrigin.current).addScaledVector(rayDirection.current, suspensionToi.current);
1302
+ let supportOffset = 0;
1303
+ if (groundDetection === "rayCast") stableRayHitPoint.current.copy(targetRayHitPoint.current);
1304
+ else {
1305
+ const rawOffset = clamp(rayHitPointOffset.current.copy(targetRayHitPoint.current).sub(rayShapeCenter.current).dot(rayLeftAxis.current), -rayShapeH, rayShapeH);
1306
+ stableRayHitPoint.current.copy(targetRayHitPoint.current).addScaledVector(rayLeftAxis.current, -rawOffset);
1307
+ const normalSide = rayHitPointNormal.current.dot(rayLeftAxis.current);
1308
+ const normalFwd = rayHitPointNormal.current.dot(rayFWDAxis.current);
1309
+ const sideWeight = clamp(Math.abs(normalSide) / Math.sqrt(Math.max(1 - normalFwd * normalFwd, 1e-6)), 0, 1);
1310
+ supportOffset = -Math.abs(rawOffset) * Math.sign(normalSide) * sideWeight;
1311
+ }
1312
+ rayHitPointPosition.current.copy(stableRayHitPoint.current).addScaledVector(rayLeftAxis.current, supportOffset);
1313
+ supportPoint.current.copy(rayShapeCenter.current).addScaledVector(rayLeftAxis.current, supportOffset);
1314
+ if (rayHitPointFriction.current !== hitCollider.friction()) rayHitPointFriction.current = (_hitCollider$friction = hitCollider.friction()) !== null && _hitCollider$friction !== void 0 ? _hitCollider$friction : 0;
1315
+ const springForce = springK * Math.max(0, rayLength - suspensionToi.current);
1316
+ const dampingForce = dampingC * rayHitPointVelocity.current.dot(rayUpAxis.current);
1317
+ floatingImpulse.current.copy(rayHitPointNormal.current).multiplyScalar(springForce - dampingForce).multiplyScalar(world.timestep);
1318
+ } else {
1319
+ rayHitBody.current = null;
1320
+ suspensionToi.current = 0;
1321
+ rayHitPointFriction.current = 0;
1322
+ floatingImpulse.current.set(0, 0, 0);
1323
+ }
1324
+ }, [
1325
+ groundDetection,
1326
+ rayCast,
1327
+ rayShape,
1328
+ rayLength,
1329
+ rayShapeR,
1330
+ rayShapeH,
1331
+ springK,
1332
+ dampingC,
1333
+ ecctrlVehicleRayFilter
1334
+ ]);
1335
+ /**
1336
+ * Detect is on a moving object
1337
+ */
1338
+ const isOnMovingObjectDetect = useCallback((body) => {
1339
+ if (followPlatform && rayHitBody.current && (rayHitBody.current.bodyType() === 0 || rayHitBody.current.bodyType() === 2)) {
1340
+ isOnMovingObject.current = true;
1341
+ if (rayHitBody.current.bodyType() === 0) massRatio.current = evaluateCurveLUT(clamp(rayHitBody.current.mass() / Math.max(body.mass(), 1e-6), 0, 1), massRatioFallOffCurve);
1342
+ else massRatio.current = 1;
1343
+ movingObjectPosition.current.copy(rayHitBody.current.translation());
1344
+ distanceFromOriginToObjectPoint.current.copy(rayOrigin.current).sub(movingObjectPosition.current);
1345
+ movingObjectLinearVelocity.current.copy(rayHitBody.current.linvel());
1346
+ movingObjectAngularVelocity.current.copy(rayHitBody.current.angvel());
1347
+ movingObjectAngvelToLinvel.current.crossVectors(movingObjectAngularVelocity.current, distanceFromOriginToObjectPoint.current);
1348
+ movingObjectVelocity.current.copy(movingObjectLinearVelocity.current).add(movingObjectAngvelToLinvel.current).multiplyScalar(massRatio.current);
1349
+ movingObjectVelocityOnPlane.current.copy(movingObjectVelocity.current).projectOnPlane(rayHitPointNormal.current);
1350
+ } else {
1351
+ isOnMovingObject.current = false;
1352
+ movingObjectVelocity.current.set(0, 0, 0);
1353
+ movingObjectVelocityOnPlane.current.set(0, 0, 0);
1354
+ massRatio.current = 1;
1355
+ }
1356
+ }, [followPlatform, massRatioFallOffCurve]);
1357
+ /**
1358
+ * Apply wheel mass on standing collider
1359
+ */
1360
+ const applyMassOnStandCollider = useCallback(() => {
1361
+ if (!rayHitBody.current || rayHitBody.current.bodyType() !== 0 || !applyCounterMass) return;
1362
+ wheelSupportImpulse.current.copy(rayHitPointNormal.current).multiplyScalar(-1 * wheelSupportForceMag.current * world.timestep * massRatio.current);
1363
+ if (wheelSupportForceMag.current > 0) rayHitBody.current.applyImpulseAtPoint(wheelSupportImpulse.current, rayHitPointPosition.current, true);
1364
+ }, [applyCounterMass]);
1365
+ /**
1366
+ * Apply tire friction on standing collider
1367
+ */
1368
+ const applyFricitonOnStandCollider = useCallback(() => {
1369
+ if (!rayHitBody.current || rayHitBody.current.bodyType() !== 0 || !applyCounterFriction) return;
1370
+ wheelFrictionImpulse.current.addVectors(lngFrictionImp.current, latFrictionImp.current).multiplyScalar(-1 * massRatio.current);
1371
+ if (wheelFrictionImpulse.current.lengthSq() > 1e-4) rayHitBody.current.applyImpulseAtPoint(wheelFrictionImpulse.current, rayHitPointPosition.current, true);
1372
+ }, [applyCounterFriction]);
1373
+ /**
1374
+ * Handle user input function
1375
+ */
1376
+ const handleUserInput = useCallback(() => {
1377
+ const currDriveConfig = driveWheelConfig.current;
1378
+ const currSteerConfig = steerWheelConfig.current;
1379
+ if (driveWheel && currDriveConfig && currDriveConfig.maxDriveTorque !== 0) {
1380
+ const maxAngVel = currDriveConfig.maxWheelAngVel * (driveDemand.current < 0 ? currDriveConfig.reverseRPMScale : 1);
1381
+ const angvelRatio = maxAngVel > 0 ? Math.abs(wheelAngVel.current) / maxAngVel : 1;
1382
+ driveTorque.current = driveDemand.current * currDriveConfig.maxDriveTorque * currDriveConfig.driveRatio * (driveDemand.current < 0 ? currDriveConfig.reverseTorqueScale : 1) * evaluateCurveLUT(angvelRatio, currDriveConfig.engineTorqueCurve) * (driveInvert ? -1 : 1);
1383
+ }
1384
+ if (steerWheel && currSteerConfig) {
1385
+ var _currSteerConfig$maxW;
1386
+ const steerMaxWheelAngVel = (_currSteerConfig$maxW = currSteerConfig === null || currSteerConfig === void 0 ? void 0 : currSteerConfig.maxWheelAngVel) !== null && _currSteerConfig$maxW !== void 0 ? _currSteerConfig$maxW : 0;
1387
+ const speedRatio = steerMaxWheelAngVel > 0 ? clamp(vehicleLinVel.current.dot(vehicleZAxis.current) / (steerMaxWheelAngVel * rayShapeR), 0, 1) : 0;
1388
+ steerTarget.current = steerDemand.current * currSteerConfig.maxSteerAngle * evaluateCurveLUT(speedRatio, currSteerConfig.steerAngleCurve) * (steerInvert ? -1 : 1);
1389
+ }
1390
+ if (brakeWheel) brakeTorque.current = brakeDemand.current * maxBrakeTorque;
1391
+ }, [
1392
+ driveWheel,
1393
+ driveInvert,
1394
+ maxBrakeTorque,
1395
+ steerWheel,
1396
+ steerInvert
1397
+ ]);
1398
+ /**
1399
+ * Steering wheel function
1400
+ */
1401
+ const steeringWheel = useCallback(() => {
1402
+ var _steerWheelConfig$cur, _steerWheelConfig$cur2;
1403
+ const angleDiff = steerTarget.current - steerAngle.current;
1404
+ const maxIncrement = ((_steerWheelConfig$cur = (_steerWheelConfig$cur2 = steerWheelConfig.current) === null || _steerWheelConfig$cur2 === void 0 ? void 0 : _steerWheelConfig$cur2.steerRate) !== null && _steerWheelConfig$cur !== void 0 ? _steerWheelConfig$cur : 0) * world.timestep;
1405
+ steerIncrement.current = Math.sign(angleDiff) * Math.min(Math.abs(angleDiff), maxIncrement);
1406
+ steerAngle.current += steerIncrement.current;
1407
+ }, [steerWheelConfig]);
1408
+ /**
1409
+ * Compute friction coefficient based on contact surface friction and tire grip factor
1410
+ */
1411
+ const computeContactFriction = useCallback(() => {
1412
+ if (rayHitBody.current) frictionCoef.current = Math.max((rayHitPointFriction.current + tireGripFactor) * .5, 0);
1413
+ else frictionCoef.current = 0;
1414
+ }, [tireGripFactor]);
1415
+ /**
1416
+ * Compute longitudinal and lateral friction impulses based on wheel slip and contact conditions
1417
+ */
1418
+ const computeWheelFrictionImpulse = useCallback((gravityMag) => {
1419
+ if (!rayHitBody.current) {
1420
+ wheelSupportForceMag.current = wheelMass * gravityMag;
1421
+ effectiveInertia.current = wheelInertia + wheelSupportForceMag.current / gravityMag * rayShapeR * rayShapeR;
1422
+ lngSlipRatio.current = 0;
1423
+ latSlipRatio.current = 0;
1424
+ slipStrength.current = 0;
1425
+ return;
1426
+ }
1427
+ wheelSupportForceMag.current = Math.max(floatingImpulse.current.dot(rayHitPointNormal.current), 0) / world.timestep;
1428
+ effectiveInertia.current = wheelInertia + wheelSupportForceMag.current / gravityMag * rayShapeR * rayShapeR;
1429
+ lngAxis.current.copy(rayFWDAxis.current).projectOnPlane(rayHitPointNormal.current).normalize();
1430
+ latAxis.current.copy(rayLeftAxis.current).projectOnPlane(rayHitPointNormal.current).normalize();
1431
+ const lngContactVel = rayHitPointVelocity.current.dot(lngAxis.current);
1432
+ const latContactVel = rayHitPointVelocity.current.dot(latAxis.current);
1433
+ const lngContactVelAbs = Math.abs(lngContactVel);
1434
+ const latContactVelAbs = Math.abs(latContactVel);
1435
+ const slipDiff = wheelAngVel.current * rayShapeR - lngContactVel;
1436
+ const slipDiffAbs = Math.abs(slipDiff);
1437
+ lngSlipRatio.current = slipDiffAbs / Math.max(lngContactVelAbs, 1e-4);
1438
+ latSlipRatio.current = latContactVelAbs === 0 && lngContactVelAbs === 0 ? 0 : clamp(Math.atan2(latContactVelAbs, lngContactVelAbs) / (Math.PI / 2), 0, 1);
1439
+ slipStrength.current = Math.max(lngSlipRatio.current, latSlipRatio.current);
1440
+ const lngSlipValue = evaluateCurveLUT(lngSlipRatio.current, lngSlipRatioCurve);
1441
+ const latSlipValue = evaluateCurveLUT(latSlipRatio.current, latSlipRatioCurve);
1442
+ const finalLngSlipValue = remap(clamp(1 - Math.max(slipDiffAbs, lngContactVelAbs) / lowVelThreshold, 0, 1), 0, 1, lngSlipValue, 1);
1443
+ const finalLatSlipValue = remap(clamp(1 - Math.max(latContactVelAbs, lngContactVelAbs) / lowVelThreshold, 0, 1), 0, 1, latSlipValue, 1);
1444
+ const maxLngImp = wheelSupportForceMag.current * finalLngSlipValue * frictionCoef.current * world.timestep * lngFrictionEllipseScale;
1445
+ const maxLatImp = wheelSupportForceMag.current * finalLatSlipValue * frictionCoef.current * world.timestep * latFrictionEllipseScale;
1446
+ desiredLngImpulse.current = slipDiff * effectiveInertia.current / (rayShapeR * rayShapeR);
1447
+ desiredLatImpulse.current = latContactVel * (wheelSupportForceMag.current / gravityMag);
1448
+ const ellipseUsage = Math.sqrt(desiredLngImpulse.current / maxLngImp * desiredLngImpulse.current / maxLngImp + desiredLatImpulse.current / maxLatImp * desiredLatImpulse.current / maxLatImp);
1449
+ if (ellipseUsage > 1) {
1450
+ desiredLngImpulse.current /= ellipseUsage;
1451
+ desiredLatImpulse.current /= ellipseUsage;
1452
+ }
1453
+ let lngCoeff = clamp(Math.max(minLngRelaxCoeff, lngContactVelAbs / Math.max(relaxLngRate, 1e-6) * world.timestep), 0, 1);
1454
+ let latCoeff = clamp(Math.max(minLatRelaxCoeff, latContactVelAbs / Math.max(relaxLatRate, 1e-6) * world.timestep), 0, 1);
1455
+ smoothedLngImpulse.current += (desiredLngImpulse.current - smoothedLngImpulse.current) * lngCoeff;
1456
+ smoothedLatImpulse.current += (desiredLatImpulse.current - smoothedLatImpulse.current) * latCoeff;
1457
+ lngFrictionImp.current.copy(lngAxis.current).multiplyScalar(smoothedLngImpulse.current);
1458
+ latFrictionImp.current.copy(latAxis.current).multiplyScalar(-smoothedLatImpulse.current);
1459
+ }, [
1460
+ wheelMass,
1461
+ wheelInertia,
1462
+ rayShapeR,
1463
+ lowVelThreshold,
1464
+ lngSlipRatioCurve,
1465
+ latSlipRatioCurve,
1466
+ lngFrictionEllipseScale,
1467
+ latFrictionEllipseScale,
1468
+ relaxLngRate,
1469
+ relaxLatRate,
1470
+ minLngRelaxCoeff,
1471
+ minLatRelaxCoeff
1472
+ ]);
1473
+ /**
1474
+ * Solve wheel rotation based on drive/brake torque and friction torque
1475
+ */
1476
+ const solveWheelRotation = useCallback(() => {
1477
+ const isDriving = driveWheel && Math.abs(driveTorque.current) > 0 && rayHitBody.current;
1478
+ const isBraking = brakeWheel && Math.abs(brakeTorque.current) > 0 && rayHitBody.current;
1479
+ const isFreeRolling = !isDriving && !isBraking;
1480
+ if (rayHitBody.current) wheelAngVel.current -= lngFrictionImp.current.dot(lngAxis.current) * rayShapeR / effectiveInertia.current;
1481
+ if (rayHitBody.current && isFreeRolling || !rayHitBody.current && wheelAngVel.current !== 0) {
1482
+ const rollingResistTorque = -rollingResistanceCoef * wheelSupportForceMag.current * wheelAngVel.current;
1483
+ wheelAngVel.current += rollingResistTorque / effectiveInertia.current * world.timestep;
1484
+ }
1485
+ if (isDriving && !isBraking) wheelAngVel.current += driveTorque.current / effectiveInertia.current * world.timestep;
1486
+ if (isBraking) {
1487
+ const appliedBrakeTorque = brakeTorque.current * -Math.sign(wheelAngVel.current);
1488
+ wheelAngVel.current += Math.min(Math.abs(wheelAngVel.current), Math.abs(appliedBrakeTorque / effectiveInertia.current) * world.timestep) * -Math.sign(wheelAngVel.current);
1489
+ }
1490
+ }, [
1491
+ rollingResistanceCoef,
1492
+ effectiveInertia,
1493
+ driveTorque,
1494
+ brakeTorque,
1495
+ rayShapeR,
1496
+ driveWheel,
1497
+ brakeWheel
1498
+ ]);
1499
+ /**
1500
+ * Update wheel models
1501
+ */
1502
+ const updateWheelModel = useCallback(() => {
1503
+ if (!wheelRef.current || !modelRef.current || !wheelModelUpdate) return;
1504
+ const offsetY = (groundDetection === "rayCast" ? rayHit.current : shapeRayHit.current) ? -(rayLength + rayShapeR) + wheelModelRadius + (rayLength - suspensionToi.current) : -(rayLength + rayShapeR) + wheelModelRadius;
1505
+ wheelRef.current.position.y = THREE.MathUtils.lerp(wheelRef.current.position.y, offsetY, 1 - Math.exp(-wheelModelLerpPosRate * world.timestep));
1506
+ modelRef.current.rotation.x += wheelAngVel.current * world.timestep * (wheelModelReversRotation ? -1 : 1);
1507
+ }, [
1508
+ groundDetection,
1509
+ wheelModelRadius,
1510
+ rayLength,
1511
+ rayShapeR,
1512
+ wheelModelLerpPosRate,
1513
+ rayLength,
1514
+ rayShapeR
1515
+ ]);
1516
+ /**
1517
+ * Update debug indicators
1518
+ */
1519
+ const updateDebugger = useCallback(() => {
1520
+ const hasContact = groundDetection === "rayCast" ? rayHit.current : shapeRayHit.current;
1521
+ vehicleInvertQuat.current.copy(vehicleQuat.current).invert();
1522
+ vehicleInvertMatrix.current.copy(vehicleMatrix.current).invert();
1523
+ if (rayHitPointRef.current) rayHitPointRef.current.position.copy(rayHitPointPosition.current).applyMatrix4(vehicleInvertMatrix.current);
1524
+ if (!shapeCastWheelRef.current) return;
1525
+ if (currFloatArrowRef.current) {
1526
+ currFloatArrowRef.current.position.copy(shapeCastWheelRef.current.position);
1527
+ currFloatArrowDir.current.copy(rayHitPointNormal.current).applyQuaternion(vehicleInvertQuat.current);
1528
+ currFloatArrowRef.current.setDirection(currFloatArrowDir.current);
1529
+ const length = hasContact ? wheelSupportForceMag.current * world.timestep * debuggerArrowScale : 0;
1530
+ currFloatArrowRef.current.setLength(length);
1531
+ }
1532
+ if (currDriftArrowRef.current) {
1533
+ currDriftArrowRef.current.position.copy(shapeCastWheelRef.current.position);
1534
+ currDriftArrowDir.current.copy(latAxis.current).negate().applyQuaternion(vehicleInvertQuat.current);
1535
+ currDriftArrowRef.current.setDirection(currDriftArrowDir.current);
1536
+ const length = hasContact ? desiredLatImpulse.current * debuggerArrowScale : 0;
1537
+ currDriftArrowRef.current.setLength(length);
1538
+ }
1539
+ if (currEngineArrowRef.current) {
1540
+ currEngineArrowRef.current.position.copy(shapeCastWheelRef.current.position);
1541
+ currEngineArrowDir.current.copy(lngAxis.current).applyQuaternion(vehicleInvertQuat.current);
1542
+ currEngineArrowRef.current.setDirection(currEngineArrowDir.current);
1543
+ const length = hasContact ? desiredLngImpulse.current * debuggerArrowScale : 0;
1544
+ currEngineArrowRef.current.setLength(length);
1545
+ }
1546
+ }, [groundDetection, debuggerArrowScale]);
1547
+ /**
1548
+ *
1549
+ *
1550
+ *
1551
+ *
1552
+ *
1553
+ *
1554
+ *
1555
+ *
1556
+ *
1557
+ *
1558
+ *
1559
+ *
1560
+ *
1561
+ *
1562
+ *
1563
+ *
1564
+ *
1565
+ *
1566
+ *
1567
+ *
1568
+ *
1569
+ *
1570
+ *
1571
+ *
1572
+ */
1573
+ useFrame(() => {
1574
+ if (!vehicleValue || !enable) return;
1575
+ const vehicleBody = vehicleValue.body.current;
1576
+ const vehicleGravityMag = vehicleValue.gravityMag.current;
1577
+ if (!vehicleBody) return;
1578
+ updateVehicleInfo(vehicleBody);
1579
+ updateShapeCastDir();
1580
+ handleUserInput();
1581
+ steeringWheel();
1582
+ floatVehicle(vehicleBody);
1583
+ isOnMovingObjectDetect(vehicleBody);
1584
+ applyMassOnStandCollider();
1585
+ applyFricitonOnStandCollider();
1586
+ computeRelativeVelocity();
1587
+ computeContactFriction();
1588
+ computeWheelFrictionImpulse(vehicleGravityMag);
1589
+ solveWheelRotation();
1590
+ updateWheelModel();
1591
+ if (debug) updateDebugger();
1592
+ });
1593
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("group", {
1594
+ ref: shapeCastWheelRef,
1595
+ ...props
1596
+ }, showWheelModel && /* @__PURE__ */ React.createElement("group", { ref: wheelRef }, /* @__PURE__ */ React.createElement("group", { ref: modelRef }, children)), debug && debugAssets && /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("group", { ref: forwardIndicatorRef }, /* @__PURE__ */ React.createElement("mesh", {
1597
+ rotation: [
1598
+ Math.PI / 2,
1599
+ 0,
1600
+ 0
1601
+ ],
1602
+ geometry: debugAssets.forwardRingGeo,
1603
+ material: debugAssets.forwardIndicatorMat
1604
+ }), /* @__PURE__ */ React.createElement("mesh", {
1605
+ rotation: [
1606
+ Math.PI / 2,
1607
+ 0,
1608
+ Math.PI / 4
1609
+ ],
1610
+ position: [
1611
+ 0,
1612
+ 0,
1613
+ rayShapeH * 1.6
1614
+ ],
1615
+ geometry: debugAssets.forwardPointerGeo,
1616
+ material: debugAssets.forwardIndicatorMat
1617
+ })), groundDetection === "shapeCast" && /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("mesh", {
1618
+ rotation: [
1619
+ Math.PI,
1620
+ 0,
1621
+ Math.PI / 2
1622
+ ],
1623
+ geometry: debugAssets.rayCastHalfGeo,
1624
+ material: debugAssets.rayCastMat
1625
+ }), /* @__PURE__ */ React.createElement("mesh", {
1626
+ position: [
1627
+ 0,
1628
+ -rayLength,
1629
+ 0
1630
+ ],
1631
+ rotation: [
1632
+ 0,
1633
+ 0,
1634
+ Math.PI / 2
1635
+ ],
1636
+ geometry: debugAssets.rayCastHalfGeo,
1637
+ material: debugAssets.rayCastMat
1638
+ })), groundDetection === "rayCast" && /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("mesh", {
1639
+ rotation: [
1640
+ -Math.PI / 2,
1641
+ 0,
1642
+ 0
1643
+ ],
1644
+ geometry: debugAssets.rayCastGeo,
1645
+ material: debugAssets.rayCastMat
1646
+ }), /* @__PURE__ */ React.createElement("mesh", {
1647
+ position: [
1648
+ 0,
1649
+ -(rayLength + rayShapeR),
1650
+ 0
1651
+ ],
1652
+ rotation: [
1653
+ -Math.PI / 2,
1654
+ 0,
1655
+ 0
1656
+ ],
1657
+ geometry: debugAssets.rayCastGeo,
1658
+ material: debugAssets.rayCastMat
1659
+ })), /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("mesh", {
1660
+ ref: xAxisPointRef,
1661
+ position: [
1662
+ 1,
1663
+ 0,
1664
+ 0
1665
+ ],
1666
+ geometry: debugAssets.standingGeo,
1667
+ material: debugAssets.xAxisPointMat
1668
+ }), /* @__PURE__ */ React.createElement("mesh", {
1669
+ ref: yAxisPointRef,
1670
+ position: [
1671
+ 0,
1672
+ 1,
1673
+ 0
1674
+ ],
1675
+ geometry: debugAssets.standingGeo,
1676
+ material: debugAssets.yAxisPointMat
1677
+ }), /* @__PURE__ */ React.createElement("mesh", {
1678
+ ref: zAxisPointRef,
1679
+ position: [
1680
+ 0,
1681
+ 0,
1682
+ 1
1683
+ ],
1684
+ geometry: debugAssets.standingGeo,
1685
+ material: debugAssets.zAxisPointMat
1686
+ })))), debug && debugAssets && /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("mesh", {
1687
+ ref: rayHitPointRef,
1688
+ geometry: debugAssets.standingGeo,
1689
+ material: debugAssets.standingMat
1690
+ }), /* @__PURE__ */ React.createElement("arrowHelper", {
1691
+ ref: currFloatArrowRef,
1692
+ args: [
1693
+ void 0,
1694
+ void 0,
1695
+ void 0,
1696
+ "#87CEFA"
1697
+ ]
1698
+ }), /* @__PURE__ */ React.createElement("arrowHelper", {
1699
+ ref: currDriftArrowRef,
1700
+ args: [
1701
+ void 0,
1702
+ void 0,
1703
+ void 0,
1704
+ "#96FA87"
1705
+ ]
1706
+ }), /* @__PURE__ */ React.createElement("arrowHelper", {
1707
+ ref: currEngineArrowRef,
1708
+ args: [
1709
+ void 0,
1710
+ void 0,
1711
+ void 0,
1712
+ "#FA8787"
1713
+ ]
1714
+ })));
1715
+ });
1716
+ var ShapeCastWheel_default = React.memo(ShapeCastWheel);
1717
+ //#endregion
1718
+ //#region src/vehicles/components/ThrustPropeller.tsx
1719
+ /*!
1720
+ * Ecctrl
1721
+ * https://github.com/pmndrs/ecctrl
1722
+ *
1723
+ * SPDX-FileCopyrightText: 2023-2026 Erdong Chen
1724
+ * SPDX-License-Identifier: MIT
1725
+ */
1726
+ var ThrustPropeller = /* @__PURE__ */ forwardRef(({ children, debug = true, enable = true, name = "", maxThrust = 500, torqueRatio = .6, invertThrust = false, invertTorque = false, showPropellerModel = true, propellerModelUpdate = true, propellerModelMaxSpin = 50, propellerModelLerpSpinRate = 10, debuggerScale = 1, debuggerArrowScale = 35, ...props }, ref) => {
1727
+ /**
1728
+ * Rapier preset
1729
+ */
1730
+ const { rapier, world } = useRapier();
1731
+ /**
1732
+ * Retrieve context object from ecctrl vehicle
1733
+ */
1734
+ const vehicleValue = useContext(VehicleContext);
1735
+ const vehicleBody = vehicleValue.body.current;
1736
+ const vehiclePos = useRef(new THREE.Vector3());
1737
+ const vehicleQuat = useRef(new THREE.Quaternion());
1738
+ const vehicleInvertQuat = useRef(new THREE.Quaternion());
1739
+ const vehicleLinVel = useRef(new THREE.Vector3());
1740
+ const vehicleAngVel = useRef(new THREE.Vector3());
1741
+ /**
1742
+ * Control preset
1743
+ */
1744
+ const localPos = useRef(new THREE.Vector3());
1745
+ const localQuat = useRef(new THREE.Quaternion());
1746
+ const worldPos = useRef(new THREE.Vector3());
1747
+ const worldQuat = useRef(new THREE.Quaternion());
1748
+ const thrustDir = useRef(new THREE.Vector3());
1749
+ const thrustForce = useRef(new THREE.Vector3());
1750
+ const leverageTorque = useRef(new THREE.Vector3());
1751
+ const reactionTorque = useRef(new THREE.Vector3());
1752
+ const reactionTorqueDir = useRef(new THREE.Vector3());
1753
+ const torqueInfluence = useRef(new THREE.Vector3());
1754
+ const throttle = useRef(0);
1755
+ const setThrottle = useCallback((value) => throttle.current = clamp(value, 0, 1), []);
1756
+ /**
1757
+ * Refs and handles
1758
+ */
1759
+ const thrustPropellerRef = useRef(null);
1760
+ useImperativeHandle(ref, () => thrustPropellerRef.current, []);
1761
+ /**
1762
+ * Propeller model preset
1763
+ */
1764
+ const modelRef = useRef(null);
1765
+ const modelSpinVel = useRef(0);
1766
+ /**
1767
+ * Register propeller information
1768
+ */
1769
+ const propellerId = useMemo(() => {
1770
+ var _props$id;
1771
+ return String((_props$id = props.id) !== null && _props$id !== void 0 ? _props$id : generateUUID());
1772
+ }, [props.id]);
1773
+ const propellerInfo = useRef({
1774
+ id: propellerId,
1775
+ name,
1776
+ enable,
1777
+ debug,
1778
+ maxThrust,
1779
+ torqueRatio,
1780
+ debuggerScale,
1781
+ invertThrust,
1782
+ invertTorque,
1783
+ thrustPos: new THREE.Vector3(),
1784
+ thrustDir: new THREE.Vector3(),
1785
+ thrustPot: new THREE.Vector3(),
1786
+ torqueDir: new THREE.Vector3(),
1787
+ torquePot: new THREE.Vector3(),
1788
+ worldThrustPos: new THREE.Vector3(),
1789
+ worldThrustDir: new THREE.Vector3(),
1790
+ worldTorqueDir: new THREE.Vector3(),
1791
+ thrustImpulse: new THREE.Vector3(),
1792
+ torqueImpulse: new THREE.Vector3(),
1793
+ finalThrottle: 0,
1794
+ throttle: throttle.current,
1795
+ setThrottle,
1796
+ lx: 0,
1797
+ ly: 0,
1798
+ lz: 0,
1799
+ ax: 0,
1800
+ ay: 0,
1801
+ az: 0
1802
+ });
1803
+ useEffect(() => {
1804
+ vehicleValue === null || vehicleValue === void 0 || vehicleValue.regPropeller(propellerInfo);
1805
+ return () => vehicleValue === null || vehicleValue === void 0 ? void 0 : vehicleValue.unregPropeller(propellerId);
1806
+ }, [vehicleValue]);
1807
+ /**
1808
+ * Debug indicators preset
1809
+ */
1810
+ const xAxisPointRef = useRef(null);
1811
+ const yAxisPointRef = useRef(null);
1812
+ const zAxisPointRef = useRef(null);
1813
+ const currThrustArrowRef = useRef(null);
1814
+ const currTorqueArrowRef = useRef(null);
1815
+ const debugAssets = useMemo(() => {
1816
+ if (!debug) return null;
1817
+ return {
1818
+ thrustRingGeo: new THREE.RingGeometry(debuggerScale * .5, debuggerScale * .55, 12, 1, 0, -Math.PI * 1),
1819
+ thrustRingMat: new THREE.MeshBasicMaterial({
1820
+ color: EC_AZURE,
1821
+ side: THREE.DoubleSide
1822
+ }),
1823
+ thrustPointerGeo: new THREE.ConeGeometry(debuggerScale * .06, debuggerScale * .5, 8, 1, true),
1824
+ thrustIndicatorMat: new THREE.MeshBasicMaterial({
1825
+ color: EC_MED_PURPLE,
1826
+ side: THREE.DoubleSide,
1827
+ transparent: true,
1828
+ opacity: .3
1829
+ }),
1830
+ axisPointGeo: new THREE.OctahedronGeometry(debuggerScale * .05, 3),
1831
+ xAxisPointMat: new THREE.MeshBasicMaterial({
1832
+ color: EC_GREEN,
1833
+ transparent: true,
1834
+ opacity: 1
1835
+ }),
1836
+ yAxisPointMat: new THREE.MeshBasicMaterial({
1837
+ color: EC_BLUE,
1838
+ transparent: true,
1839
+ opacity: 1
1840
+ }),
1841
+ zAxisPointMat: new THREE.MeshBasicMaterial({
1842
+ color: EC_RED,
1843
+ transparent: true,
1844
+ opacity: 1
1845
+ })
1846
+ };
1847
+ }, [debug, debuggerScale]);
1848
+ useEffect(() => {
1849
+ return () => {
1850
+ if (!debugAssets) return;
1851
+ for (const key in debugAssets) {
1852
+ const item = debugAssets[key];
1853
+ if ("dispose" in item && typeof item.dispose === "function") item.dispose();
1854
+ }
1855
+ };
1856
+ }, [debugAssets]);
1857
+ /**
1858
+ *
1859
+ *
1860
+ *
1861
+ *
1862
+ *
1863
+ *
1864
+ *
1865
+ *
1866
+ *
1867
+ *
1868
+ *
1869
+ *
1870
+ *
1871
+ *
1872
+ *
1873
+ *
1874
+ *
1875
+ *
1876
+ *
1877
+ *
1878
+ *
1879
+ *
1880
+ *
1881
+ *
1882
+ *
1883
+ *
1884
+ *
1885
+ *
1886
+ *
1887
+ *
1888
+ *
1889
+ *
1890
+ *
1891
+ *
1892
+ */
1893
+ /**
1894
+ * Update vehicle info function
1895
+ */
1896
+ const updateVehicleInfo = useCallback((body) => {
1897
+ vehiclePos.current.copy(body.translation());
1898
+ vehicleQuat.current.copy(body.rotation());
1899
+ vehicleLinVel.current.copy(body.linvel());
1900
+ vehicleAngVel.current.copy(body.angvel());
1901
+ }, []);
1902
+ /**
1903
+ * Update propeller info function
1904
+ */
1905
+ const updatePropellerInfo = useCallback(() => {
1906
+ if (!thrustPropellerRef.current) return;
1907
+ thrustPropellerRef.current.getWorldPosition(worldPos.current);
1908
+ thrustPropellerRef.current.getWorldQuaternion(worldQuat.current);
1909
+ vehicleInvertQuat.current.copy(vehicleQuat.current).invert();
1910
+ localPos.current.subVectors(worldPos.current, vehiclePos.current).applyQuaternion(vehicleInvertQuat.current);
1911
+ localQuat.current.multiplyQuaternions(vehicleInvertQuat.current, worldQuat.current);
1912
+ thrustDir.current.set(0, invertThrust ? -1 : 1, 0).applyQuaternion(localQuat.current);
1913
+ thrustForce.current.copy(thrustDir.current).multiplyScalar(maxThrust);
1914
+ leverageTorque.current.crossVectors(localPos.current, thrustForce.current);
1915
+ reactionTorqueDir.current.set(0, invertTorque ? -1 : 1, 0).applyQuaternion(localQuat.current);
1916
+ reactionTorque.current.copy(reactionTorqueDir.current).multiplyScalar(maxThrust * torqueRatio);
1917
+ torqueInfluence.current.copy(leverageTorque.current).add(reactionTorque.current);
1918
+ propellerInfo.current.lx = thrustForce.current.x;
1919
+ propellerInfo.current.ly = thrustForce.current.y;
1920
+ propellerInfo.current.lz = thrustForce.current.z;
1921
+ propellerInfo.current.ax = torqueInfluence.current.x;
1922
+ propellerInfo.current.ay = torqueInfluence.current.y;
1923
+ propellerInfo.current.az = torqueInfluence.current.z;
1924
+ propellerInfo.current.thrustPos = localPos.current;
1925
+ propellerInfo.current.thrustDir = thrustDir.current;
1926
+ propellerInfo.current.thrustPot = thrustForce.current;
1927
+ propellerInfo.current.torqueDir = reactionTorqueDir.current;
1928
+ propellerInfo.current.torquePot = torqueInfluence.current;
1929
+ propellerInfo.current.throttle = throttle.current;
1930
+ }, [
1931
+ invertThrust,
1932
+ invertTorque,
1933
+ maxThrust,
1934
+ torqueRatio
1935
+ ]);
1936
+ /**
1937
+ * Update propeller model function
1938
+ */
1939
+ const updatePropellerModel = useCallback((frameRateCorrection) => {
1940
+ if (!modelRef.current) return;
1941
+ const targetVel = throttle.current * propellerModelMaxSpin * (invertTorque ? -1 : 1);
1942
+ modelSpinVel.current = lerp(modelSpinVel.current, targetVel, 1 - Math.exp(-propellerModelLerpSpinRate * world.timestep));
1943
+ modelRef.current.rotateY(modelSpinVel.current * frameRateCorrection);
1944
+ }, [
1945
+ propellerModelMaxSpin,
1946
+ propellerModelLerpSpinRate,
1947
+ invertTorque
1948
+ ]);
1949
+ /**
1950
+ * Update debug indicators
1951
+ */
1952
+ const updateDebugger = useCallback(() => {
1953
+ if (currThrustArrowRef.current) currThrustArrowRef.current.setLength(throttle.current * debuggerArrowScale);
1954
+ if (currTorqueArrowRef.current) currTorqueArrowRef.current.setLength(throttle.current * debuggerArrowScale * torqueRatio);
1955
+ }, [debuggerArrowScale, torqueRatio]);
1956
+ /**
1957
+ *
1958
+ *
1959
+ *
1960
+ *
1961
+ *
1962
+ *
1963
+ *
1964
+ *
1965
+ *
1966
+ *
1967
+ *
1968
+ *
1969
+ *
1970
+ *
1971
+ *
1972
+ *
1973
+ *
1974
+ *
1975
+ *
1976
+ *
1977
+ */
1978
+ useFrame(() => {
1979
+ if (!vehicleBody || !enable) return;
1980
+ const frameRateCorrection = 60 * world.timestep;
1981
+ updateVehicleInfo(vehicleBody);
1982
+ updatePropellerInfo();
1983
+ if (propellerModelUpdate) updatePropellerModel(frameRateCorrection);
1984
+ updateDebugger();
1985
+ });
1986
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("group", {
1987
+ ref: thrustPropellerRef,
1988
+ ...props
1989
+ }, showPropellerModel && /* @__PURE__ */ React.createElement("group", { ref: modelRef }, children), debug && debugAssets && /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("mesh", {
1990
+ "rotation-x": invertThrust ? Math.PI : 0,
1991
+ position: [
1992
+ 0,
1993
+ debuggerScale * .25 * (invertThrust ? -1 : 1),
1994
+ 0
1995
+ ],
1996
+ geometry: debugAssets.thrustPointerGeo,
1997
+ material: debugAssets.thrustIndicatorMat
1998
+ })), /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("mesh", {
1999
+ "rotation-x": Math.PI / 2,
2000
+ position: [
2001
+ debuggerScale * .53 * (invertTorque ? 1 : -1),
2002
+ 0,
2003
+ debuggerScale * .25
2004
+ ],
2005
+ geometry: debugAssets.thrustPointerGeo,
2006
+ material: debugAssets.thrustRingMat
2007
+ }), /* @__PURE__ */ React.createElement("mesh", {
2008
+ "rotation-x": Math.PI / 2,
2009
+ geometry: debugAssets.thrustRingGeo,
2010
+ material: debugAssets.thrustRingMat
2011
+ })), /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("mesh", {
2012
+ ref: xAxisPointRef,
2013
+ position: [
2014
+ debuggerScale,
2015
+ 0,
2016
+ 0
2017
+ ],
2018
+ geometry: debugAssets.axisPointGeo,
2019
+ material: debugAssets.xAxisPointMat
2020
+ }), /* @__PURE__ */ React.createElement("mesh", {
2021
+ ref: yAxisPointRef,
2022
+ position: [
2023
+ 0,
2024
+ debuggerScale,
2025
+ 0
2026
+ ],
2027
+ geometry: debugAssets.axisPointGeo,
2028
+ material: debugAssets.yAxisPointMat
2029
+ }), /* @__PURE__ */ React.createElement("mesh", {
2030
+ ref: zAxisPointRef,
2031
+ position: [
2032
+ 0,
2033
+ 0,
2034
+ debuggerScale
2035
+ ],
2036
+ geometry: debugAssets.axisPointGeo,
2037
+ material: debugAssets.zAxisPointMat
2038
+ })), /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("arrowHelper", {
2039
+ ref: currThrustArrowRef,
2040
+ args: [
2041
+ new THREE.Vector3(0, invertThrust ? -1 : 1, 0),
2042
+ void 0,
2043
+ 0,
2044
+ "#87CEFA"
2045
+ ]
2046
+ }), /* @__PURE__ */ React.createElement("arrowHelper", {
2047
+ ref: currTorqueArrowRef,
2048
+ args: [
2049
+ new THREE.Vector3(0, invertTorque ? -1 : 1, 0),
2050
+ void 0,
2051
+ 0,
2052
+ "#FA8787"
2053
+ ]
2054
+ })))));
2055
+ });
2056
+ var ThrustPropeller_default = React.memo(ThrustPropeller);
2057
+ //#endregion
2058
+ //#region src/vehicle.ts
2059
+ /*!
2060
+ * Ecctrl
2061
+ * https://github.com/pmndrs/ecctrl
2062
+ *
2063
+ * SPDX-FileCopyrightText: 2023-2026 Erdong Chen
2064
+ * SPDX-License-Identifier: MIT
2065
+ */
2066
+ //#endregion
2067
+ export { ShapeCastWheel_default as n, EcctrlVehicle_default as r, ThrustPropeller_default as t };
2068
+
2069
+ //# sourceMappingURL=vehicle-B8WqQHee.js.map