File size: 12,603 Bytes
6de1b61 | 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 | import * as THREE from "three";
import { CSG } from "three-csg-ts";
class ScadParser {
constructor(source) {
this.tokens = tokenize(source);
this.index = 0;
}
parseProgram(stopAtBrace = false) {
const nodes = [];
while (!this.done()) {
if (stopAtBrace && this.peek()?.value === "}") break;
if (this.peek()?.value === ";") {
this.index += 1;
continue;
}
nodes.push(this.parseStatement());
}
return nodes;
}
parseStatement() {
const node = this.parseCall();
const next = this.peek();
if (next?.value === "{") {
this.consume("{");
node.children = this.parseProgram(true);
this.consume("}");
} else if (isChildTakingCall(node.name) && next?.type === "identifier") {
node.children = [this.parseStatement()];
}
if (this.peek()?.value === ";") this.index += 1;
return node;
}
parseCall() {
const name = this.consumeType("identifier").value;
this.consume("(");
const args = [];
const named = {};
while (!this.done() && this.peek()?.value !== ")") {
if (this.peek()?.type === "identifier" && this.peek(1)?.value === "=") {
const key = this.consumeType("identifier").value;
this.consume("=");
named[key] = this.parseValue();
} else if (this.peek()?.value === "$" && this.peek(1)?.type === "identifier" && this.peek(2)?.value === "=") {
this.consume("$");
const key = `$${this.consumeType("identifier").value}`;
this.consume("=");
named[key] = this.parseValue();
} else {
args.push(this.parseValue());
}
if (this.peek()?.value === ",") this.index += 1;
}
this.consume(")");
return { name, args, named, children: [] };
}
parseValue() {
const token = this.peek();
if (!token) throw new Error("Unexpected end of SCAD input.");
if (token.value === "[") {
this.consume("[");
const values = [];
while (!this.done() && this.peek()?.value !== "]") {
values.push(this.parseValue());
if (this.peek()?.value === ",") this.index += 1;
}
this.consume("]");
return values;
}
if (token.type === "number") {
this.index += 1;
return Number(token.value);
}
if (token.type === "identifier") {
this.index += 1;
if (token.value === "true") return true;
if (token.value === "false") return false;
return token.value;
}
throw new Error(`Unexpected token "${token.value}" while parsing value.`);
}
consume(value) {
const token = this.peek();
if (token?.value !== value) throw new Error(`Expected "${value}" but found "${token?.value || "end of input"}".`);
this.index += 1;
return token;
}
consumeType(type) {
const token = this.peek();
if (token?.type !== type) throw new Error(`Expected ${type} but found "${token?.value || "end of input"}".`);
this.index += 1;
return token;
}
peek(offset = 0) {
return this.tokens[this.index + offset];
}
done() {
return this.index >= this.tokens.length;
}
}
function tokenize(source) {
const stripped = String(source)
.replace(/\/\*[\s\S]*?\*\//g, "")
.replace(/\/\/.*$/gm, "");
const tokens = [];
const pattern = /\s*(-?\d+(?:\.\d+)?|[A-Za-z_][A-Za-z0-9_]*|\$|[()[\]{},;=])/gy;
let index = 0;
while (index < stripped.length) {
pattern.lastIndex = index;
const match = pattern.exec(stripped);
if (!match) {
if (/\s/.test(stripped[index])) {
index += 1;
continue;
}
throw new Error(`Unsupported SCAD syntax near "${stripped.slice(index, index + 24)}".`);
}
const value = match[1];
tokens.push({ value, type: /^-?\d/.test(value) ? "number" : /^[A-Za-z_]/.test(value) ? "identifier" : "symbol" });
index = pattern.lastIndex;
}
return tokens;
}
function isChildTakingCall(name) {
return ["translate", "rotate", "scale", "color", "union", "difference", "intersection"].includes(name);
}
function vector(value, fallback, length = 3) {
const source = Array.isArray(value) ? value : [value];
return Array.from({ length }, (_, index) => Number(source[index] ?? fallback[index] ?? 0));
}
function firstNumber(node, keys, fallback) {
for (const key of keys) {
if (Number.isFinite(Number(node.named[key]))) return Number(node.named[key]);
}
for (const arg of node.args) {
if (Number.isFinite(Number(arg))) return Number(arg);
}
return fallback;
}
function nodeChildren(node) {
if (!node.children?.length) throw new Error(`${node.name} requires child geometry.`);
return node.children;
}
function prepareMesh(mesh) {
mesh.updateMatrixWorld(true);
mesh.updateMatrix();
return mesh;
}
function evaluateBoolean(children, operation, material) {
if (operation === "union" && children.length > 24) {
throw new Error(`Renderer safety limit: union has ${children.length} children. Keep generated SCAD to 24 or fewer union children so the browser CSG step cannot hang.`);
}
let result = prepareMesh(evaluateNode(children[0], material));
for (const child of children.slice(1)) {
const next = prepareMesh(evaluateNode(child, material));
if (operation === "union") result = CSG.union(result, next);
if (operation === "difference") result = CSG.subtract(result, next);
if (operation === "intersection") result = CSG.intersect(result, next);
result.material = material;
}
result.geometry.computeVertexNormals();
return result;
}
function evaluateNode(node, material) {
if (node.name === "cube") {
const size = vector(node.named.size ?? node.args[0] ?? 1, [1, 1, 1]);
const mesh = new THREE.Mesh(new THREE.BoxGeometry(Math.max(size[0], 0.01), Math.max(size[1], 0.01), Math.max(size[2], 0.01)), material);
if (node.named.center !== true) mesh.position.set(size[0] / 2, size[1] / 2, size[2] / 2);
return mesh;
}
if (node.name === "sphere") {
const radius = Math.max(firstNumber(node, ["r"], Number(node.named.d || 2) / 2 || 1), 0.01);
const segments = Math.min(Math.max(Number(node.named.$fn || 16), 8), 24);
return new THREE.Mesh(new THREE.SphereGeometry(radius, segments, 12), material);
}
if (node.name === "cylinder") {
const height = Math.max(Number(node.named.h ?? node.args[0] ?? 1), 0.01);
const radius = firstNumber(node, ["r"], Number(node.named.d || 2) / 2 || 1);
const r1Raw = node.named.r1 ?? (node.named.d1 === undefined ? undefined : Number(node.named.d1) / 2) ?? radius;
const r2Raw = node.named.r2 ?? (node.named.d2 === undefined ? undefined : Number(node.named.d2) / 2) ?? radius;
const r1 = Math.max(Number(r1Raw), 0.01);
const r2 = Math.max(Number(r2Raw), 0.01);
const segments = Math.min(Math.max(Number(node.named.$fn || 16), 8), 24);
const geometry = new THREE.CylinderGeometry(r2, r1, height, segments);
geometry.rotateX(Math.PI / 2);
const mesh = new THREE.Mesh(geometry, material);
if (node.named.center !== true) mesh.position.z = height / 2;
return mesh;
}
if (node.name === "union") {
return evaluateBoolean(nodeChildren(node), "union", material);
}
if (node.name === "difference") {
return evaluateBoolean(nodeChildren(node), "difference", material);
}
if (node.name === "intersection") {
return evaluateBoolean(nodeChildren(node), "intersection", material);
}
if (node.name === "translate") {
const mesh = evaluateNode(nodeChildren(node)[0], material);
const [x, y, z] = vector(node.args[0] ?? node.named.v, [0, 0, 0]);
mesh.position.add(new THREE.Vector3(x, y, z));
return mesh;
}
if (node.name === "rotate") {
const mesh = evaluateNode(nodeChildren(node)[0], material);
const [x, y, z] = vector(node.args[0] ?? node.named.a, [0, 0, 0]);
mesh.rotation.x += THREE.MathUtils.degToRad(x);
mesh.rotation.y += THREE.MathUtils.degToRad(y);
mesh.rotation.z += THREE.MathUtils.degToRad(z);
return mesh;
}
if (node.name === "scale") {
const mesh = evaluateNode(nodeChildren(node)[0], material);
const [x, y, z] = vector(node.args[0] ?? node.named.v, [1, 1, 1]);
mesh.scale.multiply(new THREE.Vector3(x || 1, y || 1, z || 1));
return mesh;
}
if (node.name === "color") {
return evaluateNode(nodeChildren(node)[0], material);
}
throw new Error(`Unsupported OpenSCAD call "${node.name}". Supported subset: cube, sphere, cylinder, translate, rotate, scale, union, difference, intersection.`);
}
export function renderScadToGroup(source, material) {
const parser = new ScadParser(source);
const nodes = parser.parseProgram();
if (!nodes.length) throw new Error("SCAD input did not contain any renderable geometry.");
const complexity = countRenderableNodes(nodes);
if (complexity.primitives > 24) {
throw new Error(`Renderer safety limit: ${complexity.primitives} primitives. Keep generated SCAD to 24 or fewer primitives.`);
}
const mesh = nodes.length === 1 ? evaluateNode(nodes[0], material) : evaluateBoolean(nodes, "union", material);
mesh.geometry.computeBoundingBox();
mesh.geometry.computeBoundingSphere();
const topology = analyzeMeshTopology(mesh.geometry);
const box = mesh.geometry.boundingBox;
const dimensions = new THREE.Vector3();
box.getSize(dimensions);
const group = new THREE.Group();
group.add(mesh);
return {
group,
stats: {
root_nodes: nodes.length,
triangles: mesh.geometry.index ? mesh.geometry.index.count / 3 : mesh.geometry.attributes.position.count / 3,
bounding_box: {
min: [box.min.x, box.min.y, box.min.z],
max: [box.max.x, box.max.y, box.max.z]
},
dimensions: {
x: dimensions.x,
y: dimensions.y,
z: dimensions.z
},
connected_components: topology.connected_components,
floating_parts: Math.max(0, topology.connected_components - 1),
boundary_edges: topology.boundary_edges,
non_manifold_edges: topology.non_manifold_edges,
watertight: topology.boundary_edges === 0 && topology.non_manifold_edges === 0,
supported_subset: "cube/sphere/cylinder + translate/rotate/scale + union/difference/intersection"
}
};
}
function countRenderableNodes(nodes) {
let total = 0;
let primitives = 0;
const stack = [...nodes];
while (stack.length) {
const node = stack.pop();
total += 1;
if (["cube", "sphere", "cylinder"].includes(node.name)) primitives += 1;
for (const child of node.children || []) stack.push(child);
}
return { total, primitives };
}
function analyzeMeshTopology(geometry) {
const position = geometry.attributes.position;
const index = geometry.index;
const faces = [];
const vertexKeyToId = new Map();
function vertexId(rawIndex) {
const x = position.getX(rawIndex).toFixed(5);
const y = position.getY(rawIndex).toFixed(5);
const z = position.getZ(rawIndex).toFixed(5);
const key = `${x},${y},${z}`;
if (!vertexKeyToId.has(key)) vertexKeyToId.set(key, vertexKeyToId.size);
return vertexKeyToId.get(key);
}
const triCount = index ? index.count / 3 : position.count / 3;
for (let tri = 0; tri < triCount; tri += 1) {
const a = index ? index.getX(tri * 3) : tri * 3;
const b = index ? index.getX(tri * 3 + 1) : tri * 3 + 1;
const c = index ? index.getX(tri * 3 + 2) : tri * 3 + 2;
faces.push([vertexId(a), vertexId(b), vertexId(c)]);
}
const edgeCounts = new Map();
const adjacency = Array.from({ length: vertexKeyToId.size }, () => new Set());
for (const [a, b, c] of faces) {
for (const [u, v] of [[a, b], [b, c], [c, a]]) {
const key = u < v ? `${u}:${v}` : `${v}:${u}`;
edgeCounts.set(key, (edgeCounts.get(key) || 0) + 1);
adjacency[u].add(v);
adjacency[v].add(u);
}
}
let boundaryEdges = 0;
let nonManifoldEdges = 0;
for (const count of edgeCounts.values()) {
if (count === 1) boundaryEdges += 1;
if (count > 2) nonManifoldEdges += 1;
}
const visited = new Set();
let connectedComponents = 0;
for (let start = 0; start < adjacency.length; start += 1) {
if (visited.has(start)) continue;
connectedComponents += 1;
const stack = [start];
visited.add(start);
while (stack.length) {
const current = stack.pop();
for (const next of adjacency[current]) {
if (!visited.has(next)) {
visited.add(next);
stack.push(next);
}
}
}
}
return {
connected_components: connectedComponents,
boundary_edges: boundaryEdges,
non_manifold_edges: nonManifoldEdges
};
}
|