@pinkaphant/kolmo 0.4.0 → 0.4.2

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 (61) hide show
  1. package/README.md +2 -2
  2. package/bin/kolmo.mjs +0 -3
  3. package/dist/engine/kolmoVehicleConfig.d.ts +1 -1
  4. package/dist/engine/kolmoVehicleConfig.js +2 -2
  5. package/dist/engine/kolmoVehicleConfig.js.map +1 -1
  6. package/dist/engine/kolmoVehicleDriver.js +13 -4
  7. package/dist/engine/kolmoVehicleDriver.js.map +1 -1
  8. package/dist/importer/GlbImportGate.js +3 -2
  9. package/dist/importer/GlbImportGate.js.map +1 -1
  10. package/dist/importer/chopShopActions.d.ts +2 -2
  11. package/dist/importer/chopShopActions.js +7 -3
  12. package/dist/importer/chopShopActions.js.map +1 -1
  13. package/dist/importer/chopShopHandlers.js +2 -2
  14. package/dist/importer/chopShopHandlers.js.map +1 -1
  15. package/dist/importer/chopShopIoActions.d.ts +3 -0
  16. package/dist/importer/chopShopIoActions.js +25 -1
  17. package/dist/importer/chopShopIoActions.js.map +1 -1
  18. package/dist/importer/fusedWheelDetect.js +3 -2
  19. package/dist/importer/fusedWheelDetect.js.map +1 -1
  20. package/dist/importer/khrCarPlanHelpers.d.ts +12 -1
  21. package/dist/importer/khrCarPlanHelpers.js +104 -15
  22. package/dist/importer/khrCarPlanHelpers.js.map +1 -1
  23. package/dist/importer/khrCarPlanner.d.ts +1 -0
  24. package/dist/importer/khrCarPlanner.js +47 -10
  25. package/dist/importer/khrCarPlanner.js.map +1 -1
  26. package/dist/importer/khrCompiler.js +26 -3
  27. package/dist/importer/khrCompiler.js.map +1 -1
  28. package/dist/importer/khrCraftPropCompiler.d.ts +6 -1
  29. package/dist/importer/khrCraftPropCompiler.js +64 -51
  30. package/dist/importer/khrCraftPropCompiler.js.map +1 -1
  31. package/dist/importer/khrNodeNameGuard.d.ts +20 -0
  32. package/dist/importer/khrNodeNameGuard.js +139 -0
  33. package/dist/importer/khrNodeNameGuard.js.map +1 -0
  34. package/dist/importer/launcherBake.js +31 -8
  35. package/dist/importer/launcherBake.js.map +1 -1
  36. package/dist/importer/sceneSiNormalize.js +8 -1
  37. package/dist/importer/sceneSiNormalize.js.map +1 -1
  38. package/dist/importer/universalGateBake.js +21 -8
  39. package/dist/importer/universalGateBake.js.map +1 -1
  40. package/dist/importer/useChopShopController.js +7 -3
  41. package/dist/importer/useChopShopController.js.map +1 -1
  42. package/dist/importer/useChopShopState.js +9 -4
  43. package/dist/importer/useChopShopState.js.map +1 -1
  44. package/dist/importer/vehiclePartSplit.d.ts +1 -1
  45. package/dist/importer/vehiclePartSplit.js +20 -15
  46. package/dist/importer/vehiclePartSplit.js.map +1 -1
  47. package/dist/importer/wheelAxlePairing.d.ts +3 -0
  48. package/dist/importer/wheelAxlePairing.js +34 -15
  49. package/dist/importer/wheelAxlePairing.js.map +1 -1
  50. package/dist/index.js +2 -2
  51. package/dist/schema/kolmoSchema.d.ts +2 -2
  52. package/dist/schema/kolmoSchema.js +2 -2
  53. package/dist/schema/kolmoSchema.js.map +1 -1
  54. package/dist/schema/kolmoStamp.d.ts +6 -1
  55. package/dist/schema/kolmoStamp.js +51 -3
  56. package/dist/schema/kolmoStamp.js.map +1 -1
  57. package/dist/vite/index.d.ts +1 -1
  58. package/dist/vite/index.js +1 -11
  59. package/dist/vite/index.js.map +1 -1
  60. package/docs/api-reference.md +8 -5
  61. package/package.json +6 -12
@@ -1 +1 @@
1
- {"version":3,"file":"khrCarPlanner.js","names":[],"sources":["../../src/importer/khrCarPlanner.ts"],"sourcesContent":["import * as THREE from \"three\";\nimport type { KhrExportNodeSpec } from \"@khr3/core\";\nimport {\n ENGINE_TORQUE_CURVES,\n STEER_SPEED_CURVES,\n TIRE_ARCHETYPES,\n tireGripForSurface,\n} from \"@khr3/core/curves\";\nimport { COUPE_2DOOR, buildCarParts, principalAboutX, sumMass } from \"@khr3/vehicles\";\nimport { sliceCarWheelCylinders } from \"./cylinderBooleanSlice.js\";\nimport { detectFusedCarWheels } from \"./fusedWheelDetect.js\";\nimport {\n buildPanelSpecs,\n resolveCarWheels,\n tryExtractPreCoredCar,\n type ResolvedPanelPlan,\n type ResolvedWheelPlan,\n} from \"./khrCarPlanHelpers.js\";\nimport { boxInertia, r4, type KolmoCompileOptions } from \"./khrCraftPropCompiler.js\";\nimport { extractMeshIslands, separateVehicleMeshes, type SeparatedPanelMesh } from \"./meshIslands.js\";\nimport { createFleet12GonWheelGroup } from \"./surfaceCutter.js\";\nimport { suggestCarAxles } from \"./wheelAxlePairing.js\";\n\nexport function buildCarExportPlan(\n normalizedScene: THREE.Group,\n exportRoot: THREE.Group,\n opts: KolmoCompileOptions,\n box: THREE.Box3,\n size: readonly [number, number, number],\n center: THREE.Vector3,\n totalMass: number,\n): { specs: KhrExportNodeSpec[]; sceneExtras: Record<string, unknown> } {\n const [sx, sy, sz] = size;\n const driveType = opts.driveType ?? \"AWD\";\n let wheels: ResolvedWheelPlan[];\n let wheelZs: number[];\n let panels: ResolvedPanelPlan[] = [];\n let splitPanels: SeparatedPanelMesh[] = [];\n const chassis = new THREE.Group();\n chassis.name = \"Chassis\";\n\n const preCored = tryExtractPreCoredCar(normalizedScene, chassis, exportRoot, opts, driveType);\n if (preCored) {\n wheels = preCored.wheels;\n wheelZs = preCored.wheelZs;\n } else {\n const islands = opts.islands ?? extractMeshIslands(normalizedScene);\n const axles = opts.axles ?? suggestCarAxles(islands);\n const hasAxleWheels = axles.some((a) => a.left.length > 0 || a.right.length > 0);\n const explicitCutters = opts.wheelCutters && opts.wheelCutters.length > 0 ? opts.wheelCutters : null;\n const useCoring = opts.wheelSource !== \"fleet12\" && (!!explicitCutters || !hasAxleWheels);\n const detectedCutters = useCoring ? (explicitCutters ?? detectFusedCarWheels(normalizedScene, { mirrorX: opts.mirrorX ?? true })) : [];\n\n if (detectedCutters.length === 4) {\n const sliced = sliceCarWheelCylinders(normalizedScene, detectedCutters, {\n sealArchLiner: opts.sealArchLiner ?? true,\n mirrorX: opts.mirrorX ?? true,\n });\n chassis.add(sliced.chassis);\n if (sliced.liner) chassis.add(sliced.liner);\n exportRoot.add(chassis);\n const fwd = driveType === \"AWD\" || driveType === \"FWD\";\n const rwd = driveType === \"AWD\" || driveType === \"RWD\";\n wheels = sliced.cutters.map((c, i) => {\n const grp = sliced.wheels[i];\n if (grp && grp.children.length > 0) exportRoot.add(grp);\n else {\n const wg = createFleet12GonWheelGroup(c.radius, c.width, `Wheel_${c.id.toUpperCase()}`);\n wg.position.set(c.center[0], c.center[1], c.center[2]);\n exportRoot.add(wg);\n }\n const isFront = c.axle === \"front\";\n return { nodeName: `Wheel_${c.id.toUpperCase()}`, islandIds: [], fallbackPos: c.center, radius: c.radius, width: c.width, steered: isFront, driven: isFront ? fwd : rwd, brake: true };\n });\n wheelZs = sliced.cutters.map((c) => c.center[2]);\n } else {\n wheels = resolveCarWheels(islands, axles, driveType, size);\n panels = buildPanelSpecs(islands, opts.partPicks, new Set(wheels.flatMap((w) => w.islandIds)));\n const split = separateVehicleMeshes(normalizedScene, islands, wheels.filter((w) => w.islandIds.length > 0), panels.map((p) => ({ nodeName: p.nodeName, islandIds: p.islandIds, anchor: p.hinge.anchor })));\n chassis.add(split.chassisGroup);\n exportRoot.add(chassis);\n splitPanels = split.panels;\n for (const w of wheels) {\n const sep = split.wheels.find((sw) => sw.nodeName === w.nodeName);\n const pos = sep?.center ?? w.fallbackPos ?? [0, w.radius, 0];\n if (opts.wheelSource === \"fleet12\" || !sep) {\n const wg = createFleet12GonWheelGroup(w.radius, w.width, w.nodeName);\n wg.position.set(pos[0], pos[1], pos[2]);\n exportRoot.add(wg);\n } else exportRoot.add(sep.group);\n }\n wheelZs = wheels.map((w) => split.wheels.find((sw) => sw.nodeName === w.nodeName)?.center[2] ?? w.fallbackPos?.[2] ?? 0);\n }\n }\n\n const maxR = Math.max(...wheels.map((w) => w.radius));\n const chassisMass = Math.max(80, totalMass - panels.reduce((sum, p) => sum + p.massKg, 0));\n const zMinW = wheelZs.length > 0 ? Math.min(...wheelZs) : -sz * 0.32;\n const zMaxW = wheelZs.length > 0 ? Math.max(...wheelZs) : sz * 0.32;\n const effLength = Math.max(2.2, sz);\n const effWidth = Math.max(0.9, sx);\n const groundClearance = Math.max(0.08, Math.min(maxR * 0.65, sy * 0.25));\n const effHeight = Math.max(groundClearance + 0.5, sy);\n const wheelbase = Math.max(1.15, Math.min(effLength - 0.45, zMaxW - zMinW));\n const rawFrontOverhang = effLength * 0.5 - (zMaxW - center.z);\n const frontOverhang = Math.max(0.18, Math.min(effLength - wheelbase - 0.18, rawFrontOverhang));\n\n const baseFixed = buildCarParts({\n id: \"imported_car\",\n doors: 2,\n dims: { length: effLength, width: effWidth, height: effHeight, wheelbase, frontOverhang, groundClearance },\n masses: COUPE_2DOOR.masses,\n }).filter((p) => !p.hinge);\n const baseFixedSum = baseFixed.reduce((s, p) => s + p.massKg, 0);\n const massScale = chassisMass / Math.max(1, baseFixedSum);\n const scaledFixed = baseFixed.map((p) => ({ ...p, massKg: p.massKg * massScale }));\n const chassisProps = sumMass(scaledFixed);\n const principal = principalAboutX(chassisProps);\n\n const specs: KhrExportNodeSpec[] = [\n {\n nodeName: \"Chassis\",\n motion: {\n isKinematic: false,\n mass: r4(chassisMass),\n centerOfMass: [\n r4(center.x + chassisProps.centerOfMass[0]),\n r4(chassisProps.centerOfMass[1]),\n r4(center.z + chassisProps.centerOfMass[2]),\n ],\n inertiaDiagonal: [r4(principal.inertiaDiagonal[0]), r4(principal.inertiaDiagonal[1]), r4(principal.inertiaDiagonal[2])],\n inertiaOrientation: [\n r4(principal.inertiaOrientation[0]),\n r4(principal.inertiaOrientation[1]),\n r4(principal.inertiaOrientation[2]),\n r4(principal.inertiaOrientation[3]),\n ],\n },\n extras: { role: \"chassis\" },\n },\n ];\n\n for (const part of scaledFixed) {\n if (part.kind === \"seat\" || part.kind === \"gearbox\") continue;\n const nodeName = part.name === \"Body_Tub\" ? \"Chassis_Hull\" : `Chassis_${part.name}`;\n const partObj = new THREE.Object3D();\n partObj.name = nodeName;\n partObj.position.set(r4(center.x + part.center[0]), r4(part.center[1]), r4(center.z + part.center[2]));\n chassis.add(partObj);\n specs.push({\n nodeName,\n collider: {\n shape: { type: \"box\", size: [r4(part.size[0]), r4(part.size[1]), r4(part.size[2])] },\n friction: 0.38,\n restitution: 0.05,\n },\n extras: { role: part.kind },\n });\n }\n\n const tire = TIRE_ARCHETYPES.streetDrift90s;\n const tireGripFactor = tireGripForSurface(tire.muPeakLng, 0.82);\n for (const p of panels) {\n const sp = splitPanels.find((s) => s.nodeName === p.nodeName);\n if (!sp) continue;\n chassis.add(sp.group);\n const relCom: [number, number, number] = [r4(sp.center[0] - sp.anchor[0]), r4(sp.center[1] - sp.anchor[1]), r4(sp.center[2] - sp.anchor[2])];\n const colNode = new THREE.Object3D();\n colNode.name = `${p.nodeName}_Panel`;\n colNode.position.set(relCom[0], relCom[1], relCom[2]);\n sp.group.add(colNode);\n specs.push(\n { nodeName: colNode.name, collider: { shape: { type: \"box\", size: [r4(sp.size[0]), r4(sp.size[1]), r4(sp.size[2])] }, friction: 0.45 } },\n { nodeName: p.nodeName, motion: { isKinematic: false, mass: p.massKg, centerOfMass: relCom, inertiaDiagonal: boxInertia(p.massKg, sp.size[0], sp.size[1], sp.size[2]) }, joint: { connectedNodeName: \"Chassis\", kind: \"revolute\", axis: p.hinge.axis, limits: p.hinge.limits, drive: { mode: \"acceleration\", stiffness: 60, damping: 12, positionTarget: 0 } }, extras: { role: p.role } },\n );\n }\n const springK = r4(Math.max(8000, chassisMass * 24));\n const dampingC = r4(Math.max(900, chassisMass * 2.2));\n const maxForce = r4(Math.max(1800, chassisMass * 4.5));\n for (const w of wheels) {\n const wTravel = r4(Math.max(0.08, Math.min(0.3, w.radius * 0.68)));\n specs.push({\n nodeName: w.nodeName,\n wheel: {\n radius: r4(w.radius), width: r4(w.width), steering: w.steered, propulsion: w.driven,\n maxSteeringAngle: w.steered ? 0.55 : 0, maxForce, suspensionTravel: wTravel,\n suspensionStiffness: springK, suspensionDampingCompression: dampingC, suspensionDampingRebound: dampingC,\n },\n extras: {\n ecctrlWheel: {\n radius: r4(w.radius), width: r4(w.width), travel: wTravel, sag: r4(wTravel * 0.4),\n steer: w.steered, drive: w.driven, brake: w.brake, tireGripFactor,\n latFrictionEllipseScale: tire.latFrictionEllipseScale, relaxLngRate: tire.relaxLngRate,\n relaxLatRate: tire.relaxLatRate, lngSlipRatioCurveData: tire.lng, latSlipRatioCurveData: tire.lat,\n },\n },\n });\n }\n return {\n specs,\n sceneExtras: {\n tune: {\n engineHorsepower: Math.max(25, opts.powerOrThrust || 280), engineMaxRPM: 7000,\n gearRatios: [3.1, 2.05, 1.42, 1, 0.82], finalDriveRatio: 3.58, transmissionMode: \"auto\",\n maxSteerAngle: 0.55, engineTorqueCurveData: ENGINE_TORQUE_CURVES.naScreamer, steerAngleCurveData: STEER_SPEED_CURVES.driftCountersteer,\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;AAuBA,SAAgB,mBACZ,iBACA,YACA,MACA,KACA,MACA,QACA,WACoE;CACpE,MAAM,CAAC,IAAI,IAAI,MAAM;CACrB,MAAM,YAAY,KAAK,aAAa;CACpC,IAAI;CACJ,IAAI;CACJ,IAAI,SAA8B,CAAC;CACnC,IAAI,cAAoC,CAAC;CACzC,MAAM,UAAU,IAAI,MAAM,MAAM;CAChC,QAAQ,OAAO;CAEf,MAAM,WAAW,sBAAsB,iBAAiB,SAAS,YAAY,MAAM,SAAS;CAC5F,IAAI,UAAU;EACV,SAAS,SAAS;EAClB,UAAU,SAAS;CACvB,OAAO;EACH,MAAM,UAAU,KAAK,WAAW,mBAAmB,eAAe;EAClE,MAAM,QAAQ,KAAK,SAAS,gBAAgB,OAAO;EACnD,MAAM,gBAAgB,MAAM,MAAM,MAAM,EAAE,KAAK,SAAS,KAAK,EAAE,MAAM,SAAS,CAAC;EAC/E,MAAM,kBAAkB,KAAK,gBAAgB,KAAK,a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,aAAa;IACT,QAAQ,GAAG,EAAE,MAAM;IAAG,OAAO,GAAG,EAAE,KAAK;IAAG,QAAQ;IAAS,KAAK,GAAG,UAAU,EAAG;IAChF,OAAO,EAAE;IAAS,OAAO,EAAE;IAAQ,OAAO,EAAE;IAAO;IACnD,yBAAyB,KAAK;IAAyB,cAAc,KAAK;IAC1E,cAAc,KAAK;IAAc,uBAAuB,KAAK;IAAK,uBAAuB,KAAK;GAClG,EACJ;EACJ,CAAC;CACL;CACA,OAAO;EACH;EACA,aAAa,EACT,MAAM;GACF,kBAAkB,KAAK,IAAI,IAAI,KAAK,iBAAiB,GAAG;GAAG,cAAc;GACzE,YAAY;IAAC;IAAK;IAAM;IAAM;IAAG;GAAI;GAAG,iBAAiB;GAAM,kBAAkB;GACjF,eAAe;GAAM,uBAAuB,qBAAqB;GAAY,qBAAqB,mBAAmB;EACzH,EACJ;CACJ;AACJ"}
1
+ {"version":3,"file":"khrCarPlanner.js","names":[],"sources":["../../src/importer/khrCarPlanner.ts"],"sourcesContent":["import * as THREE from \"three\";\nimport type { KhrExportNodeSpec } from \"@khr3/core\";\nimport { ENGINE_TORQUE_CURVES, STEER_SPEED_CURVES, TIRE_ARCHETYPES, tireGripForSurface } from \"@khr3/core/curves\";\nimport { COUPE_2DOOR, SEDAN_4DOOR, buildCarParts, principalAboutX, sumMass } from \"@khr3/vehicles\";\nimport { sliceCarWheelCylinders } from \"./cylinderBooleanSlice.js\";\nimport { detectFusedCarWheels } from \"./fusedWheelDetect.js\";\nimport {\n attachPreservedArchLiner,\n buildPanelSpecs,\n collectArchLinerNodes,\n collectCarChassisExcludeSet,\n resolveCarWheels,\n tryExtractPreCoredCar,\n type ResolvedPanelPlan,\n type ResolvedWheelPlan,\n type SubtreeDisambiguateTarget,\n} from \"./khrCarPlanHelpers.js\";\nimport { boxInertia, r4, type KolmoCompileOptions } from \"./khrCraftPropCompiler.js\";\nimport { disambiguateExportSubtrees } from \"./khrNodeNameGuard.js\";\nimport { extractMeshIslands, separateVehicleMeshes, type SeparatedPanelMesh } from \"./meshIslands.js\";\nimport { isMeshObject } from \"./sceneSiNormalize.js\";\nimport { createFleet12GonWheelGroup } from \"./surfaceCutter.js\";\nimport { suggestCarAxles } from \"./wheelAxlePairing.js\";\n\nexport function buildCarExportPlan(\n normalizedScene: THREE.Group,\n exportRoot: THREE.Group,\n opts: KolmoCompileOptions,\n box: THREE.Box3,\n size: readonly [number, number, number],\n center: THREE.Vector3,\n totalMass: number,\n): { specs: KhrExportNodeSpec[]; sceneExtras: Record<string, unknown>; coveredSourceNodes: Set<THREE.Object3D> } {\n const [sx, sy, sz] = size;\n const driveType = opts.driveType ?? \"AWD\";\n let wheels: ResolvedWheelPlan[];\n let wheelZs: number[];\n let panels: ResolvedPanelPlan[] = [];\n let splitPanels: SeparatedPanelMesh[] = [];\n let userSubtrees: SubtreeDisambiguateTarget[] = [];\n const coveredSourceNodes = new Set<THREE.Object3D>();\n const chassis = new THREE.Group();\n chassis.name = \"Chassis\";\n\n const preCored = tryExtractPreCoredCar(normalizedScene, chassis, exportRoot, opts, driveType);\n if (preCored) {\n wheels = preCored.wheels;\n wheelZs = preCored.wheelZs;\n panels = preCored.panels;\n splitPanels = preCored.splitPanels;\n userSubtrees = preCored.userSubtrees;\n for (const n of preCored.coveredSourceNodes) coveredSourceNodes.add(n);\n } else {\n const hasOptsIslands = !!opts.islands && opts.islands.length > 0;\n const islands = hasOptsIslands ? opts.islands! : extractMeshIslands(normalizedScene);\n const linerNodes = collectArchLinerNodes(normalizedScene);\n const linerMeshes = new Set<THREE.Object3D>();\n for (const ln of linerNodes) ln.traverse((o) => { if (isMeshObject(o)) linerMeshes.add(o); });\n const axles = opts.axles ?? suggestCarAxles(linerMeshes.size > 0 ? islands.filter((i) => !linerMeshes.has(i.mesh)) : islands);\n const hasAxleWheels = axles.some((a) => a.left.length > 0 || a.right.length > 0);\n const explicitCutters = opts.wheelCutters && opts.wheelCutters.length > 0 ? opts.wheelCutters : null;\n const useCoring = opts.wheelSource !== \"fleet12\" && (!!explicitCutters || !hasAxleWheels);\n const detectedCutters = useCoring ? (explicitCutters ?? detectFusedCarWheels(normalizedScene, { mirrorX: opts.mirrorX ?? true })) : [];\n\n if (detectedCutters.length >= 2) {\n panels = buildPanelSpecs(islands, opts.partPicks, new Set(axles.flatMap((a) => [...a.left, ...a.right])));\n let sliceSource: THREE.Object3D = normalizedScene;\n if (panels.length > 0) {\n const split = separateVehicleMeshes(\n normalizedScene,\n islands,\n [],\n panels.map((p) => ({ nodeName: p.nodeName, islandIds: p.islandIds, anchor: p.hinge.anchor })),\n );\n splitPanels = split.panels;\n sliceSource = split.chassisGroup;\n }\n const sliced = sliceCarWheelCylinders(sliceSource, detectedCutters, {\n sealArchLiner: opts.sealArchLiner ?? true,\n mirrorX: opts.mirrorX ?? true,\n });\n chassis.add(sliced.chassis);\n if (sliced.liner) chassis.add(sliced.liner);\n exportRoot.add(chassis);\n const fwd = driveType === \"AWD\" || driveType === \"FWD\";\n const rwd = driveType === \"AWD\" || driveType === \"RWD\";\n wheels = sliced.cutters.map((c, i) => {\n const grp = sliced.wheels[i];\n if (grp && grp.children.length > 0) exportRoot.add(grp);\n else {\n const wg = createFleet12GonWheelGroup(c.radius, c.width, `Wheel_${c.id.toUpperCase()}`);\n wg.position.set(c.center[0], c.center[1], c.center[2]);\n exportRoot.add(wg);\n }\n const isFront = c.axle === \"front\";\n return { nodeName: `Wheel_${c.id.toUpperCase()}`, islandIds: [], fallbackPos: c.center, radius: c.radius, width: c.width, steered: isFront, driven: isFront ? fwd : rwd, brake: true };\n });\n wheelZs = sliced.cutters.map((c) => c.center[2]);\n } else {\n wheels = resolveCarWheels(islands, axles, driveType, size);\n panels = buildPanelSpecs(islands, opts.partPicks, new Set(wheels.flatMap((w) => w.islandIds)));\n const split = separateVehicleMeshes(\n normalizedScene,\n islands,\n wheels.filter((w) => w.islandIds.length > 0),\n panels.map((p) => ({ nodeName: p.nodeName, islandIds: p.islandIds, anchor: p.hinge.anchor })),\n normalizedScene,\n collectCarChassisExcludeSet(normalizedScene, linerNodes),\n );\n chassis.add(split.chassisGroup);\n const preservedLiner = attachPreservedArchLiner(linerNodes, chassis, opts.sealArchLiner);\n if (preservedLiner) {\n userSubtrees.push({ obj: preservedLiner, includeRoot: false });\n for (const ln of linerNodes) coveredSourceNodes.add(ln);\n }\n exportRoot.add(chassis);\n splitPanels = split.panels;\n for (const w of wheels) {\n const sep = split.wheels.find((sw) => sw.nodeName === w.nodeName);\n const pos = sep?.center ?? w.fallbackPos ?? [0, w.radius, 0];\n if (opts.wheelSource === \"fleet12\" || !sep) {\n const wg = createFleet12GonWheelGroup(w.radius, w.width, w.nodeName);\n wg.position.set(pos[0], pos[1], pos[2]);\n exportRoot.add(wg);\n } else exportRoot.add(sep.group);\n }\n wheelZs = wheels.map((w) => split.wheels.find((sw) => sw.nodeName === w.nodeName)?.center[2] ?? w.fallbackPos?.[2] ?? 0);\n }\n if (!hasOptsIslands) for (const isl of islands) isl.geometry.dispose();\n }\n\n const maxR = Math.max(...wheels.map((w) => w.radius));\n const chassisMass = Math.max(80, totalMass - panels.reduce((sum, p) => sum + p.massKg, 0));\n const zMinW = wheelZs.length > 0 ? Math.min(...wheelZs) : -sz * 0.32;\n const zMaxW = wheelZs.length > 0 ? Math.max(...wheelZs) : sz * 0.32;\n const effLength = Math.max(2.2, sz);\n const effWidth = Math.max(0.9, sx);\n const groundClearance = Math.max(0.08, Math.min(maxR * 0.65, sy * 0.25));\n const effHeight = Math.max(groundClearance + 0.5, sy);\n const wheelbase = Math.max(1.15, Math.min(effLength - 0.45, zMaxW - zMinW));\n const rawFrontOverhang = effLength * 0.5 - (zMaxW - center.z);\n const frontOverhang = Math.max(0.18, Math.min(effLength - wheelbase - 0.18, rawFrontOverhang));\n\n const doorCount: 2 | 4 = panels.filter((p) => p.role.includes(\"door\")).length >= 3 ? 4 : 2;\n const baseFixed = buildCarParts({\n id: \"imported_car\",\n doors: doorCount,\n dims: { length: effLength, width: effWidth, height: effHeight, wheelbase, frontOverhang, groundClearance },\n masses: doorCount === 4 ? SEDAN_4DOOR.masses : COUPE_2DOOR.masses,\n }).filter((p) => !p.hinge);\n const baseFixedSum = baseFixed.reduce((s, p) => s + p.massKg, 0);\n const massScale = chassisMass / Math.max(1, baseFixedSum);\n const scaledFixed = baseFixed.map((p) => ({ ...p, massKg: p.massKg * massScale }));\n const chassisProps = sumMass(scaledFixed);\n const principal = principalAboutX(chassisProps);\n\n const specs: KhrExportNodeSpec[] = [\n {\n nodeName: \"Chassis\",\n motion: {\n isKinematic: false,\n mass: r4(chassisMass),\n centerOfMass: [\n r4(center.x + chassisProps.centerOfMass[0]),\n r4(chassisProps.centerOfMass[1]),\n r4(center.z + chassisProps.centerOfMass[2]),\n ],\n inertiaDiagonal: [r4(principal.inertiaDiagonal[0]), r4(principal.inertiaDiagonal[1]), r4(principal.inertiaDiagonal[2])],\n inertiaOrientation: [\n r4(principal.inertiaOrientation[0]),\n r4(principal.inertiaOrientation[1]),\n r4(principal.inertiaOrientation[2]),\n r4(principal.inertiaOrientation[3]),\n ],\n },\n extras: { role: \"chassis\" },\n },\n ];\n\n for (const part of scaledFixed) {\n if (part.kind === \"seat\" || part.kind === \"gearbox\") continue;\n const nodeName = part.name === \"Body_Tub\" ? \"Chassis_Hull\" : `Chassis_${part.name}`;\n const partObj = new THREE.Object3D();\n partObj.name = nodeName;\n partObj.position.set(r4(center.x + part.center[0]), r4(part.center[1]), r4(center.z + part.center[2]));\n chassis.add(partObj);\n specs.push({\n nodeName,\n collider: {\n shape: { type: \"box\", size: [r4(part.size[0]), r4(part.size[1]), r4(part.size[2])] },\n friction: 0.38,\n restitution: 0.05,\n },\n extras: { role: part.kind },\n });\n }\n\n const tire = TIRE_ARCHETYPES.streetDrift90s;\n const tireGripFactor = tireGripForSurface(tire.muPeakLng, 0.82);\n for (const p of panels) {\n const sp = splitPanels.find((s) => s.nodeName === p.nodeName);\n if (!sp) continue;\n chassis.add(sp.group);\n const relCom: [number, number, number] = [r4(sp.center[0] - sp.anchor[0]), r4(sp.center[1] - sp.anchor[1]), r4(sp.center[2] - sp.anchor[2])];\n const colNode = new THREE.Object3D();\n colNode.name = `${p.nodeName}_Panel`;\n colNode.position.set(relCom[0], relCom[1], relCom[2]);\n sp.group.add(colNode);\n specs.push(\n { nodeName: colNode.name, collider: { shape: { type: \"box\", size: [r4(sp.size[0]), r4(sp.size[1]), r4(sp.size[2])] }, friction: 0.45 } },\n { nodeName: p.nodeName, motion: { isKinematic: false, mass: p.massKg, centerOfMass: relCom, inertiaDiagonal: boxInertia(p.massKg, sp.size[0], sp.size[1], sp.size[2]) }, joint: { connectedNodeName: \"Chassis\", kind: \"revolute\", axis: p.hinge.axis, limits: p.hinge.limits, drive: { mode: \"acceleration\", stiffness: 60, damping: 12, positionTarget: 0 } }, extras: { role: p.role } },\n );\n }\n const springK = r4(Math.max(8000, chassisMass * 24));\n const dampingC = r4(Math.max(900, chassisMass * 2.2));\n const maxForce = r4(Math.max(1800, chassisMass * 4.5));\n for (const w of wheels) {\n const wTravel = r4(Math.max(0.08, Math.min(0.3, w.radius * 0.68)));\n specs.push({\n nodeName: w.nodeName,\n wheel: {\n radius: r4(w.radius), width: r4(w.width), steering: w.steered, propulsion: w.driven,\n maxSteeringAngle: w.steered ? 0.55 : 0, maxForce, suspensionTravel: wTravel,\n suspensionStiffness: springK, suspensionDampingCompression: dampingC, suspensionDampingRebound: dampingC,\n },\n extras: {\n ecctrlWheel: {\n radius: r4(w.radius), width: r4(w.width), travel: wTravel, sag: r4(wTravel * 0.4),\n steer: w.steered, drive: w.driven, brake: w.brake, tireGripFactor,\n latFrictionEllipseScale: tire.latFrictionEllipseScale, relaxLngRate: tire.relaxLngRate,\n relaxLatRate: tire.relaxLatRate, lngSlipRatioCurveData: tire.lng, latSlipRatioCurveData: tire.lat,\n },\n },\n });\n }\n disambiguateExportSubtrees(exportRoot, specs, userSubtrees);\n return {\n specs,\n coveredSourceNodes,\n sceneExtras: {\n tune: {\n engineHorsepower: Math.max(25, opts.powerOrThrust || 280), engineMaxRPM: 7000,\n gearRatios: [3.1, 2.05, 1.42, 1, 0.82], finalDriveRatio: 3.58, transmissionMode: \"auto\",\n maxSteerAngle: 0.55, engineTorqueCurveData: ENGINE_TORQUE_CURVES.naScreamer, steerAngleCurveData: STEER_SPEED_CURVES.driftCountersteer,\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAwBA,SAAgB,mBACZ,iBACA,YACA,MACA,KACA,MACA,QACA,WAC6G;CAC7G,MAAM,CAAC,IAAI,IAAI,MAAM;CACrB,MAAM,YAAY,KAAK,aAAa;CACpC,IAAI;CACJ,IAAI;CACJ,IAAI,SAA8B,CAAC;CACnC,IAAI,cAAoC,CAAC;CACzC,IAAI,eAA4C,CAAC;CACjD,MAAM,qCAAqB,IAAI,IAAoB;CACnD,MAAM,UAAU,IAAI,MAAM,MAAM;CAChC,QAAQ,OAAO;CAEf,MAAM,WAAW,sBAAsB,iBAAiB,SAAS,YAAY,MAAM,SAAS;CAC5F,IAAI,UAAU;EACV,SAAS,SAAS;EAClB,UAAU,SAAS;EACnB,SAAS,SAAS;EAClB,cAAc,SAAS;EACvB,eAAe,SAAS;EACxB,KAAK,MAAM,KAAK,SAAS,oBAAoB,mBAAmB,IAAI,CAAC;CACzE,OAAO;EACH,MAAM,iBAAiB,CAAC,CAAC,KAAK,WAAW,KAAK,QAAQ,SAAS;EAC/D,MAAM,UAAU,iBAAiB,KAAK,UAAW,mBAAmB,eAAe;EACnF,MAAM,aAAa,sBAAsB,eAAe;EACxD,MAAM,8BAAc,IAAI,IAAoB;EAC5C,KAAK,MAAM,MAAM,YAAY,GAAG,UAAU,MAAM;GAAE,IAAI,aAAa,CAAC,GAAG,YAAY,IAAI,CAAC;EAAG,CAAC;EAC5F,MAAM,QAAQ,KAAK,SAAS,gBAAgB,YAAY,OAAO,IAAI,QAAQ,QAAQ,MAAM,CAAC,YAAY,IAAI,EAAE,IAAI,CAAC,IAAI,OAA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AAY;CAC1D,OAAO;EACH;EACA;EACA,aAAa,EACT,MAAM;GACF,kBAAkB,KAAK,IAAI,IAAI,KAAK,iBAAiB,GAAG;GAAG,cAAc;GACzE,YAAY;IAAC;IAAK;IAAM;IAAM;IAAG;GAAI;GAAG,iBAAiB;GAAM,kBAAkB;GACjF,eAAe;GAAM,uBAAuB,qBAAqB;GAAY,qBAAqB,mBAAmB;EACzH,EACJ;CACJ;AACJ"}
@@ -1,6 +1,7 @@
1
- import { stampKolmoNodesIntoGlb } from "../schema/kolmoStamp.js";
1
+ import { disambiguateExplicitPatches, stampKolmoNodesIntoGlb } from "../schema/kolmoStamp.js";
2
2
  import { buildCarExportPlan } from "./khrCarPlanner.js";
3
3
  import { buildCraftExportPlan, buildPropExportPlan, collectPreservedRigPatches, restoreStrippedTextures, stripUnloadedTextures } from "./khrCraftPropCompiler.js";
4
+ import { assignMissingEmitterNames, collectSceneNodeNames, collectSpecNodeNames, ensureRootNameUnique } from "./khrNodeNameGuard.js";
4
5
  import { buildPatchPreviewEmitters, computeChopPartHinge, normalToMinusZQuaternion } from "./chopHingeHelpers.js";
5
6
  import { isMeshObject } from "./sceneSiNormalize.js";
6
7
  import * as THREE from "three";
@@ -39,15 +40,22 @@ async function compileKhrAssetGlb(normalizedScene, opts) {
39
40
  exportRoot.name = opts.name || normalizedScene.name || `Kolmo_${opts.archetype}`;
40
41
  let specs;
41
42
  let sceneExtras;
43
+ let coveredSourceNodes = null;
42
44
  if (opts.archetype === "car") {
43
45
  const plan = buildCarExportPlan(normalizedScene, exportRoot, opts, box, size, center, totalMass);
44
46
  specs = plan.specs;
45
47
  sceneExtras = plan.sceneExtras;
48
+ coveredSourceNodes = plan.coveredSourceNodes;
46
49
  } else if (opts.archetype === "craft") {
47
50
  const plan = buildCraftExportPlan(normalizedScene, exportRoot, opts, size, center, totalMass);
48
51
  specs = plan.specs;
49
52
  sceneExtras = plan.sceneExtras;
50
53
  } else specs = buildPropExportPlan(normalizedScene, exportRoot, opts, size, center, totalMass);
54
+ const specNames = collectSpecNodeNames(specs);
55
+ ensureRootNameUnique(exportRoot, specNames);
56
+ const reserved = new Set(specNames);
57
+ for (const p of opts.patches ?? []) reserved.add(p.nodeName);
58
+ assignMissingEmitterNames(exportRoot, reserved);
51
59
  const stripped = stripUnloadedTextures(exportRoot);
52
60
  let exported;
53
61
  try {
@@ -55,8 +63,23 @@ async function compileKhrAssetGlb(normalizedScene, opts) {
55
63
  } finally {
56
64
  restoreStrippedTextures(stripped);
57
65
  }
58
- const allPatches = [...collectPreservedRigPatches(normalizedScene, opts.patches ?? []), ...opts.patches ?? []];
59
- const stamped = stampKolmoNodesIntoGlb(exported, allPatches);
66
+ const explicitPatches = opts.patches ?? [];
67
+ const preservedFromExport = collectPreservedRigPatches(exportRoot, [], { localToParent: true });
68
+ const preservedFallback = [];
69
+ if (coveredSourceNodes) {
70
+ const avoidNames = collectSceneNodeNames(exportRoot, specNames);
71
+ preservedFallback.push(...collectPreservedRigPatches(normalizedScene, preservedFromExport, {
72
+ localToParent: false,
73
+ skipSubtrees: coveredSourceNodes,
74
+ avoidNames
75
+ }));
76
+ }
77
+ const existingNames = collectSceneNodeNames(exportRoot, specNames);
78
+ for (const p of preservedFromExport) existingNames.add(p.nodeName);
79
+ for (const p of preservedFallback) existingNames.add(p.nodeName);
80
+ const safeExplicit = disambiguateExplicitPatches(explicitPatches, existingNames);
81
+ const withPreserved = stampKolmoNodesIntoGlb(exported, [...preservedFromExport, ...preservedFallback]);
82
+ const stamped = stampKolmoNodesIntoGlb(withPreserved, safeExplicit, void 0, { preserveExistingNodes: true });
60
83
  return new Uint8Array(stamped);
61
84
  }
62
85
  export { buildPatchPreviewEmitters, compileKhrAssetGlb, computeChopPartHinge, normalToMinusZQuaternion };
@@ -1 +1 @@
1
- {"version":3,"file":"khrCompiler.js","names":[],"sources":["../../src/importer/khrCompiler.ts"],"sourcesContent":["import * as THREE from \"three\";\nimport { exportKhrGlb, type KhrExportNodeSpec } from \"@khr3/core\";\nimport { stampKolmoNodesIntoGlb } from \"../schema/kolmoSchema.js\";\nimport {\n buildPatchPreviewEmitters,\n computeChopPartHinge,\n normalToMinusZQuaternion,\n type ChopHingeSpec,\n} from \"./chopHingeHelpers.js\";\nimport { buildCarExportPlan } from \"./khrCarPlanner.js\";\nimport {\n buildCraftExportPlan,\n buildPropExportPlan,\n collectPreservedRigPatches,\n restoreStrippedTextures,\n stripUnloadedTextures,\n type CarDriveMode,\n type KolmoAssetArchetype,\n type KolmoCompileOptions,\n type WheelVisualSource,\n} from \"./khrCraftPropCompiler.js\";\nimport { isMeshObject } from \"./sceneSiNormalize.js\";\n\ntype KhrSceneExtras = Parameters<typeof exportKhrGlb>[2];\n\nexport {\n buildPatchPreviewEmitters,\n computeChopPartHinge,\n normalToMinusZQuaternion,\n type CarDriveMode,\n type ChopHingeSpec,\n type KolmoAssetArchetype,\n type KolmoCompileOptions,\n type WheelVisualSource,\n};\n\nfunction computeLocalBounds(root: THREE.Object3D): THREE.Box3 {\n root.updateMatrixWorld(true);\n const invRoot = new THREE.Matrix4().copy(root.matrixWorld).invert();\n const relMat = new THREE.Matrix4();\n const box = new THREE.Box3();\n const v = new THREE.Vector3();\n root.traverse((obj) => {\n if (!isMeshObject(obj)) return;\n const pos = obj.geometry.getAttribute(\"position\");\n if (!pos || pos.count === 0) return;\n relMat.multiplyMatrices(invRoot, obj.matrixWorld);\n for (let i = 0; i < pos.count; i++) {\n v.fromBufferAttribute(pos, i).applyMatrix4(relMat);\n if (Number.isFinite(v.x) && Number.isFinite(v.y) && Number.isFinite(v.z)) box.expandByPoint(v);\n }\n });\n if (box.isEmpty()) box.set(new THREE.Vector3(-0.5, 0, -0.5), new THREE.Vector3(0.5, 1, 0.5));\n return box;\n}\n\nexport async function compileKhrAssetGlb(\n normalizedScene: THREE.Group,\n opts: KolmoCompileOptions,\n): Promise<Uint8Array<ArrayBuffer>> {\n const box = computeLocalBounds(normalizedScene);\n const sizeVec = box.getSize(new THREE.Vector3());\n const center = box.getCenter(new THREE.Vector3());\n const size: [number, number, number] = [\n Math.max(0.25, sizeVec.x),\n Math.max(0.25, sizeVec.y),\n Math.max(0.25, sizeVec.z),\n ];\n const totalMass = Math.max(5, opts.massKg || 1000);\n\n const exportRoot = new THREE.Group();\n exportRoot.name = opts.name || normalizedScene.name || `Kolmo_${opts.archetype}`;\n let specs: KhrExportNodeSpec[];\n let sceneExtras: KhrSceneExtras | undefined;\n\n if (opts.archetype === \"car\") {\n const plan = buildCarExportPlan(normalizedScene, exportRoot, opts, box, size, center, totalMass);\n specs = plan.specs;\n sceneExtras = plan.sceneExtras;\n } else if (opts.archetype === \"craft\") {\n const plan = buildCraftExportPlan(normalizedScene, exportRoot, opts, size, center, totalMass);\n specs = plan.specs;\n sceneExtras = plan.sceneExtras;\n } else {\n specs = buildPropExportPlan(normalizedScene, exportRoot, opts, size, center, totalMass);\n }\n\n const stripped = stripUnloadedTextures(exportRoot);\n let exported: Uint8Array;\n try {\n exported = new Uint8Array(await exportKhrGlb(exportRoot, specs, sceneExtras));\n } finally {\n restoreStrippedTextures(stripped);\n }\n\n const preserved = collectPreservedRigPatches(normalizedScene, opts.patches ?? []);\n const allPatches = [...preserved, ...(opts.patches ?? [])];\n const stamped = stampKolmoNodesIntoGlb(exported, allPatches);\n return new Uint8Array(stamped);\n}\n"],"mappings":";;;;;;;;AAoCA,SAAS,mBAAmB,MAAkC;CAC1D,KAAK,kBAAkB,IAAI;CAC3B,MAAM,UAAU,IAAI,MAAM,QAAQ,CAAC,CAAC,KAAK,KAAK,WAAW,CAAC,CAAC,OAAO;CAClE,MAAM,SAAS,IAAI,MAAM,QAAQ;CACjC,MAAM,MAAM,IAAI,MAAM,KAAK;CAC3B,MAAM,IAAI,IAAI,MAAM,QAAQ;CAC5B,KAAK,UAAU,QAAQ;EACnB,IAAI,CAAC,aAAa,GAAG,GAAG;EACxB,MAAM,MAAM,IAAI,SAAS,aAAa,UAAU;EAChD,IAAI,CAAC,OAAO,IAAI,UAAU,GA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AAoB,iBAAiB,YAAY,MAAM,MAAM,QAAQ,SAAS;CAG1F,MAAM,WAAW,sBAAsB,UAAU;CACjD,IAAI;CACJ,IAAI;EACA,WAAW,IAAI,WAAW,MAAM,aAAa,YAAY,OAAO,WAAW,CAAC;CAChF,UAAU;EACN,wBAAwB,QAAQ;CACpC;CAGA,MAAM,aAAa,CAAC,GADF,2BAA2B,iBAAiB,KAAK,WAAW,CAAC,CACxD,GAAW,GAAI,KAAK,WAAW,CAAC,CAAE;CACzD,MAAM,UAAU,uBAAuB,UAAU,UAAU;CAC3D,OAAO,IAAI,WAAW,OAAO;AACjC"}
1
+ {"version":3,"file":"khrCompiler.js","names":[],"sources":["../../src/importer/khrCompiler.ts"],"sourcesContent":["import * as THREE from \"three\";\nimport { exportKhrGlb, type KhrExportNodeSpec } from \"@khr3/core\";\nimport { stampKolmoNodesIntoGlb } from \"../schema/kolmoSchema.js\";\nimport {\n buildPatchPreviewEmitters,\n computeChopPartHinge,\n normalToMinusZQuaternion,\n type ChopHingeSpec,\n} from \"./chopHingeHelpers.js\";\nimport { buildCarExportPlan } from \"./khrCarPlanner.js\";\nimport {\n buildCraftExportPlan,\n buildPropExportPlan,\n collectPreservedRigPatches,\n restoreStrippedTextures,\n stripUnloadedTextures,\n type CarDriveMode,\n type KolmoAssetArchetype,\n type KolmoCompileOptions,\n type WheelVisualSource,\n} from \"./khrCraftPropCompiler.js\";\nimport {\n assignMissingEmitterNames,\n collectSceneNodeNames,\n collectSpecNodeNames,\n disambiguateExplicitPatches,\n ensureRootNameUnique,\n} from \"./khrNodeNameGuard.js\";\nimport { isMeshObject } from \"./sceneSiNormalize.js\";\n\ntype KhrSceneExtras = Parameters<typeof exportKhrGlb>[2];\n\nexport {\n buildPatchPreviewEmitters,\n computeChopPartHinge,\n normalToMinusZQuaternion,\n type CarDriveMode,\n type ChopHingeSpec,\n type KolmoAssetArchetype,\n type KolmoCompileOptions,\n type WheelVisualSource,\n};\n\nfunction computeLocalBounds(root: THREE.Object3D): THREE.Box3 {\n root.updateMatrixWorld(true);\n const invRoot = new THREE.Matrix4().copy(root.matrixWorld).invert();\n const relMat = new THREE.Matrix4();\n const box = new THREE.Box3();\n const v = new THREE.Vector3();\n root.traverse((obj) => {\n if (!isMeshObject(obj)) return;\n const pos = obj.geometry.getAttribute(\"position\");\n if (!pos || pos.count === 0) return;\n relMat.multiplyMatrices(invRoot, obj.matrixWorld);\n for (let i = 0; i < pos.count; i++) {\n v.fromBufferAttribute(pos, i).applyMatrix4(relMat);\n if (Number.isFinite(v.x) && Number.isFinite(v.y) && Number.isFinite(v.z)) box.expandByPoint(v);\n }\n });\n if (box.isEmpty()) box.set(new THREE.Vector3(-0.5, 0, -0.5), new THREE.Vector3(0.5, 1, 0.5));\n return box;\n}\n\nexport async function compileKhrAssetGlb(\n normalizedScene: THREE.Group,\n opts: KolmoCompileOptions,\n): Promise<Uint8Array<ArrayBuffer>> {\n const box = computeLocalBounds(normalizedScene);\n const sizeVec = box.getSize(new THREE.Vector3());\n const center = box.getCenter(new THREE.Vector3());\n const size: [number, number, number] = [\n Math.max(0.25, sizeVec.x),\n Math.max(0.25, sizeVec.y),\n Math.max(0.25, sizeVec.z),\n ];\n const totalMass = Math.max(5, opts.massKg || 1000);\n\n const exportRoot = new THREE.Group();\n exportRoot.name = opts.name || normalizedScene.name || `Kolmo_${opts.archetype}`;\n let specs: KhrExportNodeSpec[];\n let sceneExtras: KhrSceneExtras | undefined;\n let coveredSourceNodes: Set<THREE.Object3D> | null = null;\n\n if (opts.archetype === \"car\") {\n const plan = buildCarExportPlan(normalizedScene, exportRoot, opts, box, size, center, totalMass);\n specs = plan.specs;\n sceneExtras = plan.sceneExtras;\n coveredSourceNodes = plan.coveredSourceNodes;\n } else if (opts.archetype === \"craft\") {\n const plan = buildCraftExportPlan(normalizedScene, exportRoot, opts, size, center, totalMass);\n specs = plan.specs;\n sceneExtras = plan.sceneExtras;\n } else {\n specs = buildPropExportPlan(normalizedScene, exportRoot, opts, size, center, totalMass);\n }\n\n const specNames = collectSpecNodeNames(specs);\n ensureRootNameUnique(exportRoot, specNames);\n const reserved = new Set<string>(specNames);\n for (const p of opts.patches ?? []) reserved.add(p.nodeName);\n assignMissingEmitterNames(exportRoot, reserved);\n\n const stripped = stripUnloadedTextures(exportRoot);\n let exported: Uint8Array;\n try {\n exported = new Uint8Array(await exportKhrGlb(exportRoot, specs, sceneExtras));\n } finally {\n restoreStrippedTextures(stripped);\n }\n\n const explicitPatches = opts.patches ?? [];\n const preservedFromExport = collectPreservedRigPatches(exportRoot, [], { localToParent: true });\n const preservedFallback: ReturnType<typeof collectPreservedRigPatches> = [];\n if (coveredSourceNodes) {\n const avoidNames = collectSceneNodeNames(exportRoot, specNames);\n preservedFallback.push(\n ...collectPreservedRigPatches(normalizedScene, preservedFromExport, {\n localToParent: false,\n skipSubtrees: coveredSourceNodes,\n avoidNames,\n }),\n );\n }\n const existingNames = collectSceneNodeNames(exportRoot, specNames);\n for (const p of preservedFromExport) existingNames.add(p.nodeName);\n for (const p of preservedFallback) existingNames.add(p.nodeName);\n const safeExplicit = disambiguateExplicitPatches(explicitPatches, existingNames);\n const withPreserved = stampKolmoNodesIntoGlb(exported, [...preservedFromExport, ...preservedFallback]);\n const stamped = stampKolmoNodesIntoGlb(withPreserved, safeExplicit, undefined, { preserveExistingNodes: true });\n return new Uint8Array(stamped);\n}\n"],"mappings":";;;;;;;;;AA2CA,SAAS,mBAAmB,MAAkC;CAC1D,KAAK,kBAAkB,IAAI;CAC3B,MAAM,UAAU,IAAI,MAAM,QAAQ,CAAC,CAAC,KAAK,KAAK,WAAW,CAAC,CAAC,OAAO;CAClE,MAAM,SAAS,IAAI,MAAM,QAAQ;CACjC,MAAM,MAAM,IAAI,MAAM,KAAK;CAC3B,MAAM,IAAI,IAAI,MAAM,QAAQ;CAC5B,KAAK,UAAU,QAAQ;EACnB,IAAI,CAAC,aAAa,GAAG,GAAG;EACxB,MAAM,MAAM,IAAI,SAAS,aAAa,UAAU;EAChD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edTextures(root: THREE.Object3D): StrippedTextureSlot[];
34
34
  export declare function restoreStrippedTextures(stripped: readonly StrippedTextureSlot[]): void;
35
- export declare function collectPreservedRigPatches(scene: THREE.Object3D, explicitPatches?: readonly KolmoAuthoredNodePatch[]): KolmoAuthoredNodePatch[];
35
+ export interface CollectPreservedRigOptions {
36
+ localToParent?: boolean;
37
+ skipSubtrees?: ReadonlySet<THREE.Object3D>;
38
+ avoidNames?: ReadonlySet<string>;
39
+ }
40
+ export declare function collectPreservedRigPatches(scene: THREE.Object3D, explicitPatches?: readonly KolmoAuthoredNodePatch[], opts?: CollectPreservedRigOptions): KolmoAuthoredNodePatch[];
36
41
  export declare function buildCraftExportPlan(normalizedScene: THREE.Group, exportRoot: THREE.Group, opts: KolmoCompileOptions, size: readonly [number, number, number], center: THREE.Vector3, totalMass: number): {
37
42
  specs: KhrExportNodeSpec[];
38
43
  sceneExtras: Record<string, unknown>;
@@ -1,3 +1,4 @@
1
+ import { CRAFT_RESERVED_NAMES, PROP_RESERVED_NAMES, disambiguateCollidingName, disambiguateSubtreeNodeNames, stripEmptyReservedNodes } from "./khrNodeNameGuard.js";
1
2
  import { isMeshObject } from "./sceneSiNormalize.js";
2
3
  import * as THREE from "three";
3
4
  // src/importer/khrCraftPropCompiler.ts
@@ -61,66 +62,76 @@ var VALID_DRIVES = /* @__PURE__ */ new Set([
61
62
  "damage",
62
63
  "always"
63
64
  ]);
64
- function toKolmoExt(rawKolmo, rawVfx) {
65
- if (rawKolmo && typeof rawKolmo === "object") return structuredClone(rawKolmo);
66
- if (rawVfx && typeof rawVfx === "object") {
67
- const v = rawVfx;
68
- const kind = typeof v.kind === "string" && VALID_KINDS.has(v.kind) ? v.kind : "plume";
69
- const drive = typeof v.drive === "string" && VALID_DRIVES.has(v.drive) ? v.drive : "throttle";
70
- const color = Array.isArray(v.color) && v.color.length === 3 ? [
71
- Number(v.color[0]),
72
- Number(v.color[1]),
73
- Number(v.color[2])
74
- ] : void 0;
75
- const size = typeof v.size === "number" && v.size > 0 ? v.size : 1;
76
- return {
77
- kind,
78
- drive,
79
- ...color ? { color } : {},
80
- size
81
- };
82
- }
83
- return null;
65
+ function toKolmoExt(rawKolmo) {
66
+ if (!rawKolmo || typeof rawKolmo !== "object") return null;
67
+ const v = rawKolmo;
68
+ if (typeof v.socket === "string") return structuredClone(rawKolmo);
69
+ const kind = typeof v.kind === "string" && VALID_KINDS.has(v.kind) ? v.kind : "plume";
70
+ const drive = typeof v.drive === "string" && VALID_DRIVES.has(v.drive) ? v.drive : "throttle";
71
+ const color = Array.isArray(v.color) && v.color.length === 3 ? [
72
+ Number(v.color[0]),
73
+ Number(v.color[1]),
74
+ Number(v.color[2])
75
+ ] : void 0;
76
+ const size = typeof v.size === "number" && v.size > 0 ? v.size : 1;
77
+ return {
78
+ kind,
79
+ drive,
80
+ ...color ? { color } : {},
81
+ size
82
+ };
84
83
  }
85
- function collectPreservedRigPatches(scene, explicitPatches = []) {
84
+ function collectPreservedRigPatches(scene, explicitPatches = [], opts = {}) {
86
85
  scene.updateMatrixWorld(true);
87
86
  const invRoot = new THREE.Matrix4().copy(scene.matrixWorld).invert();
88
- const rel = new THREE.Matrix4();
89
- const pos = new THREE.Vector3();
90
- const quat = new THREE.Quaternion();
91
- const scl = new THREE.Vector3();
87
+ const rel = new THREE.Matrix4(), pos = new THREE.Vector3(), quat = new THREE.Quaternion(), scl = new THREE.Vector3();
92
88
  const taken = new Set(explicitPatches.map((p) => p.nodeName));
89
+ const forbidden = opts.avoidNames ? /* @__PURE__ */ new Set([...taken, ...opts.avoidNames]) : null;
93
90
  const out = [];
94
91
  let idx = 0;
95
- scene.traverse((obj) => {
96
- if (obj === scene) return;
97
- const ext = toKolmoExt(obj.userData?.KOLMO_emitter ?? obj.userData?.kolmoExtension, obj.userData?.KHR3_vfx_emitter);
98
- if (!ext) return;
99
- const nodeName = obj.name || `Preserved_Emitter_${idx++}`;
100
- if (taken.has(nodeName)) return;
101
- taken.add(nodeName);
102
- rel.multiplyMatrices(invRoot, obj.matrixWorld).decompose(pos, quat, scl);
103
- out.push({
104
- nodeName,
105
- translation: [
106
- r4(pos.x),
107
- r4(pos.y),
108
- r4(pos.z)
109
- ],
110
- rotation: [
111
- r4(quat.x),
112
- r4(quat.y),
113
- r4(quat.z),
114
- r4(quat.w)
115
- ],
116
- extension: ext
117
- });
118
- });
92
+ const visit = (obj) => {
93
+ if (obj !== scene) {
94
+ if (opts.skipSubtrees?.has(obj)) return;
95
+ const ext = toKolmoExt(obj.userData?.KOLMO_emitter ?? obj.userData?.kolmoExtension);
96
+ if (ext) {
97
+ const rawName = obj.name || `Preserved_Emitter_${idx++}`;
98
+ const nodeName = forbidden ? disambiguateCollidingName(rawName, forbidden) : rawName;
99
+ if (!taken.has(nodeName)) {
100
+ taken.add(nodeName);
101
+ forbidden?.add(nodeName);
102
+ if (opts.localToParent) {
103
+ pos.copy(obj.position);
104
+ quat.copy(obj.quaternion);
105
+ } else rel.multiplyMatrices(invRoot, obj.matrixWorld).decompose(pos, quat, scl);
106
+ out.push({
107
+ nodeName,
108
+ translation: [
109
+ r4(pos.x),
110
+ r4(pos.y),
111
+ r4(pos.z)
112
+ ],
113
+ rotation: [
114
+ r4(quat.x),
115
+ r4(quat.y),
116
+ r4(quat.z),
117
+ r4(quat.w)
118
+ ],
119
+ extension: ext
120
+ });
121
+ }
122
+ }
123
+ }
124
+ for (const c of obj.children) visit(c);
125
+ };
126
+ visit(scene);
119
127
  return out;
120
128
  }
121
129
  function buildCraftExportPlan(normalizedScene, exportRoot, opts, size, center, totalMass) {
122
130
  const [sx, sy, sz] = size;
123
- for (const child of normalizedScene.clone(true).children) exportRoot.add(child);
131
+ const visualClone = normalizedScene.clone(true);
132
+ stripEmptyReservedNodes(visualClone, CRAFT_RESERVED_NAMES);
133
+ disambiguateSubtreeNodeNames(visualClone, CRAFT_RESERVED_NAMES, false);
134
+ for (const child of [...visualClone.children]) exportRoot.add(child);
124
135
  const hull = new THREE.Object3D();
125
136
  hull.name = "HullBody";
126
137
  hull.position.set(center.x, center.y, center.z);
@@ -206,8 +217,10 @@ function buildPropExportPlan(normalizedScene, exportRoot, opts, size, center, to
206
217
  const [sx, sy, sz] = size;
207
218
  const propBody = new THREE.Group();
208
219
  propBody.name = "PropBody";
220
+ const visualClone = normalizedScene.clone(true);
221
+ disambiguateSubtreeNodeNames(visualClone, PROP_RESERVED_NAMES, false);
209
222
  let hasGeom = false;
210
- for (const child of normalizedScene.clone(true).children) {
223
+ for (const child of [...visualClone.children]) {
211
224
  propBody.add(child);
212
225
  child.traverse((obj) => {
213
226
  if (isMeshObject(obj) && (obj.geometry.getAttribute("position")?.count ?? 0) >= 3) hasGeom = true;
@@ -1 +1 @@
1
- {"version":3,"file":"khrCraftPropCompiler.js","names":[],"sources":["../../src/importer/khrCraftPropCompiler.ts"],"sourcesContent":["import * as THREE from \"three\";\nimport type { KhrExportNodeSpec } from \"@khr3/core\";\nimport type { KolmoAuthoredNodePatch, KolmoNodeExtension } from \"../schema/kolmoSchema.js\";\nimport type { WheelCutterSpec } from \"./fusedWheelDetect.js\";\nimport type { MeshIsland, WheelAxle } from \"./meshIslands.js\";\nimport { isMeshObject } from \"./sceneSiNormalize.js\";\nimport type { ChopPartRole } from \"./surfaceCutter.js\";\n\nexport type KolmoAssetArchetype = \"car\" | \"craft\" | \"prop\";\nexport type CarDriveMode = \"RWD\" | \"FWD\" | \"AWD\";\nexport type WheelVisualSource = \"imported\" | \"fleet12\";\n\nexport interface KolmoCompileOptions {\n archetype: KolmoAssetArchetype;\n massKg: number;\n powerOrThrust: number;\n driveType?: CarDriveMode;\n wheelSource?: WheelVisualSource;\n staticProp?: boolean;\n axles?: readonly WheelAxle[];\n islands?: readonly MeshIsland[];\n partPicks?: Readonly<Record<number, ChopPartRole>>;\n wheelCutters?: readonly WheelCutterSpec[];\n sealArchLiner?: boolean;\n mirrorX?: boolean;\n patches?: readonly KolmoAuthoredNodePatch[];\n name?: string;\n}\n\nconst STRIP_TEXTURE_SLOTS = [\n \"map\",\n \"normalMap\",\n \"roughnessMap\",\n \"metalnessMap\",\n \"aoMap\",\n \"emissiveMap\",\n] as const;\n\nexport const r4 = (n: number): number => Number(n.toFixed(4));\n\nexport const boxInertia = (m: number, x: number, y: number, z: number): [number, number, number] => [\n r4((m / 12) * (y * y + z * z)),\n r4((m / 12) * (x * x + z * z)),\n r4((m / 12) * (x * x + y * y)),\n];\n\nexport interface StrippedTextureSlot {\n rec: Record<string, THREE.Texture | null | undefined>;\n slot: string;\n tex: THREE.Texture;\n}\n\nexport function stripUnloadedTextures(root: THREE.Object3D): StrippedTextureSlot[] {\n const stripped: StrippedTextureSlot[] = [];\n root.traverse((obj) => {\n const mesh = obj as THREE.Mesh | null | undefined;\n if (!mesh?.isMesh || !mesh.material)\n return;\n const mats = Array.isArray(mesh.material) ? mesh.material : [mesh.material];\n for (const m of mats) {\n const mat = m as unknown as Record<string, THREE.Texture | null | undefined>;\n for (const slot of STRIP_TEXTURE_SLOTS) {\n const tex = mat[slot];\n if (tex && !tex.image) {\n stripped.push({ rec: mat, slot, tex });\n mat[slot] = null;\n }\n }\n }\n });\n return stripped;\n}\n\nexport function restoreStrippedTextures(stripped: readonly StrippedTextureSlot[]): void {\n for (const item of stripped)\n item.rec[item.slot] = item.tex;\n}\n\nconst VALID_KINDS = new Set([\"plume\", \"sparkle\", \"fume\", \"trail\", \"flare\"]);\nconst VALID_DRIVES = new Set([\"throttle\", \"boost\", \"brake\", \"slip\", \"reverse\", \"turn_l\", \"turn_r\", \"headlight\", \"fire\", \"damage\", \"always\"]);\n\nfunction toKolmoExt(rawKolmo: unknown, rawVfx: unknown): KolmoNodeExtension | null {\n if (rawKolmo && typeof rawKolmo === \"object\")\n return structuredClone(rawKolmo) as KolmoNodeExtension;\n if (rawVfx && typeof rawVfx === \"object\") {\n const v = rawVfx as Record<string, unknown>;\n const kind = typeof v.kind === \"string\" && VALID_KINDS.has(v.kind) ? v.kind : \"plume\";\n const drive = typeof v.drive === \"string\" && VALID_DRIVES.has(v.drive) ? v.drive : \"throttle\";\n const color = Array.isArray(v.color) && v.color.length === 3\n ? [Number(v.color[0]), Number(v.color[1]), Number(v.color[2])] as [number, number, number]\n : undefined;\n const size = typeof v.size === \"number\" && v.size > 0 ? v.size : 1;\n return { kind: kind as KolmoNodeExtension[\"kind\"], drive: drive as KolmoNodeExtension[\"drive\"], ...(color ? { color } : {}), size };\n }\n return null;\n}\n\nexport function collectPreservedRigPatches(\n scene: THREE.Object3D,\n explicitPatches: readonly KolmoAuthoredNodePatch[] = [],\n): KolmoAuthoredNodePatch[] {\n scene.updateMatrixWorld(true);\n const invRoot = new THREE.Matrix4().copy(scene.matrixWorld).invert();\n const rel = new THREE.Matrix4();\n const pos = new THREE.Vector3();\n const quat = new THREE.Quaternion();\n const scl = new THREE.Vector3();\n const taken = new Set(explicitPatches.map((p) => p.nodeName));\n const out: KolmoAuthoredNodePatch[] = [];\n let idx = 0;\n\n scene.traverse((obj) => {\n if (obj === scene)\n return;\n const ext = toKolmoExt(\n obj.userData?.KOLMO_emitter ?? obj.userData?.kolmoExtension,\n obj.userData?.KHR3_vfx_emitter,\n );\n if (!ext)\n return;\n const nodeName = obj.name || `Preserved_Emitter_${idx++}`;\n if (taken.has(nodeName))\n return;\n taken.add(nodeName);\n rel.multiplyMatrices(invRoot, obj.matrixWorld).decompose(pos, quat, scl);\n out.push({\n nodeName,\n translation: [r4(pos.x), r4(pos.y), r4(pos.z)],\n rotation: [r4(quat.x), r4(quat.y), r4(quat.z), r4(quat.w)],\n extension: ext,\n });\n });\n return out;\n}\n\nexport function buildCraftExportPlan(\n normalizedScene: THREE.Group,\n exportRoot: THREE.Group,\n opts: KolmoCompileOptions,\n size: readonly [number, number, number],\n center: THREE.Vector3,\n totalMass: number,\n): { specs: KhrExportNodeSpec[]; sceneExtras: Record<string, unknown> } {\n const [sx, sy, sz] = size;\n for (const child of normalizedScene.clone(true).children)\n exportRoot.add(child);\n const hull = new THREE.Object3D();\n hull.name = \"HullBody\";\n hull.position.set(center.x, center.y, center.z);\n exportRoot.add(hull);\n\n const maxThrust = Math.max(400, opts.powerOrThrust || 4500, Math.ceil(totalMass * 9.81 * 0.72));\n const specs: KhrExportNodeSpec[] = [\n {\n nodeName: \"HullBody\",\n motion: {\n isKinematic: false,\n mass: totalMass,\n centerOfMass: [0, r4(-sy * 0.06), 0],\n inertiaDiagonal: boxInertia(totalMass, sx, sy, sz),\n },\n collider: {\n shape: { type: \"box\", size: [r4(sx * 0.86), r4(sy * 0.78), r4(sz * 0.9)] },\n friction: 0.35,\n restitution: 0.08,\n },\n },\n ];\n for (const [name, dx, dz, inv] of [\n [\"Thruster_FL\", sx * 0.36, sz * 0.32, false],\n [\"Thruster_FR\", -sx * 0.36, sz * 0.32, true],\n [\"Thruster_RL\", sx * 0.36, -sz * 0.32, true],\n [\"Thruster_RR\", -sx * 0.36, -sz * 0.32, false],\n ] as const) {\n const thruster = new THREE.Object3D();\n thruster.name = name;\n thruster.position.set(center.x + dx, center.y, center.z + dz);\n exportRoot.add(thruster);\n specs.push({\n nodeName: name,\n extras: { ecctrlPropeller: { maxThrust, torqueRatio: 0.6, invertTorque: inv } },\n });\n }\n return {\n specs,\n sceneExtras: {\n droneTune: {\n controlMode: \"VELOCITY\",\n maxYawRate: 2.4,\n maxHorizSpeed: 44,\n maxVertSpeed: 22,\n maxTiltAngle: 0.52,\n airDragFactor: 0.18,\n },\n },\n };\n}\n\nexport function buildPropExportPlan(\n normalizedScene: THREE.Group,\n exportRoot: THREE.Group,\n opts: KolmoCompileOptions,\n size: readonly [number, number, number],\n center: THREE.Vector3,\n totalMass: number,\n): KhrExportNodeSpec[] {\n const [sx, sy, sz] = size;\n const propBody = new THREE.Group();\n propBody.name = \"PropBody\";\n let hasGeom = false;\n for (const child of normalizedScene.clone(true).children) {\n propBody.add(child);\n child.traverse((obj) => {\n if (isMeshObject(obj) && (obj.geometry.getAttribute(\"position\")?.count ?? 0) >= 3)\n hasGeom = true;\n });\n }\n exportRoot.add(propBody);\n return [\n {\n nodeName: \"PropBody\",\n motion: opts.staticProp\n ? { isKinematic: true }\n : {\n isKinematic: false,\n mass: totalMass,\n centerOfMass: [r4(center.x), r4(center.y), r4(center.z)],\n inertiaDiagonal: boxInertia(totalMass, sx, sy, sz),\n },\n collider: hasGeom\n ? { meshNodeName: \"PropBody\", convexHull: true, friction: 0.6, restitution: 0.1 }\n : { shape: { type: \"box\", size: [r4(sx), r4(sy), r4(sz)] }, friction: 0.6, restitution: 0.1 },\n },\n ];\n}\n"],"mappings":";;;AA6BA,IAAM,sBAAsB;CACxB;CACA;CACA;CACA;CACA;CACA;AACJ;AAEA,IAAa,MAAM,MAAsB,OAAO,EAAE,QAAQ,CAAC,CAAC;AAE5D,IAAa,cAAc,GAAW,GAAW,GAAW,MAAwC;CAChG,GAAI,IAAI,MAAO,IAAI,IAAI,IAAI,EAAE;CAC7B,GAAI,IAAI,MAAO,IAAI,IAAI,IAAI,EAAE;CAC7B,GAAI,IAAI,MAAO,IAAI,IAAI,IAAI,EAAE;AACjC;AAQA,SAAgB,sBAAsB,MAA6C;CAC/E,MAAM,WAAkC,CAAC;CACzC,KAAK,UAAU,QAAQ;EACnB,MAAM,OAAO;EACb,IAAI,CAAC,MAAM,UAAU,CAAC,KAAK,UACvB;EACJ,MAAM,OAAO,MAAM,QAAQ,KAAK,QAAQ,IAAI,KAAK,WAAW,CAAC,KAAK,QAAQ;EAC1E,KAAK,MAAM,KAAK,MAAM;GAClB,MAAM,MAAM;GACZ,KAAK,MAAM,QAAQ,qBAAqB;IACpC,MAAM,MAAM,IAAI;IAChB,IAAI,OAAO,CAAC,IAAI,OAAO;KACnB,SAAS,KAAK;MAAE,KAAK;MAAK;MAAM;KAAI,CAAC;KACrC,IAAI,QAAQ;IAChB;GACJ;EACJ;CACJ,CAAC;CACD,OAAO;AACX;AAEA,SAAgB,wBAAwB,UAAgD;CACpF,KAAK,MAAM,QAAQ,UACf,KAAK,IAAI,KAAK,QAAQ,KAAK;AACnC;AAE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,CAAC;CACL;CACA,WAAW,IAAI,QAAQ;CACvB,OAAO,CACH;EACI,UAAU;EACV,QAAQ,KAAK,aACP,EAAE,aAAa,KAAK,IACpB;GACI,aAAa;GACb,MAAM;GACN,cAAc;IAAC,GAAG,OAAO,CAAC;IAAG,GAAG,OAAO,CAAC;IAAG,GAAG,OAAO,CAAC;GAAC;GACvD,iBAAiB,WAAW,WAAW,IAAI,IAAI,EAAE;EACrD;EACN,UAAU,UACJ;GAAE,cAAc;GAAY,YAAY;GAAM,UAAU;GAAK,aAAa;EAAI,IAC9E;GAAE,OAAO;IAAE,MAAM;IAAO,MAAM;KAAC,GAAG,EAAE;KAAG,GAAG,EAAE;KAAG,GAAG,EAAE;IAAC;GAAE;GAAG,UAAU;GAAK,aAAa;EAAI;CACpG,CACJ;AACJ"}
1
+ {"version":3,"file":"khrCraftPropCompiler.js","names":[],"sources":["../../src/importer/khrCraftPropCompiler.ts"],"sourcesContent":["import * as THREE from \"three\";\nimport type { KhrExportNodeSpec } from \"@khr3/core\";\nimport type { KolmoAuthoredNodePatch, KolmoNodeExtension } from \"../schema/kolmoSchema.js\";\nimport type { WheelCutterSpec } from \"./fusedWheelDetect.js\";\nimport { CRAFT_RESERVED_NAMES, PROP_RESERVED_NAMES, disambiguateCollidingName, disambiguateSubtreeNodeNames, stripEmptyReservedNodes } from \"./khrNodeNameGuard.js\";\nimport type { MeshIsland, WheelAxle } from \"./meshIslands.js\";\nimport { isMeshObject } from \"./sceneSiNormalize.js\";\nimport type { ChopPartRole } from \"./surfaceCutter.js\";\n\nexport type KolmoAssetArchetype = \"car\" | \"craft\" | \"prop\";\nexport type CarDriveMode = \"RWD\" | \"FWD\" | \"AWD\";\nexport type WheelVisualSource = \"imported\" | \"fleet12\";\n\nexport interface KolmoCompileOptions {\n archetype: KolmoAssetArchetype;\n massKg: number;\n powerOrThrust: number;\n driveType?: CarDriveMode;\n wheelSource?: WheelVisualSource;\n staticProp?: boolean;\n axles?: readonly WheelAxle[];\n islands?: readonly MeshIsland[];\n partPicks?: Readonly<Record<number, ChopPartRole>>;\n wheelCutters?: readonly WheelCutterSpec[];\n sealArchLiner?: boolean;\n mirrorX?: boolean;\n patches?: readonly KolmoAuthoredNodePatch[];\n name?: string;\n}\n\nconst STRIP_TEXTURE_SLOTS = [\"map\", \"normalMap\", \"roughnessMap\", \"metalnessMap\", \"aoMap\", \"emissiveMap\"] as const;\n\nexport const r4 = (n: number): number => Number(n.toFixed(4));\n\nexport const boxInertia = (m: number, x: number, y: number, z: number): [number, number, number] => [\n r4((m / 12) * (y * y + z * z)),\n r4((m / 12) * (x * x + z * z)),\n r4((m / 12) * (x * x + y * y)),\n];\n\nexport interface StrippedTextureSlot { rec: Record<string, THREE.Texture | null | undefined>; slot: string; tex: THREE.Texture; }\n\nexport function stripUnloadedTextures(root: THREE.Object3D): StrippedTextureSlot[] {\n const stripped: StrippedTextureSlot[] = [];\n root.traverse((obj) => {\n const mesh = obj as THREE.Mesh | null | undefined;\n if (!mesh?.isMesh || !mesh.material)\n return;\n const mats = Array.isArray(mesh.material) ? mesh.material : [mesh.material];\n for (const m of mats) {\n const mat = m as unknown as Record<string, THREE.Texture | null | undefined>;\n for (const slot of STRIP_TEXTURE_SLOTS) {\n const tex = mat[slot];\n if (tex && !tex.image) {\n stripped.push({ rec: mat, slot, tex });\n mat[slot] = null;\n }\n }\n }\n });\n return stripped;\n}\n\nexport function restoreStrippedTextures(stripped: readonly StrippedTextureSlot[]): void {\n for (const item of stripped)\n item.rec[item.slot] = item.tex;\n}\n\nconst VALID_KINDS = new Set([\"plume\", \"sparkle\", \"fume\", \"trail\", \"flare\"]);\nconst VALID_DRIVES = new Set([\"throttle\", \"boost\", \"brake\", \"slip\", \"reverse\", \"turn_l\", \"turn_r\", \"headlight\", \"fire\", \"damage\", \"always\"]);\n\nfunction toKolmoExt(rawKolmo: unknown): KolmoNodeExtension | null {\n if (!rawKolmo || typeof rawKolmo !== \"object\")\n return null;\n const v = rawKolmo as Record<string, unknown>;\n if (typeof v.socket === \"string\")\n return structuredClone(rawKolmo) as KolmoNodeExtension;\n const kind = typeof v.kind === \"string\" && VALID_KINDS.has(v.kind) ? v.kind : \"plume\";\n const drive = typeof v.drive === \"string\" && VALID_DRIVES.has(v.drive) ? v.drive : \"throttle\";\n const color = Array.isArray(v.color) && v.color.length === 3\n ? [Number(v.color[0]), Number(v.color[1]), Number(v.color[2])] as [number, number, number]\n : undefined;\n const size = typeof v.size === \"number\" && v.size > 0 ? v.size : 1;\n return { kind: kind as KolmoNodeExtension[\"kind\"], drive: drive as KolmoNodeExtension[\"drive\"], ...(color ? { color } : {}), size };\n}\n\nexport interface CollectPreservedRigOptions {\n localToParent?: boolean;\n skipSubtrees?: ReadonlySet<THREE.Object3D>;\n avoidNames?: ReadonlySet<string>;\n}\n\nexport function collectPreservedRigPatches(\n scene: THREE.Object3D,\n explicitPatches: readonly KolmoAuthoredNodePatch[] = [],\n opts: CollectPreservedRigOptions = {},\n): KolmoAuthoredNodePatch[] {\n scene.updateMatrixWorld(true);\n const invRoot = new THREE.Matrix4().copy(scene.matrixWorld).invert();\n const rel = new THREE.Matrix4(), pos = new THREE.Vector3(), quat = new THREE.Quaternion(), scl = new THREE.Vector3();\n const taken = new Set(explicitPatches.map((p) => p.nodeName));\n const forbidden = opts.avoidNames ? new Set([...taken, ...opts.avoidNames]) : null;\n const out: KolmoAuthoredNodePatch[] = [];\n let idx = 0;\n const visit = (obj: THREE.Object3D): void => {\n if (obj !== scene) {\n if (opts.skipSubtrees?.has(obj)) return;\n const ext = toKolmoExt(obj.userData?.KOLMO_emitter ?? obj.userData?.kolmoExtension);\n if (ext) {\n const rawName = obj.name || `Preserved_Emitter_${idx++}`;\n const nodeName = forbidden ? disambiguateCollidingName(rawName, forbidden) : rawName;\n if (!taken.has(nodeName)) {\n taken.add(nodeName);\n forbidden?.add(nodeName);\n if (opts.localToParent) { pos.copy(obj.position); quat.copy(obj.quaternion); }\n else rel.multiplyMatrices(invRoot, obj.matrixWorld).decompose(pos, quat, scl);\n out.push({\n nodeName,\n translation: [r4(pos.x), r4(pos.y), r4(pos.z)],\n rotation: [r4(quat.x), r4(quat.y), r4(quat.z), r4(quat.w)],\n extension: ext,\n });\n }\n }\n }\n for (const c of obj.children) visit(c);\n };\n visit(scene);\n return out;\n}\n\nexport function buildCraftExportPlan(\n normalizedScene: THREE.Group,\n exportRoot: THREE.Group,\n opts: KolmoCompileOptions,\n size: readonly [number, number, number],\n center: THREE.Vector3,\n totalMass: number,\n): { specs: KhrExportNodeSpec[]; sceneExtras: Record<string, unknown> } {\n const [sx, sy, sz] = size;\n const visualClone = normalizedScene.clone(true);\n stripEmptyReservedNodes(visualClone, CRAFT_RESERVED_NAMES);\n disambiguateSubtreeNodeNames(visualClone, CRAFT_RESERVED_NAMES, false);\n for (const child of [...visualClone.children])\n exportRoot.add(child);\n const hull = new THREE.Object3D();\n hull.name = \"HullBody\";\n hull.position.set(center.x, center.y, center.z);\n exportRoot.add(hull);\n\n const maxThrust = Math.max(400, opts.powerOrThrust || 4500, Math.ceil(totalMass * 9.81 * 0.72));\n const specs: KhrExportNodeSpec[] = [\n {\n nodeName: \"HullBody\",\n motion: {\n isKinematic: false,\n mass: totalMass,\n centerOfMass: [0, r4(-sy * 0.06), 0],\n inertiaDiagonal: boxInertia(totalMass, sx, sy, sz),\n },\n collider: {\n shape: { type: \"box\", size: [r4(sx * 0.86), r4(sy * 0.78), r4(sz * 0.9)] },\n friction: 0.35,\n restitution: 0.08,\n },\n },\n ];\n for (const [name, dx, dz, inv] of [\n [\"Thruster_FL\", sx * 0.36, sz * 0.32, false],\n [\"Thruster_FR\", -sx * 0.36, sz * 0.32, true],\n [\"Thruster_RL\", sx * 0.36, -sz * 0.32, true],\n [\"Thruster_RR\", -sx * 0.36, -sz * 0.32, false],\n ] as const) {\n const thruster = new THREE.Object3D();\n thruster.name = name;\n thruster.position.set(center.x + dx, center.y, center.z + dz);\n exportRoot.add(thruster);\n specs.push({\n nodeName: name,\n extras: { ecctrlPropeller: { maxThrust, torqueRatio: 0.6, invertTorque: inv } },\n });\n }\n return {\n specs,\n sceneExtras: {\n droneTune: {\n controlMode: \"VELOCITY\",\n maxYawRate: 2.4,\n maxHorizSpeed: 44,\n maxVertSpeed: 22,\n maxTiltAngle: 0.52,\n airDragFactor: 0.18,\n },\n },\n };\n}\n\nexport function buildPropExportPlan(\n normalizedScene: THREE.Group,\n exportRoot: THREE.Group,\n opts: KolmoCompileOptions,\n size: readonly [number, number, number],\n center: THREE.Vector3,\n totalMass: number,\n): KhrExportNodeSpec[] {\n const [sx, sy, sz] = size;\n const propBody = new THREE.Group();\n propBody.name = \"PropBody\";\n const visualClone = normalizedScene.clone(true);\n disambiguateSubtreeNodeNames(visualClone, PROP_RESERVED_NAMES, false);\n let hasGeom = false;\n for (const child of [...visualClone.children]) {\n propBody.add(child);\n child.traverse((obj) => {\n if (isMeshObject(obj) && (obj.geometry.getAttribute(\"position\")?.count ?? 0) >= 3)\n hasGeom = true;\n });\n }\n exportRoot.add(propBody);\n return [\n {\n nodeName: \"PropBody\",\n motion: opts.staticProp\n ? { isKinematic: true }\n : {\n isKinematic: false,\n mass: totalMass,\n centerOfMass: [r4(center.x), r4(center.y), r4(center.z)],\n inertiaDiagonal: boxInertia(totalMass, sx, sy, sz),\n },\n collider: hasGeom\n ? { meshNodeName: \"PropBody\", convexHull: true, friction: 0.6, restitution: 0.1 }\n : { shape: { type: \"box\", size: [r4(sx), r4(sy), r4(sz)] }, friction: 0.6, restitution: 0.1 },\n },\n ];\n}\n"],"mappings":";;;;AA8BA,IAAM,sBAAsB;CAAC;CAAO;CAAa;CAAgB;CAAgB;CAAS;AAAa;AAEvG,IAAa,MAAM,MAAsB,OAAO,EAAE,QAAQ,CAAC,CAAC;AAE5D,IAAa,cAAc,GAAW,GAAW,GAAW,MAAwC;CAChG,GAAI,IAAI,MAAO,IAAI,IAAI,IAAI,EAAE;CAC7B,GAAI,IAAI,MAAO,IAAI,IAAI,IAAI,EAAE;CAC7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P,EAAE,aAAa,KAAK,IACpB;GACI,aAAa;GACb,MAAM;GACN,cAAc;IAAC,GAAG,OAAO,CAAC;IAAG,GAAG,OAAO,CAAC;IAAG,GAAG,OAAO,CAAC;GAAC;GACvD,iBAAiB,WAAW,WAAW,IAAI,IAAI,EAAE;EACrD;EACN,UAAU,UACJ;GAAE,cAAc;GAAY,YAAY;GAAM,UAAU;GAAK,aAAa;EAAI,IAC9E;GAAE,OAAO;IAAE,MAAM;IAAO,MAAM;KAAC,GAAG,EAAE;KAAG,GAAG,EAAE;KAAG,GAAG,EAAE;IAAC;GAAE;GAAG,UAAU;GAAK,aAAa;EAAI;CACpG,CACJ;AACJ"}
@@ -0,0 +1,20 @@
1
+ import * as THREE from "three";
2
+ import type { KhrExportNodeSpec } from "@khr3/core";
3
+ import { disambiguateExplicitPatches } from "../schema/kolmoSchema.js";
4
+ export { disambiguateExplicitPatches };
5
+ export declare const CRAFT_RESERVED_NAMES: ReadonlySet<string>;
6
+ export declare const PROP_RESERVED_NAMES: ReadonlySet<string>;
7
+ export declare function hasMeshDescendant(obj: THREE.Object3D): boolean;
8
+ export declare function hasNodeEmitterData(obj: THREE.Object3D): boolean;
9
+ export declare function hasEmitterDescendant(obj: THREE.Object3D): boolean;
10
+ export declare function stripEmptyReservedNodes(root: THREE.Object3D, reservedNames: ReadonlySet<string>): void;
11
+ export declare function disambiguateCollidingName(baseName: string, forbidden: ReadonlySet<string>): string;
12
+ export declare function assignMissingEmitterNames(root: THREE.Object3D, reservedNames?: ReadonlySet<string>): void;
13
+ export declare function disambiguateSubtreeNodeNames(root: THREE.Object3D, reservedNames: ReadonlySet<string>, includeRoot?: boolean, externalTaken?: Iterable<string>): void;
14
+ export declare function collectSceneNodeNames(root: THREE.Object3D, extra?: Iterable<string>): Set<string>;
15
+ export declare function collectSpecNodeNames(specs: readonly KhrExportNodeSpec[]): Set<string>;
16
+ export declare function ensureRootNameUnique(root: THREE.Object3D, reservedNames: ReadonlySet<string>): void;
17
+ export declare function disambiguateExportSubtrees(exportRoot: THREE.Object3D, specs: readonly KhrExportNodeSpec[], subtrees: readonly {
18
+ obj: THREE.Object3D;
19
+ includeRoot: boolean;
20
+ }[]): void;
@@ -0,0 +1,139 @@
1
+ import { disambiguateExplicitPatches } from "../schema/kolmoStamp.js";
2
+ import { isMeshObject } from "./sceneSiNormalize.js";
3
+ import "three";
4
+ // src/importer/khrNodeNameGuard.ts
5
+ var CRAFT_RESERVED_NAMES = /* @__PURE__ */ new Set([
6
+ "HullBody",
7
+ "Thruster_FL",
8
+ "Thruster_FR",
9
+ "Thruster_RL",
10
+ "Thruster_RR"
11
+ ]);
12
+ var PROP_RESERVED_NAMES = /* @__PURE__ */ new Set(["PropBody"]);
13
+ function hasMeshDescendant(obj) {
14
+ let found = false;
15
+ obj.traverse((cur) => {
16
+ if (!found && isMeshObject(cur)) found = true;
17
+ });
18
+ return found;
19
+ }
20
+ function hasNodeEmitterData(obj) {
21
+ const ud = obj.userData;
22
+ if (!ud) return false;
23
+ return Boolean(ud.KOLMO_emitter && typeof ud.KOLMO_emitter === "object" || ud.kolmoExtension && typeof ud.kolmoExtension === "object");
24
+ }
25
+ function hasEmitterDescendant(obj) {
26
+ let found = false;
27
+ obj.traverse((cur) => {
28
+ if (!found && hasNodeEmitterData(cur)) found = true;
29
+ });
30
+ return found;
31
+ }
32
+ function stripEmptyReservedNodes(root, reservedNames) {
33
+ for (const child of [...root.children]) {
34
+ if (child.name && reservedNames.has(child.name) && !hasMeshDescendant(child) && !hasEmitterDescendant(child)) {
35
+ root.remove(child);
36
+ continue;
37
+ }
38
+ stripEmptyReservedNodes(child, reservedNames);
39
+ }
40
+ }
41
+ function disambiguateCollidingName(baseName, forbidden) {
42
+ if (!forbidden.has(baseName)) return baseName;
43
+ let candidate = `${baseName}_Visual`;
44
+ let idx = 1;
45
+ while (forbidden.has(candidate)) candidate = `${baseName}_Visual_${idx++}`;
46
+ return candidate;
47
+ }
48
+ function assignMissingEmitterNames(root, reservedNames) {
49
+ const taken = new Set(reservedNames);
50
+ root.traverse((obj) => {
51
+ if (obj.name) taken.add(obj.name);
52
+ });
53
+ let idx = 0;
54
+ root.traverse((obj) => {
55
+ if (obj === root || obj.name || !hasNodeEmitterData(obj)) return;
56
+ let candidate = `Preserved_Emitter_${idx++}`;
57
+ while (taken.has(candidate)) candidate = `Preserved_Emitter_${idx++}`;
58
+ taken.add(candidate);
59
+ obj.name = candidate;
60
+ });
61
+ }
62
+ function disambiguateSubtreeNodeNames(root, reservedNames, includeRoot = true, externalTaken) {
63
+ const taken = new Set(reservedNames);
64
+ if (externalTaken) {
65
+ for (const n of externalTaken) if (n) taken.add(n);
66
+ }
67
+ const seen = new Set(taken);
68
+ root.traverse((obj) => {
69
+ if ((includeRoot || obj !== root) && obj.name) taken.add(obj.name);
70
+ });
71
+ root.traverse((obj) => {
72
+ if (!includeRoot && obj === root || !obj.name) return;
73
+ if (seen.has(obj.name)) {
74
+ const candidate = disambiguateCollidingName(obj.name, taken);
75
+ taken.add(candidate);
76
+ obj.name = candidate;
77
+ }
78
+ seen.add(obj.name);
79
+ });
80
+ }
81
+ function collectSceneNodeNames(root, extra) {
82
+ const names = new Set(extra);
83
+ root.traverse((obj) => {
84
+ if (obj.name) names.add(obj.name);
85
+ });
86
+ return names;
87
+ }
88
+ function collectSpecNodeNames(specs) {
89
+ const names = /* @__PURE__ */ new Set();
90
+ for (const spec of specs) {
91
+ if (spec.nodeName) names.add(spec.nodeName);
92
+ if (spec.collider?.meshNodeName) names.add(spec.collider.meshNodeName);
93
+ if (spec.joint?.connectedNodeName) names.add(spec.joint.connectedNodeName);
94
+ }
95
+ return names;
96
+ }
97
+ function ensureRootNameUnique(root, reservedNames) {
98
+ if (!root.name) return;
99
+ const taken = new Set(reservedNames);
100
+ let collides = reservedNames.has(root.name);
101
+ root.traverse((obj) => {
102
+ if (obj !== root && obj.name) {
103
+ taken.add(obj.name);
104
+ if (obj.name === root.name) collides = true;
105
+ }
106
+ });
107
+ if (!collides) return;
108
+ let candidate = `${root.name}_Asset`;
109
+ let idx = 1;
110
+ while (taken.has(candidate)) candidate = `${root.name}_Asset_${idx++}`;
111
+ root.name = candidate;
112
+ }
113
+ function disambiguateExportSubtrees(exportRoot, specs, subtrees) {
114
+ if (subtrees.length === 0) return;
115
+ const specNames = collectSpecNodeNames(specs);
116
+ const userNodes = /* @__PURE__ */ new Set();
117
+ for (const t of subtrees) t.obj.traverse((o) => {
118
+ if (t.includeRoot || o !== t.obj) userNodes.add(o);
119
+ });
120
+ const seen = new Set(specNames);
121
+ const taken = new Set(specNames);
122
+ exportRoot.traverse((o) => {
123
+ if (!o.name) return;
124
+ taken.add(o.name);
125
+ if (o !== exportRoot && !userNodes.has(o)) seen.add(o.name);
126
+ });
127
+ for (const t of subtrees) t.obj.traverse((o) => {
128
+ if (!t.includeRoot && o === t.obj || !o.name) return;
129
+ if (seen.has(o.name)) {
130
+ const candidate = disambiguateCollidingName(o.name, taken);
131
+ taken.add(candidate);
132
+ o.name = candidate;
133
+ }
134
+ seen.add(o.name);
135
+ });
136
+ }
137
+ export { CRAFT_RESERVED_NAMES, PROP_RESERVED_NAMES, assignMissingEmitterNames, collectSceneNodeNames, collectSpecNodeNames, disambiguateCollidingName, disambiguateExplicitPatches, disambiguateExportSubtrees, disambiguateSubtreeNodeNames, ensureRootNameUnique, hasEmitterDescendant, hasMeshDescendant, hasNodeEmitterData, stripEmptyReservedNodes };
138
+
139
+ //# sourceMappingURL=khrNodeNameGuard.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"khrNodeNameGuard.js","names":[],"sources":["../../src/importer/khrNodeNameGuard.ts"],"sourcesContent":["import * as THREE from \"three\";\nimport type { KhrExportNodeSpec } from \"@khr3/core\";\nimport { disambiguateExplicitPatches } from \"../schema/kolmoSchema.js\";\nimport { isMeshObject } from \"./sceneSiNormalize.js\";\n\nexport { disambiguateExplicitPatches };\n\nexport const CRAFT_RESERVED_NAMES: ReadonlySet<string> = new Set([\n \"HullBody\",\n \"Thruster_FL\",\n \"Thruster_FR\",\n \"Thruster_RL\",\n \"Thruster_RR\",\n]);\n\nexport const PROP_RESERVED_NAMES: ReadonlySet<string> = new Set([\"PropBody\"]);\n\nexport function hasMeshDescendant(obj: THREE.Object3D): boolean {\n let found = false;\n obj.traverse((cur) => {\n if (!found && isMeshObject(cur)) found = true;\n });\n return found;\n}\n\nexport function hasNodeEmitterData(obj: THREE.Object3D): boolean {\n const ud = obj.userData as Record<string, unknown> | undefined;\n if (!ud) return false;\n return Boolean(\n (ud.KOLMO_emitter && typeof ud.KOLMO_emitter === \"object\") ||\n (ud.kolmoExtension && typeof ud.kolmoExtension === \"object\"),\n );\n}\n\nexport function hasEmitterDescendant(obj: THREE.Object3D): boolean {\n let found = false;\n obj.traverse((cur) => {\n if (!found && hasNodeEmitterData(cur)) found = true;\n });\n return found;\n}\n\nexport function stripEmptyReservedNodes(root: THREE.Object3D, reservedNames: ReadonlySet<string>): void {\n for (const child of [...root.children]) {\n if (child.name && reservedNames.has(child.name) && !hasMeshDescendant(child) && !hasEmitterDescendant(child)) {\n root.remove(child);\n continue;\n }\n stripEmptyReservedNodes(child, reservedNames);\n }\n}\n\nexport function disambiguateCollidingName(baseName: string, forbidden: ReadonlySet<string>): string {\n if (!forbidden.has(baseName)) return baseName;\n let candidate = `${baseName}_Visual`;\n let idx = 1;\n while (forbidden.has(candidate)) candidate = `${baseName}_Visual_${idx++}`;\n return candidate;\n}\n\nexport function assignMissingEmitterNames(root: THREE.Object3D, reservedNames?: ReadonlySet<string>): void {\n const taken = new Set<string>(reservedNames);\n root.traverse((obj) => {\n if (obj.name) taken.add(obj.name);\n });\n let idx = 0;\n root.traverse((obj) => {\n if (obj === root || obj.name || !hasNodeEmitterData(obj)) return;\n let candidate = `Preserved_Emitter_${idx++}`;\n while (taken.has(candidate)) candidate = `Preserved_Emitter_${idx++}`;\n taken.add(candidate);\n obj.name = candidate;\n });\n}\n\nexport function disambiguateSubtreeNodeNames(\n root: THREE.Object3D,\n reservedNames: ReadonlySet<string>,\n includeRoot = true,\n externalTaken?: Iterable<string>,\n): void {\n const taken = new Set<string>(reservedNames);\n if (externalTaken) {\n for (const n of externalTaken) {\n if (n) taken.add(n);\n }\n }\n const seen = new Set<string>(taken);\n root.traverse((obj) => {\n if ((includeRoot || obj !== root) && obj.name) taken.add(obj.name);\n });\n root.traverse((obj) => {\n if ((!includeRoot && obj === root) || !obj.name) return;\n if (seen.has(obj.name)) {\n const candidate = disambiguateCollidingName(obj.name, taken);\n taken.add(candidate);\n obj.name = candidate;\n }\n seen.add(obj.name);\n });\n}\n\nexport function collectSceneNodeNames(root: THREE.Object3D, extra?: Iterable<string>): Set<string> {\n const names = new Set<string>(extra);\n root.traverse((obj) => {\n if (obj.name) names.add(obj.name);\n });\n return names;\n}\n\nexport function collectSpecNodeNames(specs: readonly KhrExportNodeSpec[]): Set<string> {\n const names = new Set<string>();\n for (const spec of specs) {\n if (spec.nodeName) names.add(spec.nodeName);\n if (spec.collider?.meshNodeName) names.add(spec.collider.meshNodeName);\n if (spec.joint?.connectedNodeName) names.add(spec.joint.connectedNodeName);\n }\n return names;\n}\n\nexport function ensureRootNameUnique(root: THREE.Object3D, reservedNames: ReadonlySet<string>): void {\n if (!root.name) return;\n const taken = new Set<string>(reservedNames);\n let collides = reservedNames.has(root.name);\n root.traverse((obj) => {\n if (obj !== root && obj.name) {\n taken.add(obj.name);\n if (obj.name === root.name) collides = true;\n }\n });\n if (!collides) return;\n let candidate = `${root.name}_Asset`;\n let idx = 1;\n while (taken.has(candidate)) candidate = `${root.name}_Asset_${idx++}`;\n root.name = candidate;\n}\n\nexport function disambiguateExportSubtrees(\n exportRoot: THREE.Object3D,\n specs: readonly KhrExportNodeSpec[],\n subtrees: readonly { obj: THREE.Object3D; includeRoot: boolean }[],\n): void {\n if (subtrees.length === 0) return;\n const specNames = collectSpecNodeNames(specs);\n const userNodes = new Set<THREE.Object3D>();\n for (const t of subtrees) {\n t.obj.traverse((o) => {\n if (t.includeRoot || o !== t.obj) userNodes.add(o);\n });\n }\n const seen = new Set<string>(specNames);\n const taken = new Set<string>(specNames);\n exportRoot.traverse((o) => {\n if (!o.name) return;\n taken.add(o.name);\n if (o !== exportRoot && !userNodes.has(o)) seen.add(o.name);\n });\n for (const t of subtrees) {\n t.obj.traverse((o) => {\n if ((!t.includeRoot && o === t.obj) || !o.name) return;\n if (seen.has(o.name)) {\n const candidate = disambiguateCollidingName(o.name, taken);\n taken.add(candidate);\n o.name = candidate;\n }\n seen.add(o.name);\n });\n }\n}\n"],"mappings":";;;;AAOA,IAAa,uCAA4C,IAAI,IAAI;CAC7D;CACA;CACA;CACA;CACA;AACJ,CAAC;AAED,IAAa,sCAA2C,IAAI,IAAI,CAAC,UAAU,CAAC;AAE5E,SAAgB,kBAAkB,KAA8B;CAC5D,IAAI,QAAQ;CACZ,IAAI,UAAU,QAAQ;EAClB,IAAI,CAAC,SAAS,aAAa,GAAG,GAAG,QAAQ;CAC7C,CAAC;CACD,OAAO;AACX;AAEA,SAAgB,mBAAmB,KAA8B;CAC7D,MAAM,KAAK,IAAI;CACf,IAAI,CAAC,IAAI,OAAO;CAChB,OAAO,QACF,GAAG,iBAAiB,OAAO,GAAG,kBAAkB,YAChD,GAAG,kBAAkB,OAAO,GAAG,mBAAmB,QACvD;AACJ;AAEA,SAAgB,qBAAqB,KAA8B;CAC/D,IAAI,QAAQ;CACZ,IAAI,UAAU,QAAQ;EAClB,IAAI,CAAC,SAAS,mBAAmB,GAAG,GAAG,QAAQ;CACnD,CAAC;CACD,OAAO;AACX;AAEA,SAAgB,wBAAwB,MAAsB,eAA0C;CACpG,KAAK,MAAM,SAAS,CAAC,GAAG,KAAK,QAAQ,GAAG;EACpC,IAAI,MAAM,QAAQ,cAAc,IAAI,MAAM,IAAI,KAAK,CAAC,kBAAkB,KAAK,KAAK,CAAC,qBAAqB,KAAK,GAAG;GAC1G,KAAK,OAAO,KAAK;GACjB;EACJ;EACA,wBAAwB,OAAO,aAAa;CAChD;AACJ;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