@khr3/core 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 khr3 contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,127 @@
1
- # Temporary Holding Version
1
+ # `@khr3/core` (`khr3`)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `KHR_physics_rigid_bodies` + `KHR_implicit_shapes` runtime loader, binary `.glb` exporter, `@react-three/rapier` multi-body assembly synchronizer, and `@pinkaphant/ecctrl` vehicle rig + monotone Pacejka curve presets for React Three Fiber.
4
+
5
+ ## Stack Map (`@khr3/*` → `Kolmo`)
6
+
7
+ All `@khr3/*` packages are **strictly `koota`-free** reusable building blocks; `Kolmo` owns the ECS, world generation, character body, and universal GLB intake gate:
8
+
9
+ | Package | Role | `koota`? |
10
+ | --- | --- | --- |
11
+ | **`@khr3/core`** *(this package)* | `.glb` KHR physics loader/exporter, `<PhysicsWorld>`, `<KhrAssembly>`, `<KhrVehicle>`, `@khr3/core/curves` | No |
12
+ | `@khr3/assets` | Cloudflare R2 `.glb` vault Worker/client + binary `inspectGlbBuffer` / `normalizeGlbBuffer` | No |
13
+ | `@khr3/c12` | Exact architectural grid ($\mathbb{Z}[1/2, \sqrt{3}]$, `yaw12`), `3 m` socket snapping, `planSettlement` | No |
14
+ | `@khr3/vehicles` | Multi-domain R2 vehicle catalog, multi-body `planCar` (`SEDAN_4DOOR`, `COUPE_2DOOR`), `@khr3/vehicles/paper-shell` | No |
15
+ | `@khr3/launchers` | Moving-part launcher planner (`planLauncher`), rail/hand sockets, ammo catalog, `stepLauncher` | No |
16
+ | `Kolmo` | Game engine & studio (`koota` ECS, `src/world/` roads & terrain, `src/body/`, Universal 2-Step GLB & USD Gate) | **Yes** |
17
+
18
+ ## Install
19
+
20
+ ```sh
21
+ npm install @khr3/core @pinkaphant/ecctrl @dimforge/rapier3d-compat @react-three/fiber @react-three/rapier react react-dom three
22
+ ```
23
+
24
+ ### Peer Dependencies
25
+
26
+ | Package | Version | Required By |
27
+ | --- | --- | --- |
28
+ | `@dimforge/rapier3d-compat` | `^0.19.0` | `@khr3/core`, `@khr3/core/vehicle` |
29
+ | `@pinkaphant/ecctrl` | `^2.0.4-beta.3` | Optional (`@khr3/core/vehicle` only) |
30
+ | `@react-three/fiber` | `^9.0.0` | `@khr3/core`, `@khr3/core/vehicle` |
31
+ | `@react-three/rapier` | `^2.2.0` | `@khr3/core`, `@khr3/core/vehicle` |
32
+ | `react` | `^19.0.0` | `@khr3/core`, `@khr3/core/vehicle` |
33
+ | `react-dom` | `^19.0.0` | Optional (browser DOM apps) |
34
+ | `three` | `>=0.159.0` | `@khr3/core`, `@khr3/core/vehicle` |
35
+
36
+ ## Subpath Exports
37
+
38
+ `@khr3/core` ships strictly three ESM subpaths (`"sideEffects": false`, NodeNext `.d.ts` declarations):
39
+
40
+ | Subpath | Exports |
41
+ | --- | --- |
42
+ | `@khr3/core` | `PhysicsWorld`, `createKhrGltfPlugin`, `useKhrGlb`, `loadKhrGlb`, `cloneKhrBundle`, `disposeKhrBundle`, `claimBundleMount`, `releaseBundleMount`, `exportKhrGlb`, `patchGlbJsonChunk`, `KhrCollider`, `KhrAssembly`, `JointRegistryContext`, `assertUnitScale`, `assertIdentityWorldScale`, `assertSceneIdentityWorldScale`, `KhrValidationError`, KHR & rotor tag types |
43
+ | `@khr3/core/vehicle` | `KhrVehicle`, `solveWheelLoads`, `BENCH_GRAVITY`, `WHEEL_ASSEMBLY_DENSITY_KG_M3`, `KhrVehicleProps`, `KhrWheelConfig`, `SolvedWheel` |
44
+ | `@khr3/core/curves` | `compilePacejkaCurve`, `tireGripForSurface`, `engineHorsepowerForPeakTorque`, `TIRE_ARCHETYPES`, `TIRE_SLIP_CURVES`, `ENGINE_TORQUE_CURVES`, `STEER_SPEED_CURVES`, `TireArchetypePreset`, `CurveData`, `CurvePoint` |
45
+
46
+ ## Quick Start
47
+
48
+ ```tsx
49
+ import { useRef } from "react";
50
+ import { Canvas } from "@react-three/fiber";
51
+ import type { EcctrlVehicleHandle } from "@pinkaphant/ecctrl/vehicle";
52
+ import { KhrAssembly, PhysicsWorld, loadKhrGlb, type KhrAssemblyHandle } from "@khr3/core";
53
+ import { KhrVehicle } from "@khr3/core/vehicle";
54
+ import { ENGINE_TORQUE_CURVES, TIRE_ARCHETYPES, tireGripForSurface } from "@khr3/core/curves";
55
+
56
+ const roadBundle = await loadKhrGlb(await fetch("/assets/city/R_Straight_6x6.glb").then((r) => r.arrayBuffer()));
57
+ const doorBundle = await loadKhrGlb(await fetch("/assets/city/door_hinged_single_900x2100.glb").then((r) => r.arrayBuffer()));
58
+ const carBundle = await loadKhrGlb(await fetch("/assets/cars/kolmogorov_hatchback.glb").then((r) => r.arrayBuffer()));
59
+
60
+ export function Scene() {
61
+ const doorRef = useRef<KhrAssemblyHandle>(null);
62
+ const vehicleRef = useRef<EcctrlVehicleHandle>(null);
63
+ const tire = TIRE_ARCHETYPES.streetDrift90s;
64
+
65
+ return (
66
+ <Canvas>
67
+ <PhysicsWorld>
68
+ <KhrAssembly bundle={roadBundle} fixedRoot />
69
+ <KhrAssembly ref={doorRef} bundle={doorBundle} position={[3.6, 0.1, 0]} fixedRoot />
70
+ <KhrVehicle
71
+ ref={vehicleRef}
72
+ bundle={carBundle}
73
+ position={[0, 0.15, 0]}
74
+ carConfig={{
75
+ engineTorqueCurveData: ENGINE_TORQUE_CURVES.naScreamer,
76
+ transmissionMode: "auto",
77
+ gearRatios: [3.2, 2.1, 1.45, 1.0],
78
+ shiftUpRPM: 5800,
79
+ shiftDownRPM: 2600, // < 5800 * (1.0 / 1.45) = 4000 (hysteresis invariant)
80
+ }}
81
+ wheelConfig={{
82
+ tireGripFactor: tireGripForSurface(tire.muPeakLng, 0.8),
83
+ lngSlipRatioCurveData: tire.lng,
84
+ latSlipRatioCurveData: tire.lat,
85
+ latFrictionEllipseScale: tire.latFrictionEllipseScale,
86
+ }}
87
+ frontWheelConfig={{ driveTorqueWeight: 0.35 }}
88
+ rearWheelConfig={{ driveTorqueWeight: 0.65 }}
89
+ />
90
+ </PhysicsWorld>
91
+ </Canvas>
92
+ );
93
+ }
94
+ ```
95
+
96
+ ## Loading Assets
97
+
98
+ ```tsx
99
+ import { Suspense } from "react";
100
+ import { KhrAssembly, useKhrGlb, disposeKhrBundle } from "@khr3/core";
101
+
102
+ function Door() {
103
+ const bundle = useKhrGlb("/assets/city/door_hinged_single_900x2100.glb"); // Suspense + cache, clones per call site
104
+ return <KhrAssembly bundle={bundle} />;
105
+ }
106
+ ```
107
+
108
+ - `useKhrGlb(url)` suspends, caches by URL, and returns a per-instance clone; `createKhrGltfPlugin()` registers the same decoder on any `GLTFLoader`; `loadKhrGlb(bytes)` is the headless/buffer path.
109
+ - Call `disposeKhrBundle(template)` once when an asset is retired.
110
+ - `<PhysicsWorld>` steps Rapier directly in `useFrame` with clamped `maxDelta` and `timeScale`; `@pinkaphant/ecctrl` is an optional peer required only by `@khr3/core/vehicle` (`@khr3/core/curves` is zero-dependency TypeScript math).
111
+ - Peer range for `three` is `>=0.159.0`.
112
+
113
+ ## Core Architecture & Invariants
114
+
115
+ 1. **Bundle Ownership & Zero-Reparse Cloning (`cloneKhrBundle`)**: `loadKhrGlb(source)` constructs live `THREE.Object3D` nodes (`bundle.scene`, `w.object`, `p.object`). Mount each `KhrAssetBundle` in at most **one** `<KhrAssembly>` or `<KhrVehicle>` at a time; parse once with `loadKhrGlb(bytes)` and call `cloneKhrBundle(template)` per tiled road, prop, or vehicle instance (cloning only the lightweight `Object3D` hierarchy while sharing GPU `BufferGeometry`/`Material` buffers and Rapier `Float32Array` collider vertices). Sequential `mount -> unmount -> remount` of a single bundle is safe, and swapping the `bundle` prop cleanly remounts Rapier bodies and joints via `key={bundle.scene.uuid}`.
116
+ 2. **CoM-Aligned Vehicle RigidBody (`body.translation() === body.worldCom()`)**: `<KhrVehicle>` offsets the underlying `<EcctrlVehicle>` Rapier `RigidBody` spawn to `position + R(spawnQuat) * chassisCom` and shifts local chassis colliders, `bundle.scene`, `children`, `<ShapeCastWheel>`, and `<ThrustPropeller>` mounts by `-chassisCom`. World-space visual and collider poses at `position` remain unchanged while `EcctrlVehicle` wheel lever arms (`rayOrigin - body.translation()`) act directly about the true center of mass, preserving authored CG height and parallel-axis inertia without artificial rollover or pitch coupling.
117
+ 3. **glTF & Rapier Safety**:
118
+ - `exportKhrGlb` emits `KHR_physics_rigid_bodies` and `KHR_implicit_shapes` strictly in `extensionsUsed` (never `extensionsRequired`).
119
+ - `KhrCollider` sets `density: 0` (exact mass/CoM/inertia are applied once via `setAdditionalMassProperties`) and omits `collisionGroups` whenever `undefined` so Rapier WASM never coerces `undefined` to `0x00000000`.
120
+ 4. **5 `@pinkaphant/ecctrl` v2 Curve & Grip Invariants**:
121
+ - **Surface Grip Averaging**: `ShapeCastWheel` computes $\mu_{\text{eff}} = \frac{1}{2}(\mu_{\text{ground}} + \text{tireGripFactor})$. Use `tireGripForSurface(muPeak, muGround)` (`2 * muPeak - muGround`).
122
+ - **Peak Torque Scaling**: `EcctrlVehicle` computes $T_{\max} = \frac{\text{engineHorsepower} \times 7022}{\text{engineMaxRPM}}$. Use `engineHorsepowerForPeakTorque(peakTorqueNm, engineMaxRPM)`.
123
+ - **Slip Domains**: `lngSlipRatioCurveData` maps $x = \frac{|\omega R - v_x|}{\max(|v_x|, 10^{-4})} \in [0, 1]$; `latSlipRatioCurveData` maps slip angle linearly as $x = \frac{\operatorname{atan2}(|v_y|, |v_x|)}{\pi/2} \in [0, 1]$.
124
+ - **Monotone Hermite Tangents**: `CurvePoint` `r_in`/`r_out` are **radian angles** (`slope = Math.tan(r)`). `compilePacejkaCurve` enforces Fritsch–Carlson clamping so `bakeCurveLUT` stays strictly in $[0, 1]$ with zero Hermite overshoot.
125
+ - **Shift Hysteresis & Gear-Relative Steer Curve**: Auto transmission requires `shiftDownRPM < shiftUpRPM * min(g[i+1] / g[i])` to prevent shift oscillation; `steerAngleCurveData` evaluates at `v_fwd / (maxWheelAngVel * R)` relative to the **active gear's** redline wheel speed.
126
+
127
+ See [docs/api-reference.md](./docs/api-reference.md) for the complete API, `.glb` KHR + `extras` schema, custom gravity, transmission, and curve reference.
@@ -0,0 +1,17 @@
1
+ import React from "react";
2
+ import { type RapierRigidBody, type RigidBodyProps } from "@react-three/rapier";
3
+ import type { RootPlan } from "./assemblyPlan.js";
4
+ import { type JointRuntime } from "./physicsEcs.js";
5
+ export type AssemblyRigidBodyProps = Omit<RigidBodyProps, "type" | "position" | "rotation" | "quaternion" | "colliders" | "children" | "ref">;
6
+ export interface AssemblyRootBodyProps {
7
+ plan: RootPlan;
8
+ assemblyId: number;
9
+ position: [number, number, number];
10
+ quaternion: [number, number, number, number];
11
+ fixedRoot: boolean;
12
+ rigidBodyProps?: AssemblyRigidBodyProps;
13
+ onBody: (rootName: string, rb: React.RefObject<RapierRigidBody | null> | null) => void;
14
+ onJoints: (rootName: string, joints: Map<string, JointRuntime> | null) => void;
15
+ children?: React.ReactNode;
16
+ }
17
+ export declare function AssemblyRootBody({ plan, assemblyId, position, quaternion, fixedRoot, rigidBodyProps, onBody, onJoints, children, }: AssemblyRootBodyProps): React.JSX.Element;
@@ -0,0 +1,428 @@
1
+ import { createContext as e, useCallback as t, useEffect as n, useLayoutEffect as r, useRef as i } from "react";
2
+ import { BallCollider as a, CapsuleCollider as o, ConvexHullCollider as s, CuboidCollider as c, CylinderCollider as l, TrimeshCollider as u } from "@react-three/rapier";
3
+ import * as d from "three";
4
+ import { jsx as f } from "react/jsx-runtime";
5
+ // src/khrTypes.ts
6
+ var p = class extends Error {
7
+ constructor(e) {
8
+ super(e), this.name = "KhrValidationError";
9
+ }
10
+ }, m = e(null), h = e(null), g = 1e-4;
11
+ function _(e) {
12
+ return typeof e == "number" && Number.isFinite(e) && Math.abs(e - 1) <= 1e-9;
13
+ }
14
+ function v(e, t) {
15
+ if (e === void 0) return;
16
+ let n = !1;
17
+ if (typeof e == "number") n = _(e);
18
+ else if (Array.isArray(e)) n = e.length === 3 && e.every(_);
19
+ else if (typeof e == "object" && e && "x" in e && "y" in e && "z" in e) {
20
+ let t = e;
21
+ n = _(t.x) && _(t.y) && _(t.z);
22
+ }
23
+ if (!n) throw new p(`${t}: scale must be 1 (got ${typeof e == "number" && !Number.isFinite(e) ? String(e) : JSON.stringify(e)}); bake scale into the .glb at import`);
24
+ }
25
+ function y(e, t) {
26
+ if (!Array.isArray(e) || e.length !== 3 || !e.every((e) => typeof e == "number" && Number.isFinite(e))) throw new p(`Invalid ${t}: expected finite 3-tuple`);
27
+ return [
28
+ e[0],
29
+ e[1],
30
+ e[2]
31
+ ];
32
+ }
33
+ function b(e, t) {
34
+ if (!Array.isArray(e) || e.length !== 4 || !e.every((e) => typeof e == "number" && Number.isFinite(e))) throw new p(`Invalid ${t}: expected finite 4-tuple`);
35
+ let n = Math.hypot(e[0], e[1], e[2], e[3]);
36
+ if (!(n > 1e-6)) throw new p(`Invalid ${t}: zero-norm quaternion`);
37
+ return [
38
+ e[0] / n,
39
+ e[1] / n,
40
+ e[2] / n,
41
+ e[3] / n
42
+ ];
43
+ }
44
+ function x(e, t) {
45
+ let n = e.getWorldScale(new d.Vector3());
46
+ if (!Number.isFinite(n.x) || !Number.isFinite(n.y) || !Number.isFinite(n.z) || Math.abs(n.x - 1) > g || Math.abs(n.y - 1) > g || Math.abs(n.z - 1) > g) throw new p(`Non-identity world scale [${n.x.toFixed(4)}, ${n.y.toFixed(4)}, ${n.z.toFixed(4)}] on "${t}"; bake scale=[1,1,1]`);
47
+ let r = e.scale;
48
+ if (!Number.isFinite(r.x) || !Number.isFinite(r.y) || !Number.isFinite(r.z) || Math.abs(r.x - 1) > g || Math.abs(r.y - 1) > g || Math.abs(r.z - 1) > g) throw new p(`Non-identity local scale [${r.x.toFixed(4)}, ${r.y.toFixed(4)}, ${r.z.toFixed(4)}] on "${t}"; bake scale=[1,1,1]`);
49
+ }
50
+ function S(e) {
51
+ e.traverse((t) => {
52
+ x(t, t.name || (t === e ? "gltf.scene" : "unnamed_node"));
53
+ });
54
+ }
55
+ function C(e, t) {
56
+ let n = e.getWorldPosition(new d.Vector3()), r = e.getWorldQuaternion(new d.Quaternion()).invert(), i = t.getWorldPosition(new d.Vector3()).sub(n).applyQuaternion(r), a = r.multiply(t.getWorldQuaternion(new d.Quaternion()));
57
+ return {
58
+ localPosition: [
59
+ i.x,
60
+ i.y,
61
+ i.z
62
+ ],
63
+ localQuaternion: [
64
+ a.x,
65
+ a.y,
66
+ a.z,
67
+ a.w
68
+ ]
69
+ };
70
+ }
71
+ function w(e, t, n) {
72
+ x(e, t);
73
+ let r = e.matrixWorld.clone().invert(), i = new d.Matrix4(), a = new d.Vector3(), o = [], s = [];
74
+ if (e.traverse((e) => {
75
+ let n = e;
76
+ if (!n.isMesh || !n.geometry) return;
77
+ x(n, n.name || t);
78
+ let c = n.geometry.getAttribute("position");
79
+ if (!c || c.count === 0) return;
80
+ i.multiplyMatrices(r, n.matrixWorld);
81
+ let l = o.length / 3;
82
+ for (let e = 0; e < c.count; e++) {
83
+ if (a.fromBufferAttribute(c, e).applyMatrix4(i), !Number.isFinite(a.x) || !Number.isFinite(a.y) || !Number.isFinite(a.z)) throw new p(`Non-finite vertex in collider mesh "${t}"`);
84
+ o.push(a.x, a.y, a.z);
85
+ }
86
+ let u = n.geometry.getIndex();
87
+ if (u) for (let e = 0; e < u.count; e++) s.push(l + u.getX(e));
88
+ else for (let e = 0; e < c.count; e++) s.push(l + e);
89
+ }), o.length < 9) throw new p(`Collider node "${t}" has fewer than 3 vertices`);
90
+ if (n) return {
91
+ type: "convexHull",
92
+ vertices: new Float32Array(o),
93
+ meshNodeName: t
94
+ };
95
+ if (s.length < 3) throw new p(`Trimesh node "${t}" has fewer than 3 indices`);
96
+ return {
97
+ type: "trimesh",
98
+ vertices: new Float32Array(o),
99
+ indices: new Uint32Array(s),
100
+ meshNodeName: t
101
+ };
102
+ }
103
+ function T(e) {
104
+ if (e.type === "box") {
105
+ let [t, n, r] = e.size;
106
+ return {
107
+ volume: t * n * r,
108
+ centroid: new d.Vector3(),
109
+ unitInertia: [
110
+ (n * n + r * r) / 12,
111
+ (t * t + r * r) / 12,
112
+ (t * t + n * n) / 12
113
+ ]
114
+ };
115
+ }
116
+ if (e.type === "sphere") {
117
+ let t = e.radius, n = .4 * t * t;
118
+ return {
119
+ volume: 4 / 3 * Math.PI * t * t * t,
120
+ centroid: new d.Vector3(),
121
+ unitInertia: [
122
+ n,
123
+ n,
124
+ n
125
+ ]
126
+ };
127
+ }
128
+ if (e.type === "convexHull" || e.type === "trimesh") {
129
+ let t = new d.Box3(), n = new d.Vector3(), r = e.vertices;
130
+ for (let e = 0; e < r.length; e += 3) t.expandByPoint(n.set(r[e], r[e + 1], r[e + 2]));
131
+ let i = t.getSize(new d.Vector3());
132
+ return {
133
+ volume: i.x * i.y * i.z,
134
+ centroid: t.getCenter(new d.Vector3()),
135
+ unitInertia: [
136
+ (i.y * i.y + i.z * i.z) / 12,
137
+ (i.x * i.x + i.z * i.z) / 12,
138
+ (i.x * i.x + i.y * i.y) / 12
139
+ ]
140
+ };
141
+ }
142
+ let t = e.radiusTop, n = e.height;
143
+ if (e.type === "capsule") {
144
+ let e = Math.PI * t * t * n, r = e + 4 / 3 * Math.PI * t * t * t, i = e / r, a = 1 - i, o = .5 * i * t * t + .4 * a * t * t, s = i * (n * n / 12 + .25 * t * t) + a * (.4 * t * t + .25 * n * n + .375 * n * t);
145
+ return {
146
+ volume: r,
147
+ centroid: new d.Vector3(),
148
+ unitInertia: [
149
+ s,
150
+ o,
151
+ s
152
+ ]
153
+ };
154
+ }
155
+ let r = (3 * t * t + n * n) / 12;
156
+ return {
157
+ volume: Math.PI * t * t * n,
158
+ centroid: new d.Vector3(),
159
+ unitInertia: [
160
+ r,
161
+ .5 * t * t,
162
+ r
163
+ ]
164
+ };
165
+ }
166
+ function E(e, t, n, r, i) {
167
+ if (e.length === 0) throw new p(`Dynamic node "${i}" is missing motion.inertiaDiagonal and has no colliders`);
168
+ let a = e.map((e) => T(e.shape)), o = 0;
169
+ for (let e of a) o += e.volume;
170
+ let s = new d.Quaternion().fromArray(r).invert(), c = new d.Vector3().fromArray(n), l = new d.Quaternion(), u = new d.Quaternion(), f = new d.Vector3(), m = new d.Matrix4(), h = m.elements, g = 0, _ = 0, v = 0;
171
+ for (let n = 0; n < e.length; n++) {
172
+ let r = e[n], i = a[n], p = o > 0 ? t * (i.volume / o) : t / e.length;
173
+ l.fromArray(r.localQuaternion), f.copy(i.centroid).applyQuaternion(l).add(new d.Vector3().fromArray(r.localPosition)).sub(c).applyQuaternion(s), u.copy(s).multiply(l), m.makeRotationFromQuaternion(u);
174
+ let [y, b, x] = i.unitInertia, S = h[0] * h[0] * y + h[4] * h[4] * b + h[8] * h[8] * x, C = h[1] * h[1] * y + h[5] * h[5] * b + h[9] * h[9] * x, w = h[2] * h[2] * y + h[6] * h[6] * b + h[10] * h[10] * x;
175
+ g += p * (S + f.y * f.y + f.z * f.z), _ += p * (C + f.x * f.x + f.z * f.z), v += p * (w + f.x * f.x + f.y * f.y);
176
+ }
177
+ if (!Number.isFinite(g) || !Number.isFinite(_) || !Number.isFinite(v) || g <= 0 || _ <= 0 || v <= 0) throw new p(`Dynamic node "${i}" has degenerate collider geometry; cannot compute positive motion.inertiaDiagonal`);
178
+ return [
179
+ g,
180
+ _,
181
+ v
182
+ ];
183
+ }
184
+ function D(e) {
185
+ let t = 0, n = 0, r = 0, i = 0, a = new d.Quaternion(), o = new d.Vector3();
186
+ for (let s of e) s.isKinematic || (t += s.mass, o.fromArray(s.centerOfMass).applyQuaternion(a.fromArray(s.localQuaternion)), n += (s.localPosition[0] + o.x) * s.mass, r += (s.localPosition[1] + o.y) * s.mass, i += (s.localPosition[2] + o.z) * s.mass);
187
+ return {
188
+ totalDynamicMass: t,
189
+ centerOfMass: t > 0 ? [
190
+ n / t,
191
+ r / t,
192
+ i / t
193
+ ] : [
194
+ 0,
195
+ 0,
196
+ 0
197
+ ]
198
+ };
199
+ }
200
+ // src/khrClone.ts
201
+ var O = /* @__PURE__ */ new WeakSet(), k = /* @__PURE__ */ new WeakSet(), A = /* @__PURE__ */ new WeakSet();
202
+ function j(e, t) {
203
+ if (A.has(e.scene)) throw new p(`${t}: KhrAssetBundle "${e.scene.name || e.scene.uuid}" has already been disposed`);
204
+ if (O.has(e.scene)) throw new p(`${t}: KhrAssetBundle "${e.scene.name || e.scene.uuid}" is already mounted; call cloneKhrBundle(template) per concurrent instance`);
205
+ O.add(e.scene);
206
+ }
207
+ function M(e) {
208
+ O.delete(e.scene);
209
+ }
210
+ function N(e, t, n) {
211
+ if (t === e) return n;
212
+ let r = [], i = t;
213
+ for (; i && i !== e;) {
214
+ let e = i.parent;
215
+ if (!e) throw new p(`cloneKhrBundle: body node "${t.name}" is detached from bundle.scene`);
216
+ let n = e.children.indexOf(i);
217
+ if (n < 0) throw new p(`cloneKhrBundle: child index missing for "${t.name}"`);
218
+ r.push(n), i = e;
219
+ }
220
+ let a = n;
221
+ for (let e = r.length - 1; e >= 0; e--) a = a.children[r[e]];
222
+ return a;
223
+ }
224
+ function P(e) {
225
+ if (e) return {
226
+ ...e,
227
+ points: e.points.map((e) => ({ ...e }))
228
+ };
229
+ }
230
+ function F(e) {
231
+ if (e) return {
232
+ ...e,
233
+ ...e.gearRatios ? { gearRatios: [...e.gearRatios] } : {},
234
+ ...e.engineTorqueCurveData ? { engineTorqueCurveData: P(e.engineTorqueCurveData) } : {},
235
+ ...e.steerAngleCurveData ? { steerAngleCurveData: P(e.steerAngleCurveData) } : {}
236
+ };
237
+ }
238
+ function I(e) {
239
+ if (A.has(e.scene)) throw new p(`cloneKhrBundle: cannot clone disposed KhrAssetBundle "${e.scene.name || e.scene.uuid}"`);
240
+ let t = e.scene.clone(!0);
241
+ return k.add(t), {
242
+ scene: t,
243
+ bodies: e.bodies.map((n) => {
244
+ let r = n.joint ? n.joint.drives.map((e) => ({ ...e })) : [];
245
+ return {
246
+ ...n,
247
+ centerOfMass: [...n.centerOfMass],
248
+ inertiaDiagonal: [...n.inertiaDiagonal],
249
+ inertiaOrientation: [...n.inertiaOrientation],
250
+ ...n.linearVelocity ? { linearVelocity: [...n.linearVelocity] } : {},
251
+ ...n.angularVelocity ? { angularVelocity: [...n.angularVelocity] } : {},
252
+ localPosition: [...n.localPosition],
253
+ localQuaternion: [...n.localQuaternion],
254
+ colliders: n.colliders.map((e) => ({
255
+ ...e,
256
+ shape: e.shape.type === "box" ? {
257
+ ...e.shape,
258
+ size: [...e.shape.size]
259
+ } : { ...e.shape },
260
+ localPosition: [...e.localPosition],
261
+ localQuaternion: [...e.localQuaternion]
262
+ })),
263
+ joint: n.joint ? {
264
+ ...n.joint,
265
+ axis: [...n.joint.axis],
266
+ limits: n.joint.limits ? [...n.joint.limits] : null,
267
+ drive: r[0] ?? (n.joint.drive ? { ...n.joint.drive } : null),
268
+ drives: r,
269
+ anchor1: [...n.joint.anchor1],
270
+ anchor2: [...n.joint.anchor2]
271
+ } : null,
272
+ object: N(e.scene, n.object, t)
273
+ };
274
+ }),
275
+ wheels: e.wheels.map((n) => ({
276
+ ...n,
277
+ object: N(e.scene, n.object, t),
278
+ position: [...n.position],
279
+ ...n.quaternion ? { quaternion: [...n.quaternion] } : {},
280
+ ...n.lngSlipRatioCurveData ? { lngSlipRatioCurveData: P(n.lngSlipRatioCurveData) } : {},
281
+ ...n.latSlipRatioCurveData ? { latSlipRatioCurveData: P(n.latSlipRatioCurveData) } : {}
282
+ })),
283
+ propellers: e.propellers.map((n) => ({
284
+ ...n,
285
+ object: N(e.scene, n.object, t),
286
+ position: [...n.position],
287
+ ...n.quaternion ? { quaternion: [...n.quaternion] } : {}
288
+ })),
289
+ sockets: Object.fromEntries(Object.entries(e.sockets).map(([e, t]) => [e, [...t]])),
290
+ totalDynamicMass: e.totalDynamicMass,
291
+ centerOfMass: [...e.centerOfMass],
292
+ ...e.tune ? { tune: F(e.tune) } : {},
293
+ ...e.droneTune ? { droneTune: { ...e.droneTune } } : {}
294
+ };
295
+ }
296
+ function L(e) {
297
+ if (O.delete(e.scene), k.has(e.scene) || A.has(e.scene)) {
298
+ A.add(e.scene);
299
+ return;
300
+ }
301
+ A.add(e.scene);
302
+ let t = /* @__PURE__ */ new Set(), n = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Set(), i = (e) => {
303
+ e.traverse((e) => {
304
+ let i = e;
305
+ i.geometry && !t.has(i.geometry) && (t.add(i.geometry), i.geometry.dispose());
306
+ let a = Array.isArray(i.material) ? i.material : i.material ? [i.material] : [];
307
+ for (let e of a) if (!n.has(e)) {
308
+ n.add(e);
309
+ for (let t of Object.values(e)) if (t && typeof t == "object" && "isTexture" in t && t.isTexture) {
310
+ let e = t;
311
+ r.has(e) || (r.add(e), e.dispose());
312
+ }
313
+ e.dispose();
314
+ }
315
+ });
316
+ };
317
+ i(e.scene);
318
+ for (let t of e.wheels) i(t.object);
319
+ for (let t of e.propellers) i(t.object);
320
+ }
321
+ // src/KhrCollider.tsx
322
+ function R({ c: e, position: r, quaternion: d, massProperties: p, ref: m }) {
323
+ let h = i(null), g = t((e) => {
324
+ h.current = e, typeof m == "function" ? m(e) : m && (m.current = e);
325
+ }, [m]);
326
+ n(() => {
327
+ let e = h.current;
328
+ e && e.parent()?.recomputeMassPropertiesFromColliders();
329
+ }, [e, p]);
330
+ let _ = {
331
+ ref: g,
332
+ position: r ?? e.localPosition,
333
+ quaternion: d ?? e.localQuaternion,
334
+ ...p ? { massProperties: p } : { density: 0 },
335
+ ...e.friction === void 0 ? {} : { friction: e.friction },
336
+ ...e.restitution === void 0 ? {} : { restitution: e.restitution },
337
+ ...e.collisionGroups === void 0 ? {} : { collisionGroups: e.collisionGroups }
338
+ }, { shape: v } = e;
339
+ if (v.type === "box") {
340
+ let [e, t, n] = v.size;
341
+ return /* @__PURE__ */ f(c, {
342
+ args: [
343
+ e * .5,
344
+ t * .5,
345
+ n * .5
346
+ ],
347
+ ..._
348
+ });
349
+ }
350
+ return v.type === "sphere" ? /* @__PURE__ */ f(a, {
351
+ args: [v.radius],
352
+ ..._
353
+ }) : v.type === "cylinder" ? /* @__PURE__ */ f(l, {
354
+ args: [v.height * .5, v.radiusTop],
355
+ ..._
356
+ }) : v.type === "capsule" ? /* @__PURE__ */ f(o, {
357
+ args: [v.height * .5, v.radiusTop],
358
+ ..._
359
+ }) : v.type === "convexHull" ? /* @__PURE__ */ f(s, {
360
+ args: [v.vertices],
361
+ ..._
362
+ }) : /* @__PURE__ */ f(u, {
363
+ args: [v.vertices, v.indices],
364
+ ..._
365
+ });
366
+ }
367
+ // src/BundleSceneHost.tsx
368
+ function z(e) {
369
+ let t = /* @__PURE__ */ new Map(), n = /* @__PURE__ */ new Map();
370
+ for (let r of e) {
371
+ let e = r.parent, i = /* @__PURE__ */ new Map(), a = -1;
372
+ if (e) {
373
+ let n = t.get(e);
374
+ n || (n = /* @__PURE__ */ new Map(), e.children.forEach((e, t) => n.set(e, t)), t.set(e, n)), i = n, a = i.get(r) ?? e.children.indexOf(r);
375
+ }
376
+ n.set(r, {
377
+ origParent: e,
378
+ origIndex: a,
379
+ origOrder: i,
380
+ origPos: r.position.clone(),
381
+ origQuat: r.quaternion.clone(),
382
+ origScale: r.scale.clone()
383
+ });
384
+ }
385
+ return n;
386
+ }
387
+ function B(e, t) {
388
+ e.position.copy(t.origPos), e.quaternion.copy(t.origQuat), e.scale.copy(t.origScale);
389
+ let { origParent: n, origIndex: r, origOrder: i } = t;
390
+ if (n) {
391
+ n.add(e);
392
+ let t = n.children.indexOf(e);
393
+ t >= 0 && n.children.splice(t, 1);
394
+ let a = n.children.length;
395
+ if (i.size > 0) {
396
+ for (let e = 0; e < n.children.length; e++) if ((i.get(n.children[e]) ?? Infinity) > r) {
397
+ a = e;
398
+ break;
399
+ }
400
+ } else r >= 0 && (a = Math.min(r, n.children.length));
401
+ n.children.splice(a, 0, e);
402
+ }
403
+ }
404
+ function V({ bundle: e, owner: t }) {
405
+ let n = i(null);
406
+ return r(() => {
407
+ let r = n.current;
408
+ if (r) return j(e, t), r.add(e.scene), () => {
409
+ e.scene.parent === r && r.remove(e.scene), M(e);
410
+ };
411
+ }, [e, t]), /* @__PURE__ */ f("group", { ref: n });
412
+ }
413
+ function H({ object: e, position: t, quaternion: n, origin: a }) {
414
+ let o = i(null);
415
+ return r(() => {
416
+ let t = o.current;
417
+ if (!t) return;
418
+ let n = a ?? z([e]).get(e);
419
+ return n.origParent && n.origParent.remove(e), e.position.set(0, 0, 0), e.quaternion.set(0, 0, 0, 1), e.scale.set(1, 1, 1), t.add(e), () => {
420
+ e.parent === t && t.remove(e), B(e, n);
421
+ };
422
+ }, [e, a]), /* @__PURE__ */ f("group", {
423
+ ref: o,
424
+ position: t,
425
+ quaternion: n
426
+ });
427
+ }
428
+ export { y as _, R as a, h as b, L as c, S as d, v as f, w as g, C as h, B as i, M as l, E as m, H as n, j as o, D as p, z as r, I as s, V as t, x as u, b as v, p as x, m as y };
@@ -0,0 +1,23 @@
1
+ import React from "react";
2
+ import * as THREE from "three";
3
+ import type { KhrAssetBundle } from "./khrTypes.js";
4
+ export interface SubtreeOrigin {
5
+ origParent: THREE.Object3D | null;
6
+ origIndex: number;
7
+ origOrder: Map<THREE.Object3D, number>;
8
+ origPos: THREE.Vector3;
9
+ origQuat: THREE.Quaternion;
10
+ origScale: THREE.Vector3;
11
+ }
12
+ export declare function captureSubtreeOrigins(objects: readonly THREE.Object3D[]): Map<THREE.Object3D, SubtreeOrigin>;
13
+ export declare function restoreSubtreeOrigin(object: THREE.Object3D, snap: SubtreeOrigin): void;
14
+ export declare function BundleSceneHost({ bundle, owner }: {
15
+ bundle: KhrAssetBundle;
16
+ owner: string;
17
+ }): React.JSX.Element;
18
+ export declare function MountSubtreeSlot({ object, position, quaternion, origin, }: {
19
+ object: THREE.Object3D;
20
+ position: [number, number, number];
21
+ quaternion: [number, number, number, number];
22
+ origin?: SubtreeOrigin;
23
+ }): React.JSX.Element;
@@ -0,0 +1,29 @@
1
+ import React from "react";
2
+ import type { ThreeElements } from "@react-three/fiber";
3
+ import type { RapierRigidBody } from "@react-three/rapier";
4
+ import { type AssemblyRigidBodyProps } from "./AssemblyRootBody.js";
5
+ import { type KhrAssetBundle } from "./khrTypes.js";
6
+ export interface KhrAssemblyHandle {
7
+ /** RigidBody carrying `nodeName` (the root body for articulated compound parts), or null if no KHR body has that name. */
8
+ getBody: (nodeName: string) => RapierRigidBody | null;
9
+ /** Sets the authored drive's position target on one articulated node. */
10
+ setJointTarget: (nodeName: string, target: number) => void;
11
+ /** Sets the position target on every articulated node whose `extras.role` matches. */
12
+ setRoleTarget: (role: string, target: number) => void;
13
+ }
14
+ type GroupProps = Omit<ThreeElements["group"], "ref" | "position" | "rotation" | "quaternion" | "scale" | "children">;
15
+ export interface KhrAssemblyProps extends GroupProps {
16
+ ref?: React.Ref<KhrAssemblyHandle>;
17
+ bundle: KhrAssetBundle;
18
+ position?: [number, number, number];
19
+ rotation?: [number, number, number];
20
+ quaternion?: [number, number, number, number];
21
+ /** Must be 1: assets are baked to identity scale by the importer gate. */
22
+ scale?: ThreeElements["group"]["scale"];
23
+ /** Kinematic roots become `fixed` bodies instead of `kinematicPosition`. */
24
+ fixedRoot?: boolean;
25
+ rigidBodyProps?: AssemblyRigidBodyProps;
26
+ children?: React.ReactNode;
27
+ }
28
+ export declare function KhrAssembly({ ref, bundle, position, rotation, quaternion, scale, fixedRoot, rigidBodyProps, children, ...groupProps }: KhrAssemblyProps): React.JSX.Element;
29
+ export {};
@@ -0,0 +1,14 @@
1
+ import React from "react";
2
+ import { type RapierCollider } from "@react-three/rapier";
3
+ import type { ColliderMass } from "./assemblyPlan.js";
4
+ import type { KhrColliderSpec } from "./khrTypes.js";
5
+ export interface KhrColliderProps {
6
+ c: KhrColliderSpec;
7
+ /** Pose override in the parent RigidBody frame; defaults to the authored KHR collider offset. */
8
+ position?: [number, number, number];
9
+ quaternion?: [number, number, number, number];
10
+ /** Authored body mass carried by this collider. Without it the collider is massless (density 0). */
11
+ massProperties?: ColliderMass;
12
+ ref?: React.Ref<RapierCollider>;
13
+ }
14
+ export declare function KhrCollider({ c, position, quaternion, massProperties, ref }: KhrColliderProps): React.JSX.Element;