Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 | 1x 1x 1x 362x 362x 362x 362x 362x 47589x 47589x 362x 362x 47589x 47589x 362x 362x 360x 47024x 45897x 45897x 47024x 1127x 1127x 47024x 360x 362x 362x 47589x 47589x 2369x 2369x 2369x 47589x 362x 268x 2101x 2101x 2101x 268x 362x 362x 362x 362x 362x 47589x 1468x 1468x 1468x 47589x 47589x 47589x 47589x 47589x 47589x 92298x 46121x 46121x 46121x 92298x 47589x 47589x 1468x 3729x 3729x 1468x 47589x 182x 182x 182x 16x 47589x 47589x 47589x 47589x 1468x 47589x 47589x 47589x 47589x 47589x 47589x 47589x 1468x 1468x 47567x 47567x 1468x 1468x 47589x 47589x 47589x 342x 1126x 1x 1125x 14x 1111x 680x 431x 340x 91x 47589x 47589x 47589x 47589x 47589x 47589x 47589x 47589x 47589x 47589x 47589x 47589x 47589x 47589x 47589x 47589x 47589x 47589x 1468x 47589x 47589x 47589x 47589x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 340x 47589x 680x 680x 680x 680x 680x 680x 680x 680x 680x 1128x 340x 340x 340x 340x 340x 340x 340x 340x 448x 108x 108x 2369x 2369x 2369x 2369x 2369x 2369x 108x 42x 202x 202x 202x 202x 1777x 1777x 1777x 1777x 1777x 1777x 1777x 1777x 1777x 1777x 202x 202x 202x 202x 202x 202x 202x 202x 202x 202x 202x 202x 202x 202x 202x 108x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 66x 108x 1468x 1468x 1468x 1468x 1468x 1468x 1468x 1468x 1468x 1468x 1468x 1468x 1468x 1468x 362x 20x 19x 19x 19x 19x 19x 19x 2107x 2107x 19x 19x 107x 107x 107x 107x 68x 68x 68x 107x 107x 19x 91x 91x 2084x 2084x 2084x 91x 91x 91x 19x 19x 19x 120x 106x 106x 106x 106x 104x 31x 31x 14x 19x 19x 19x 19x 19x 19x 19x 2107x 710x 710x 2107x 19x 20x 362x 362x 362x 1127x 1127x 1127x 1088x 1088x 1127x 1127x 1127x 1127x 1127x 1127x 1127x 1127x 1127x 1127x 1127x 1127x 1127x 1127x 1127x 1127x 362x 362x 362x 1088x 1088x 1088x 1088x 362x 1057x 1029x 1049x 28x 28x 28x 28x 59x 59x 59x 59x 59x 59x 59x 28x 28x 28x 28x 28x 28x 1057x 362x 1468x 1468x 1467x 1468x 361x 1468x 1x 1x 1107x 1106x 1106x 1468x 362x 362x 47589x 680x 680x 680x 680x 680x 680x 680x 680x 680x 680x 680x 680x 47589x 47589x 362x 362x 362x 362x 362x 362x 362x 362x 362x 362x 362x 362x 362x 362x 1x | import {
PlacedPart,
ConnectionLink,
ClusteredCompoundBody,
ExtractedJoint,
RobotAssemblySpec,
} from './types';
import { TECHNIC_PART_CATALOG, isChainPart } from './part-catalog';
export interface PreSolverInput {
name: string;
parts: PlacedPart[];
links: ConnectionLink[];
}
export interface PreSolverOptions {
disablePreSolver?: boolean;
}
export class CadClusteringPreSolver {
/**
* Solves an assembly graph into compound bodies and 1-DOF joints
*/
public static solve(input: PreSolverInput, options?: PreSolverOptions): RobotAssemblySpec {
const { name, parts } = input;
const links = input.links || (input as any).connections || [];
const disablePreSolver = options?.disablePreSolver ?? false;
const partMap = new Map<string, PlacedPart>();
for (const part of parts) {
partMap.set(part.id, part);
}
// Build adjacency list for rigid connections
const adjacency = new Map<string, Set<string>>();
for (const part of parts) {
adjacency.set(part.id, new Set<string>());
}
const activeLinks: ConnectionLink[] = [];
// If pre-solver is enabled, use topological connection links
if (!disablePreSolver) {
for (const link of links) {
if (link.connectionType === 'RIGID_PIN' || link.connectionType === 'RIGID_FRAME') {
adjacency.get(link.fromPartId)?.add(link.toPartId);
adjacency.get(link.toPartId)?.add(link.fromPartId);
} else if (link.connectionType === 'REVOLUTE_AXLE' || link.connectionType === 'FREE_ROTATION') {
activeLinks.push(link);
}
}
}
// Link parts belonging to the same submodel instance (rigid subassembly)
const bySubmodel = new Map<string, string[]>();
for (const part of parts) {
const sub = part.submodelInstance || part.submodel || (disablePreSolver ? '__top_level_root__' : undefined);
if (sub) {
if (!bySubmodel.has(sub)) bySubmodel.set(sub, []);
bySubmodel.get(sub)!.push(part.id);
}
}
for (const ids of bySubmodel.values()) {
for (let k = 0; k < ids.length - 1; k++) {
adjacency.get(ids[k])?.add(ids[k + 1]);
adjacency.get(ids[k + 1])?.add(ids[k]);
}
}
// Connected components search for rigid clusters
const visited = new Set<string>();
const clusters: ClusteredCompoundBody[] = [];
const partToClusterId = new Map<string, string>();
let clusterIndex = 0;
for (const part of parts) {
if (visited.has(part.id)) continue;
// Group all reachable rigidly connected parts
const queue: string[] = [part.id];
visited.add(part.id);
const componentPartIds: string[] = [];
while (queue.length > 0) {
const currId = queue.shift()!;
componentPartIds.push(currId);
const neighbors = adjacency.get(currId);
if (neighbors) {
for (const neighborId of neighbors) {
if (!visited.has(neighborId)) {
visited.add(neighborId);
queue.push(neighborId);
}
}
}
}
// Check if this cluster contains the chassis core or motors
const hasCore = componentPartIds.some((id) => {
const p = partMap.get(id);
return p && (p.role === 'CHASSIS_CORE' || p.role === 'MOTOR_STATOR');
});
const isRootSub = disablePreSolver && componentPartIds.some((id) => {
const p = partMap.get(id);
const sub = p?.submodelInstance || p?.submodel;
return sub === 'root_inst0' || sub === '__top_level_root__' || sub === 'model.ldr';
});
const clusterId = (hasCore || isRootSub) ? 'chassis_root' : `cluster_${clusterIndex++}`;
for (const id of componentPartIds) {
partToClusterId.set(id, clusterId);
}
// Compute mass and simple bounding colliders for the cluster
let totalMassGrams = 0;
for (const id of componentPartIds) {
const p = partMap.get(id);
if (!p) continue;
const catalogEntry = TECHNIC_PART_CATALOG[p.partNumber];
const mass = catalogEntry ? catalogEntry.massGrams : 2.0;
totalMassGrams += mass;
}
const isRoot = clusterId === 'chassis_root';
const isChain = componentPartIds.some((id) => {
const p = partMap.get(id);
return p && (p.role === 'CHAIN_LINK' || isChainPart(p.partNumber, p.submodel));
});
const firstPart = partMap.get(componentPartIds[0]);
const subName = firstPart?.submodelInstance || firstPart?.submodel;
const cleanSubName = (subName && subName !== '__top_level_root__') ? subName : 'Base Frame / Root';
const clusterName = isRoot
? (disablePreSolver ? cleanSubName : 'Chassis Main Assembly')
: isChain
? 'Dynamic Chain Link'
: (disablePreSolver && subName)
? subName
: componentPartIds.some((id) => partMap.get(id)?.role === 'WHEEL_RIM')
? 'Drive Wheel'
: componentPartIds.some((id) => partMap.get(id)?.role === 'CASTER_SKID')
? 'Passive Caster / Skid'
: `Rigid Body ${clusterId}`;
// Build colliders based on cluster type
const colliders: ClusteredCompoundBody['colliders'] = [];
const massKg = Math.max(0.01, totalMassGrams / 1000);
// Compute bounding box of parts in cluster in meters
let minX = Infinity, maxX = -Infinity;
let minY = Infinity, maxY = -Infinity;
let minZ = Infinity, maxZ = -Infinity;
for (const id of componentPartIds) {
const p = partMap.get(id);
if (!p) continue;
const px = p.position[0] / 1000;
const py = p.position[1] / 1000;
const pz = p.position[2] / 1000;
if (px < minX) minX = px;
if (px > maxX) maxX = px;
if (py < minY) minY = py;
if (py > maxY) maxY = py;
if (pz < minZ) minZ = pz;
if (pz > maxZ) maxZ = pz;
}
const hasParts = minX !== Infinity;
const cx = hasParts ? (minX + maxX) / 2 : 0;
const cy = hasParts ? (minY + maxY) / 2 : 0;
const cz = hasParts ? (minZ + maxZ) / 2 : 0;
if (isRoot && hasCore) {
// 1. Compound box for main chassis frame (88mm wide frame, leaving clean clearance to wheels).
// Elevated with bottom at Y = 0.005 - 0.012 = -0.007m (28mm clearance above ground at Y = -0.035m, never drags).
colliders.push({
shape: 'box',
halfExtents: [0.044, 0.012, 0.050],
offset: [0, 0.005, -0.015],
rotation: [0, 0, 0, 1],
friction: 0.1,
restitution: 0.0,
});
// 2. Frictionless spherical rear caster skid (Part 49283).
// Radius 10mm with center at Y = -0.0245m: bottom touches at Y = -0.0345m (0.5mm clearance, wheels bear primary weight).
colliders.push({
shape: 'sphere',
radius: 0.010,
offset: [0, -0.0245, -0.065],
rotation: [0, 0, 0, 1],
friction: 0.0, // Frictionless glide for tank turns
restitution: 0.0,
});
} else if (clusterName === 'Drive Wheel') {
// Cylinder collider for drive wheel
colliders.push({
shape: 'cylinder',
radius: 0.028, // 56mm diameter = 28mm radius
halfHeight: 0.013, // 26mm width = 13mm half height
offset: [0, 0, 0],
rotation: [0, 0, 0.7071, 0.7071], // Oriented along X axis
friction: 0.9, // High traction rubber
restitution: 0.0,
});
} else if (clusterName === 'Passive Caster / Skid') {
// Low-friction sphere collider for caster ball
colliders.push({
shape: 'sphere',
radius: 0.012,
offset: [0, 0, 0],
rotation: [0, 0, 0, 1],
friction: 0.02, // Low friction glide
restitution: 0.0,
});
} else {
// Group parts by submodel instance to create decomposed, tight compound colliders
const subGroups = new Map<string, PlacedPart[]>();
for (const id of componentPartIds) {
const p = partMap.get(id);
if (!p) continue;
const key = p.submodelInstance || p.submodel || 'main';
if (!subGroups.has(key)) subGroups.set(key, []);
subGroups.get(key)!.push(p);
}
if (subGroups.size > 1) {
for (const pList of subGroups.values()) {
let sMinX = Infinity, sMaxX = -Infinity;
let sMinY = Infinity, sMaxY = -Infinity;
let sMinZ = Infinity, sMaxZ = -Infinity;
for (const p of pList) {
const px = p.position[0] / 1000;
const py = p.position[1] / 1000;
const pz = p.position[2] / 1000;
if (px < sMinX) sMinX = px;
if (px > sMaxX) sMaxX = px;
if (py < sMinY) sMinY = py;
if (py > sMaxY) sMaxY = py;
if (pz < sMinZ) sMinZ = pz;
if (pz > sMaxZ) sMaxZ = pz;
}
// Standard 4mm margin (half-stud pitch) so collider covers physical LEGO brick walls
const sHx = Math.max(0.004, (sMaxX - sMinX) / 2 + 0.004);
const sHy = Math.max(0.004, (sMaxY - sMinY) / 2 + 0.004);
const sHz = Math.max(0.004, (sMaxZ - sMinZ) / 2 + 0.004);
const sCx = (sMinX + sMaxX) / 2;
const sCy = (sMinY + sMaxY) / 2;
const sCz = (sMinZ + sMaxZ) / 2;
colliders.push({
shape: 'box',
halfExtents: [sHx, sHy, sHz],
offset: [sCx, sCy, sCz],
rotation: [0, 0, 0, 1],
friction: isRoot ? 0.8 : 0.5,
restitution: 0.05,
});
}
} else {
// Single tight box collider with standard 4mm margin
const tightHx = Math.max(0.004, (maxX - minX) / 2 + 0.004);
const tightHy = Math.max(0.004, (maxY - minY) / 2 + 0.004);
const tightHz = Math.max(0.004, (maxZ - minZ) / 2 + 0.004);
colliders.push({
shape: 'box',
halfExtents: [tightHx, tightHy, tightHz],
offset: [cx, cy, cz],
rotation: [0, 0, 0, 1],
friction: isRoot ? 0.8 : 0.5,
restitution: 0.05,
});
}
}
const clusterParts: PlacedPart[] = componentPartIds
.map((id) => partMap.get(id))
.filter((p): p is PlacedPart => p !== undefined);
clusters.push({
clusterId,
name: clusterName,
isRootChassis: isRoot,
isFixed: isRoot,
partIds: componentPartIds,
parts: clusterParts,
totalMassKg: massKg,
colliders,
});
}
// Ensure root chassis exists (pick the ground-resting, joint-bearing base or largest rigid assembly as root chassis/base)
if (!clusters.some((c) => c.isRootChassis)) {
if (clusters.length > 0) {
const nonChainClusters = clusters.filter(
(c) => !c.parts?.some((p) => p.role === 'CHAIN_LINK' || isChainPart(p.partNumber, p.submodel))
);
const candidates = nonChainClusters.length > 0 ? nonChainClusters : clusters;
// Ground-level calculation: lowest bottom-Y among parts
let globalMinY = Infinity;
for (const p of parts) {
if (p.position[1] < globalMinY) globalMinY = p.position[1];
}
// Count incident non-rigid links (joints) for each cluster candidate
const jointIncidentCount = new Map<string, number>();
for (const link of activeLinks) {
if (link.connectionType !== 'RIGID_PIN') {
const cA = partToClusterId.get(link.fromPartId);
const cB = partToClusterId.get(link.toPartId);
if (cA && cB && cA !== cB) {
jointIncidentCount.set(cA, (jointIncidentCount.get(cA) || 0) + 1);
jointIncidentCount.set(cB, (jointIncidentCount.get(cB) || 0) + 1);
}
}
}
// Candidate score: prefer ground-resting (minY within 12mm of globalMinY),
// prefer having active mechanism joints, then largest part count
const scoredCandidates = candidates.map((c) => {
let minY = Infinity;
for (const pid of c.partIds) {
const p = partMap.get(pid);
if (p && p.position[1] < minY) minY = p.position[1];
}
const isGround = minY <= globalMinY + 12.0;
const jCount = jointIncidentCount.get(c.clusterId) || 0;
return { cluster: c, isGround, jCount, partsCount: c.partIds.length };
});
const hasAnyJoints = scoredCandidates.some((c) => c.jCount > 0);
scoredCandidates.sort((a, b) => {
if (hasAnyJoints) {
const aHasJ = a.jCount > 0 ? 1 : 0;
const bHasJ = b.jCount > 0 ? 1 : 0;
if (aHasJ !== bHasJ) return bHasJ - aHasJ;
if (a.jCount !== b.jCount) return b.jCount - a.jCount;
if (a.isGround !== b.isGround) return a.isGround ? -1 : 1;
return b.partsCount - a.partsCount;
}
// Default when no joints exist: pick largest cluster by part count
return b.partsCount - a.partsCount;
});
const chosen = scoredCandidates[0].cluster;
const oldId = chosen.clusterId;
chosen.isRootChassis = true;
chosen.isFixed = true;
chosen.clusterId = 'chassis_root';
for (const [partId, cid] of partToClusterId.entries()) {
if (cid === oldId) {
partToClusterId.set(partId, 'chassis_root');
}
}
}
}
// Extract 1-DOF and spherical joints from active links
const joints: ExtractedJoint[] = [];
let jointIndex = 0;
for (const link of activeLinks) {
const parentCluster = partToClusterId.get(link.fromPartId) || 'chassis_root';
const childCluster = partToClusterId.get(link.toPartId) || `cluster_${jointIndex}`;
if (parentCluster === childCluster) continue;
const fromPart = partMap.get(link.fromPartId);
const toPart = partMap.get(link.toPartId);
const isMotorPort = (fromPart?.meta?.port || toPart?.meta?.port) as any;
const isFlexible = link.connectionType === 'FREE_ROTATION';
joints.push({
jointId: `joint_${jointIndex++}`,
name: isFlexible ? 'Flexible Chain Joint' : `Revolute Joint ${link.jointAxis ? 'Wheel' : 'Arm'}`,
type: isFlexible ? 'SPHERICAL' : 'REVOLUTE',
parentClusterId: parentCluster,
childClusterId: childCluster,
anchorParent: (link.anchor || [0, 0, 0]) as [number, number, number],
anchorChild: (link.anchor || [0, 0, 0]) as [number, number, number],
axis: (link.jointAxis || [1, 0, 0]) as [number, number, number],
motorPort: isMotorPort,
maxTorqueNm: 0.25, // SPIKE large motor rated torque
maxVelocityDegPerSec: 1000,
});
}
// Merge redundant collinear joints between the same pair of clusters (e.g. co-axial hinge pins)
const mergedJoints: ExtractedJoint[] = [];
const jointClusterPairs = new Map<string, ExtractedJoint[]>();
for (const j of joints) {
const pairKey = [j.parentClusterId, j.childClusterId].sort().join(':::') + `:::${j.type}:::${j.axis.join(',')}`;
if (!jointClusterPairs.has(pairKey)) jointClusterPairs.set(pairKey, []);
jointClusterPairs.get(pairKey)!.push(j);
}
for (const jList of jointClusterPairs.values()) {
if (jList.length === 1) {
mergedJoints.push(jList[0]);
} else {
const rep = jList[0];
const avgParent: [number, number, number] = [0, 0, 0];
const avgChild: [number, number, number] = [0, 0, 0];
for (const j of jList) {
avgParent[0] += j.anchorParent[0] / jList.length;
avgParent[1] += j.anchorParent[1] / jList.length;
avgParent[2] += j.anchorParent[2] / jList.length;
avgChild[0] += j.anchorChild[0] / jList.length;
avgChild[1] += j.anchorChild[1] / jList.length;
avgChild[2] += j.anchorChild[2] / jList.length;
}
mergedJoints.push({
...rep,
anchorParent: avgParent,
anchorChild: avgChild,
});
}
}
// Determine cluster fixed state:
// - Root chassis is fixed to field mat by default (base dual lock anchor).
// - All non-root clusters (articulated mechanisms, child of joints, sliding carts, payloads, loose pieces)
// remain DYNAMIC so they simulate physically, collide, and interact with the robot!
for (const cluster of clusters) {
const isChain =
cluster.name.toLowerCase().includes('chain') ||
cluster.parts?.some((p) => p.role === 'CHAIN_LINK' || isChainPart(p.partNumber, p.submodel));
if (cluster.isRootChassis) {
cluster.isFixed = true;
} else if (isChain) {
cluster.isFixed = false;
if (!cluster.name.toLowerCase().includes('chain')) {
cluster.name = 'Dynamic Chain Link';
}
} else {
// Non-root clusters (revolute arms, sliding carts, loose elements) are DYNAMIC
cluster.isFixed = false;
}
}
// Extract sensors from placed parts
const sensors: RobotAssemblySpec['sensors'] = [];
for (const part of parts) {
if (part.role === 'SENSOR_COLOR') {
const port = (part.meta?.port || 'C') as any;
sensors.push({
id: `color_sensor_${port}`,
type: 'COLOR',
port,
relativePosition: [
part.position[0] / 1000,
part.position[1] / 1000,
part.position[2] / 1000,
],
relativeOrientation: part.rotation,
});
} else if (part.role === 'SENSOR_DISTANCE') {
const port = (part.meta?.port || 'E') as any;
sensors.push({
id: `dist_sensor_${port}`,
type: 'DISTANCE',
port,
relativePosition: [
part.position[0] / 1000,
part.position[1] / 1000,
part.position[2] / 1000,
],
relativeOrientation: part.rotation,
});
}
}
// Always include Hub IMU gyro sensor
sensors.push({
id: 'hub_motion_gyro',
type: 'GYRO',
relativePosition: [0, 0.04, 0],
relativeOrientation: [0, 0, 0, 1],
});
return {
name,
clusters,
joints: mergedJoints,
sensors,
isPreSolverDisabled: disablePreSolver,
};
}
}
|