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 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 | 165x 165x 165x 165x 165x 3x 3x 3x 6x 3x 3x 3x 5x 3x 3x 9x 9x 1x 8x 8x 7x 2x 2x 11x 11x 1x 10x 10x 9x 2x 2x 4x 4x 4x 8x 4x 4x 4x 4x 8x 4x 3027x 3027x 3025x 1x 1x 1x 1x 1x 3024x 1x 3023x 3023x 3023x 3024x 3x 3x 3021x 3024x 3024x 3024x 2x 2x 6x 6x 6x 1x 1x 5x 5x 6x 6x 6x 11x 11x 11x 2x 2x 9x 2x 7x 7x 11x 11x 6x 6x 6x 52x 52x 52x 83x 83x 3x 83x 3x 2x 3x 3x 83x 52x 15x 52x 52x 15x 1x 1x 1x 1x 1x 14x 37x 37x 37x 37x 37x 27x 27x 27x 4x 23x 27x 5x 22x 27x 17x 17x 2x 17x 26x 8x 26x 26x 18x 18x 18x 18x 26x 7x 7x 28x 28x 28x 28x 7x 8x 6x 2x 7x 3x 4x 5x 5x 5x 5x 5x 4x 4x 21x 28x 9x 9x 9x 14x 9x 10x 10x 9x 9x 13x 13x 13x 13x 9x 18x 10x 11x 3x 8x 8x 8x 11x 11x 11x 20x 20x 11x 45x 45x 45x 45x 45x 45x 45x 80x 80x 80x 80x 80x 43x 474x 80x 80x 45x 45x 45x 45x 45x 8x 8x 45x 45x 45x 4x 4x 4x 4x 41x 41x 41x 41x 41x 41x 41x 41x 41x 45x 3x 45x 30x 30x 30x 30x 66x 30x 30x 11x 11x 11x 11x 11x 11x 11x 1x 11x 30x 30x 30x 30x 30x 66x 198x 198x 198x 198x 198x 198x 66x 3035x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3027x 3035x 3035x 34x 34x 34x 3035x 1x 3035x 3035x 3035x 3035x 3035x 3035x 3035x 3035x 3035x 3035x 3035x 17x 17x 17x 17x 11x 3x 8x 8x 8x 8x 4x 4x 4x 4x 4x 4x 4x 4x 4x 11x 46x 11x 11x 11x 11x 11x 17x 8x 8x 174x 85x 8x 8x 17x 2x 2x 17x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 48x 48x 12x 12x 1x 1x 1x 17x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 24x 24x 6x 6x 1x 1x 1x 17x 88x 88x 88x 88x 88x 212x 212x 212x 308x 308x 308x 308x 308x 212x 212x 212x 9x 9x 36x 36x 36x 36x 88x 28x 19x 19x 19x 19x 19x 4x 5x 4x 65x 184x 65x 88x 88x 248x 248x 248x 688x 88x 69x 69x 69x 69x 69x 69x 69x 69x 13x 12x 12x 9x 9x 9x 9x 9x 9x 9x 9x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 3x 1x 1x 1x 1x 1x 4x 1x 1x 1x 1x 25x 25x 6645x 6645x 3167x 3167x 3167x 80x 3087x 9x 9x 9x 8x 9x 9x 3087x 3087x 3087x 58x 58x 58x 17x 41x 41x 41x 41x 84x 39x 39x 39x 39x 39x 39x 39x 39x 39x 84x 84x 84x 84x 84x 7x 84x 84x 84x 84x 84x 84x 84x 47x 1133x 47x 47x 58x 41x 41x 41x 41x 41x 1163x 58x 47x 47x 47x 47x 58x 58x 55x 55x 55x 55x 55x 55x 55x 1133x 1133x 1133x 55x 55x 55x 47x |
import { Context } from "./context";
import * as Inputs from "./inputs/inputs";
import { DrawHelperCore, MeshData } from "@bitbybit-dev/core";
import { JSCADText } from "@bitbybit-dev/jscad-worker";
import { Vector } from "@bitbybit-dev/base";
import { JSCADWorkerManager } from "@bitbybit-dev/jscad-worker";
import { ManifoldWorkerManager } from "@bitbybit-dev/manifold-worker";
import { OCCTWorkerManager } from "@bitbybit-dev/occt-worker";
import * as THREEJS from "three";
import { CACHE_CONFIG, DEFAULT_COLORS, MATERIAL_DEFAULTS } from "./constants";
export class DrawHelper extends DrawHelperCore {
// Map-based material cache for better performance (MeshPhysicalMaterial for lit surfaces)
private readonly materialCache = new Map<string, THREEJS.MeshPhysicalMaterial>();
// Separate cache for unlit materials (MeshBasicMaterial for points/lines)
private readonly unlitMaterialCache = new Map<string, THREEJS.MeshBasicMaterial>();
// Entity ID generation
private entityIdCounter = 0;
private readonly instanceId = `three-${Date.now()}`;
constructor(
private readonly context: Context,
private readonly solidText: JSCADText,
public readonly vector: Vector,
private readonly jscadWorkerManager: JSCADWorkerManager,
private readonly manifoldWorkerManager: ManifoldWorkerManager,
private readonly occWorkerManager: OCCTWorkerManager
) {
super(vector);
}
/**
* Check if DrawHelper has been disposed
* @returns True if disposed, false otherwise
*/
public isDisposed(): boolean {
return this.materialCache.size === 0 && this.unlitMaterialCache.size === 0;
}
/**
* Cleanup method to dispose of cached materials and prevent memory leaks
* Should be called when the DrawHelper instance is no longer needed
*/
public dispose(): void {
// Dispose cached PBR materials
this.materialCache.forEach((material, key) => {
try {
if (material.dispose) {
material.dispose();
}
} catch (error) {
console.warn(`Error disposing material ${key}:`, error);
}
});
this.materialCache.clear();
// Dispose cached unlit materials (MeshBasicMaterial for points)
this.unlitMaterialCache.forEach((material, key) => {
try {
if (material.dispose) {
material.dispose();
}
} catch (error) {
console.warn(`Error disposing unlit material ${key}:`, error);
}
});
this.unlitMaterialCache.clear();
// Reset counters
this.entityIdCounter = 0;
console.log("DrawHelper disposed successfully");
}
async drawManifoldsOrCrossSections(inputs: Inputs.Manifold.DrawManifoldsOrCrossSectionsDto<Inputs.Manifold.ManifoldPointer | Inputs.Manifold.CrossSectionPointer, THREEJS.MeshPhysicalMaterial>): Promise<THREEJS.Group> {
try {
const safeWorkerOptions = this.getSafeWorkerOptions(inputs);
const decomposedMesh: Inputs.Manifold.DecomposedManifoldMeshDto[] = await this.manifoldWorkerManager.genericCallToWorkerPromise("decomposeManifoldsOrCrossSections", safeWorkerOptions);
const meshes = decomposedMesh.map(dec => this.handleDecomposedManifold(dec, inputs)).filter(s => s !== undefined);
const manifoldMeshContainer = new THREEJS.Group();
manifoldMeshContainer.name = this.generateEntityId("manifoldMeshContainer");
meshes.forEach(mesh => {
mesh.parent = manifoldMeshContainer;
});
this.context.scene.add(manifoldMeshContainer);
return manifoldMeshContainer;
} catch (error) {
console.error("Error drawing manifolds or cross sections:", error);
throw new Error(`Failed to draw manifolds or cross sections: ${error instanceof Error ? error.message : String(error)}`);
}
}
async drawManifoldOrCrossSection(inputs: Inputs.Manifold.DrawManifoldOrCrossSectionDto<Inputs.Manifold.ManifoldPointer | Inputs.Manifold.CrossSectionPointer, THREEJS.MeshPhysicalMaterial>): Promise<THREEJS.Group> {
try {
if (!inputs.manifoldOrCrossSection) {
throw new Error("Manifold or cross section parameter is required");
}
const safeWorkerOptions = this.getSafeWorkerOptions(inputs);
const decomposedMesh: Inputs.Manifold.DecomposedManifoldMeshDto = await this.manifoldWorkerManager.genericCallToWorkerPromise("decomposeManifoldOrCrossSection", safeWorkerOptions);
return this.handleDecomposedManifold(decomposedMesh, inputs);
} catch (error) {
console.error("Error drawing manifold or cross section:", error);
throw new Error(`Failed to draw manifold or cross section: ${error instanceof Error ? error.message : String(error)}`);
}
}
async drawShape(inputs: Inputs.OCCT.DrawShapeDto<Inputs.OCCT.TopoDSShapePointer>): Promise<THREEJS.Group> {
try {
if (!inputs.shape) {
throw new Error("Shape parameter is required");
}
const safeWorkerOptions = this.getSafeWorkerOptions(inputs);
const decomposedMesh: Inputs.OCCT.DecomposedMeshDto = await this.occWorkerManager.genericCallToWorkerPromise("shapeToMesh", safeWorkerOptions);
return this.handleDecomposedMesh(inputs, decomposedMesh, inputs);
} catch (error) {
console.error("Error drawing OCCT shape:", error);
throw new Error(`Failed to draw OCCT shape: ${error instanceof Error ? error.message : String(error)}`);
}
}
async drawShapes(inputs: Inputs.OCCT.DrawShapesDto<Inputs.OCCT.TopoDSShapePointer>): Promise<THREEJS.Group> {
try {
const safeWorkerOptions = this.getSafeWorkerOptions(inputs);
const meshes: Inputs.OCCT.DecomposedMeshDto[] = await this.occWorkerManager.genericCallToWorkerPromise("shapesToMeshes", safeWorkerOptions);
const meshesSolved = await Promise.all(meshes.map(async decomposedMesh => this.handleDecomposedMesh(inputs, decomposedMesh, inputs)));
const shapesMeshContainer = new THREEJS.Group();
shapesMeshContainer.name = this.generateEntityId("shapesMeshContainer");
this.context.scene.add(shapesMeshContainer);
meshesSolved.forEach(mesh => {
shapesMeshContainer.add(mesh);
});
return shapesMeshContainer;
} catch (error) {
console.error("Error drawing OCCT shapes:", error);
throw new Error(`Failed to draw OCCT shapes: ${error instanceof Error ? error.message : String(error)}`);
}
}
async drawSolidOrPolygonMesh(inputs: Inputs.JSCAD.DrawSolidMeshDto<THREEJS.Group>): Promise<THREEJS.Group> {
try {
const res: {
positions: number[],
normals: number[],
indices: number[],
transforms: [],
} = await this.jscadWorkerManager.genericCallToWorkerPromise("shapeToMesh", inputs);
// Validate worker response
if (!res || !res.positions || !res.indices || !res.transforms) {
console.warn("Corrupted worker response, returning empty mesh");
const emptyMesh = new THREEJS.Group();
emptyMesh.name = this.generateEntityId("jscadMesh");
this.context.scene.add(emptyMesh);
return emptyMesh;
}
let meshToUpdate;
if (inputs.jscadMesh && inputs.updatable) {
meshToUpdate = inputs.jscadMesh;
} else {
meshToUpdate = new THREEJS.Group();
meshToUpdate.name = this.generateEntityId("jscadMesh");
this.context.scene.add(meshToUpdate);
}
let colour;
if (inputs.mesh.color && inputs.mesh.color.length > 0) {
// if jscad geometry is colorized and color is baked on geometry it will be used over anything that set in the draw options
const c = inputs.mesh.color;
colour = "#" + new THREEJS.Color(c[0], c[1], c[2]).getHexString();
} else {
colour = Array.isArray(inputs.colours) ? inputs.colours[0] : inputs.colours;
}
const s = this.makeMesh({
updatable: inputs.updatable,
opacity: inputs.opacity,
hidden: inputs.hidden,
colour,
drawTwoSided: inputs.drawTwoSided,
backFaceColour: inputs.backFaceColour,
backFaceOpacity: inputs.backFaceOpacity
}, meshToUpdate, res);
inputs.jscadMesh = s;
return s;
} catch (error) {
console.error("Error drawing JSCAD solid or polygon mesh:", error);
throw new Error(`Failed to draw JSCAD mesh: ${error instanceof Error ? error.message : String(error)}`);
}
}
async drawSolidOrPolygonMeshes(inputs: Inputs.JSCAD.DrawSolidMeshesDto<THREEJS.Group>): Promise<THREEJS.Group> {
try {
const res: {
positions: number[],
normals: number[],
indices: number[],
transforms: [],
color?: number[]
}[] = await this.jscadWorkerManager.genericCallToWorkerPromise("shapesToMeshes", inputs);
let localOrigin: THREEJS.Group;
if (inputs.jscadMesh && inputs.updatable) {
localOrigin = inputs.jscadMesh;
localOrigin.clear();
} else {
localOrigin = new THREEJS.Group();
localOrigin.name = this.generateEntityId("jscadMeshes");
}
const colourIsArrayAndMatches = Array.isArray(inputs.colours) && inputs.colours.length === res.length;
const colorsAreArrays = Array.isArray(inputs.colours);
res.map((r, index) => {
const meshToUpdate = new THREEJS.Group();
meshToUpdate.name = this.generateEntityId("jscadMesh", localOrigin.name);
let colour;
if (r.color) {
const c = r.color;
colour = "#" + new THREEJS.Color(c[0], c[1], c[2]).getHexString();
} else if (colourIsArrayAndMatches) {
colour = inputs.colours[index];
} else Iif (colorsAreArrays) {
colour = inputs.colours[0];
} else {
colour = inputs.colours;
}
const m = this.makeMesh({
...inputs,
colour,
drawTwoSided: inputs.drawTwoSided,
backFaceColour: inputs.backFaceColour,
backFaceOpacity: inputs.backFaceOpacity
}, meshToUpdate, r);
localOrigin.add(m);
});
this.context.scene.add(localOrigin);
inputs.jscadMesh = localOrigin;
return localOrigin;
} catch (error) {
console.error("Error drawing JSCAD solid or polygon meshes:", error);
throw new Error(`Failed to draw JSCAD meshes: ${error instanceof Error ? error.message : String(error)}`);
}
}
drawPolylinesWithColours(inputs: Inputs.Polyline.DrawPolylinesDto<THREEJS.Group> & { colorMapStrategy?: Inputs.Base.colorMapStrategyEnum, arrowSize?: number, arrowAngle?: number }) {
let colours = inputs.colours;
const strategy = inputs.colorMapStrategy || Inputs.Base.colorMapStrategyEnum.lastColorRemainder;
const points = inputs.polylines.map((s, index) => {
const pts = s.points;
//handle jscad
if (s.isClosed) {
pts.push(pts[0]);
}
// sometimes polylines can have assigned colors in case of jscad for example. Such colour will overwrite the default provided colour for that polyline.
if (s.color) {
if (!Array.isArray(colours)) {
colours = [];
}
if (Array.isArray(s.color)) {
colours[index] = "#" + new THREEJS.Color(s.color[0], s.color[1], s.color[2]).getHexString();
} else E{
colours[index] = s.color;
}
}
return pts;
});
let lineSegments: THREEJS.LineSegments;
if (inputs.polylinesMesh && inputs.updatable) {
lineSegments = inputs.polylinesMesh.children[0] as THREEJS.LineSegments;
}
const polylines = this.drawPolylines(
lineSegments,
points,
inputs.updatable,
inputs.size,
inputs.opacity,
colours,
strategy,
inputs.arrowSize,
inputs.arrowAngle
);
if (inputs.polylinesMesh && inputs.updatable) {
if (inputs.polylinesMesh.children[0].name !== polylines.name) {
const group = new THREEJS.Group();
group.name = this.generateEntityId("polylines");
group.add(polylines);
this.context.scene.add(group);
return group;
} else {
return inputs.polylinesMesh;
}
} else {
const group = new THREEJS.Group();
group.name = this.generateEntityId("polylines");
group.add(polylines);
this.context.scene.add(group);
return group;
}
}
drawPoint(inputs: Inputs.Point.DrawPointDto<THREEJS.Group>): THREEJS.Group {
const vectorPoints = [inputs.point];
let colorsHex: string[] = [];
if (Array.isArray(inputs.colours)) {
colorsHex = inputs.colours;
} else {
colorsHex = [inputs.colours];
}
if (inputs.pointMesh && inputs.updatable) {
this.updatePointsInstances(inputs.pointMesh, vectorPoints);
} else {
inputs.pointMesh = this.createPointSpheresMesh(
this.generateEntityId("pointMesh"), vectorPoints, colorsHex, inputs.opacity, inputs.size, inputs.updatable
);
}
return inputs.pointMesh;
}
drawPolylineClose(inputs: Inputs.Polyline.DrawPolylineDto<THREEJS.Group> & { arrowSize?: number, arrowAngle?: number }): THREEJS.Group {
const points = inputs.polyline.points;
if (inputs.polyline.isClosed) {
points.push(points[0]);
}
return this.drawPolyline(
inputs.polylineMesh,
points,
inputs.updatable,
inputs.size,
inputs.opacity,
inputs.colours,
inputs.arrowSize,
inputs.arrowAngle
);
}
drawPolyline(mesh: THREEJS.Group,
pointsToDraw: Inputs.Base.Point3[],
updatable: boolean, size: number, opacity: number, colours: string | string[],
arrowSize = 0, arrowAngle = 30): THREEJS.Group {
let lineSegments: THREEJS.LineSegments;
if (mesh && mesh.children.length > 0) {
lineSegments = mesh.children[0] as THREEJS.LineSegments;
}
const polylines = this.drawPolylines(lineSegments, [pointsToDraw], updatable, size, opacity, colours,
Inputs.Base.colorMapStrategyEnum.lastColorRemainder, arrowSize, arrowAngle);
if (!mesh) {
mesh = new THREEJS.Group();
mesh.name = this.generateEntityId("polyline");
mesh.add(polylines);
this.context.scene.add(mesh);
}
return mesh;
}
drawCurve(inputs: Inputs.Verb.DrawCurveDto<THREEJS.Group>): THREEJS.Group {
const points = inputs.curve.tessellate();
return this.drawPolyline(
inputs.curveMesh,
points,
inputs.updatable,
inputs.size,
inputs.opacity,
inputs.colours
);
}
drawPoints(inputs: Inputs.Point.DrawPointsDto<THREEJS.Group> & { colorMapStrategy?: Inputs.Base.colorMapStrategyEnum }): THREEJS.Group {
const vectorPoints = inputs.points;
const strategy = inputs.colorMapStrategy || Inputs.Base.colorMapStrategyEnum.lastColorRemainder;
// Resolve colors for all points using the color mapping strategy
const coloursHex = this.resolveAllColors(inputs.colours, vectorPoints.length, strategy);
if (inputs.pointsMesh && inputs.updatable) {
// Calculate the total number of points currently in the mesh
const currentPointCount = inputs.pointsMesh.children.reduce((sum, child) => {
if (child instanceof THREEJS.InstancedMesh) {
return sum + child.count;
}
return sum + 1; // Regular mesh counts as 1 point
}, 0);
if (currentPointCount === vectorPoints.length) {
this.updatePointsInstances(inputs.pointsMesh, vectorPoints);
} else {
// Dispose old geometries before recreating
inputs.pointsMesh.children.forEach(child => {
Eif (child instanceof THREEJS.Mesh || child instanceof THREEJS.InstancedMesh) {
child.geometry?.dispose();
Eif (child.material) {
Iif (Array.isArray(child.material)) {
child.material.forEach(m => m.dispose());
} else {
child.material.dispose();
}
}
}
});
inputs.pointsMesh.remove();
inputs.pointsMesh = this.createPointSpheresMesh(
this.generateEntityId("pointsMesh"), vectorPoints, coloursHex, inputs.opacity, inputs.size, inputs.updatable
);
}
} else {
inputs.pointsMesh = this.createPointSpheresMesh(
this.generateEntityId("pointsMesh"), vectorPoints, coloursHex, inputs.opacity, inputs.size, inputs.updatable
);
}
return inputs.pointsMesh;
}
updatePointsInstances(group: THREEJS.Group, positions: Inputs.Base.Point3[]): void {
// The group contains InstancedMesh children, each handling multiple points of the same color
// We need to update the instance matrices based on the new positions
const children = group.children as THREEJS.InstancedMesh[];
// Build a map of original index to new position
const positionMap = new Map<number, THREEJS.Vector3>();
positions.forEach((pos, index) => {
positionMap.set(index, new THREEJS.Vector3(pos[0], pos[1], pos[2]));
});
// Each InstancedMesh has metadata with the original indices of points it contains
children.forEach((instancedMesh: THREEJS.InstancedMesh) => {
const indices = instancedMesh.userData.pointIndices as number[];
if (indices) {
const matrix = new THREEJS.Matrix4();
indices.forEach((originalIndex, instanceIndex) => {
const newPos = positionMap.get(originalIndex);
Eif (newPos) {
matrix.setPosition(newPos);
instancedMesh.setMatrixAt(instanceIndex, matrix);
}
});
instancedMesh.instanceMatrix.needsUpdate = true;
}
});
}
drawCurves(inputs: Inputs.Verb.DrawCurvesDto<THREEJS.Group>): THREEJS.Group {
const points = inputs.curves.map(s => ({ points: s.tessellate() }));
return this.drawPolylinesWithColours({ polylines: points, polylinesMesh: inputs.curvesMesh, ...inputs });
}
drawSurfacesMultiColour(inputs: Inputs.Verb.DrawSurfacesColoursDto<THREEJS.Group> & { colorMapStrategy?: Inputs.Base.colorMapStrategyEnum }): THREEJS.Group {
if (inputs.surfacesMesh && inputs.updatable) {
inputs.surfacesMesh.clear();
} else {
inputs.surfacesMesh = new THREEJS.Group();
inputs.surfacesMesh.name = this.generateEntityId("colouredSurfaces");
this.context.scene.add(inputs.surfacesMesh);
}
const strategy = inputs.colorMapStrategy || Inputs.Base.colorMapStrategyEnum.lastColorRemainder;
const resolvedColours = this.resolveAllColors(inputs.colours, inputs.surfaces.length, strategy);
inputs.surfaces.forEach((surface, index) => {
const srf = this.drawSurface({
surface,
colours: resolvedColours[index],
updatable: inputs.updatable,
opacity: inputs.opacity,
hidden: inputs.hidden,
drawTwoSided: inputs.drawTwoSided,
backFaceColour: inputs.backFaceColour,
backFaceOpacity: inputs.backFaceOpacity,
});
inputs.surfacesMesh.add(srf);
});
return inputs.surfacesMesh;
}
createOrUpdateSurfacesMesh(
meshDataConverted: { positions: number[]; indices: number[]; normals: number[]; uvs?: number[] }[],
group: THREEJS.Group, updatable: boolean, material: THREEJS.MeshPhysicalMaterial, addToScene: boolean, hidden: boolean
): THREEJS.Group {
const createMesh = () => {
// Merge all geometries into one
const totalPositions: number[] = [];
let totalNormals: number[] = [];
const totalIndices: number[] = [];
const totalUvs: number[] = [];
let indexOffset = 0;
meshDataConverted.forEach(meshItem => {
// Validate mesh data structure
Iif (!meshItem || !meshItem.positions || !meshItem.indices) {
console.warn("Skipping corrupted mesh item");
return;
}
totalPositions.push(...meshItem.positions);
Eif (meshItem.normals && meshItem.normals.length > 0) {
totalNormals.push(...meshItem.normals);
}
if (meshItem.uvs) {
totalUvs.push(...meshItem.uvs);
}
// Offset indices
const offsetIndices = meshItem.indices.map(i => i + indexOffset);
totalIndices.push(...offsetIndices);
indexOffset += meshItem.positions.length / 3;
});
// Compute normals if they're missing
Iif (totalNormals.length === 0 && totalPositions.length > 0) {
totalNormals = Array.from(this.computeNormals(totalPositions, totalIndices));
}
const geometry = new THREEJS.BufferGeometry();
geometry.setAttribute("position", new THREEJS.BufferAttribute(Float32Array.from(totalPositions), 3));
geometry.setAttribute("normal", new THREEJS.BufferAttribute(Float32Array.from(totalNormals), 3));
if (totalUvs.length > 0) {
geometry.setAttribute("uv", new THREEJS.BufferAttribute(Float32Array.from(totalUvs), 2));
geometry.setAttribute("uv2", new THREEJS.BufferAttribute(Float32Array.from(totalUvs), 2));
}
geometry.setIndex(new THREEJS.BufferAttribute(Uint32Array.from(totalIndices), 1));
return geometry;
};
if (group && updatable) {
group.clear();
const geometry = createMesh();
if (material) {
group.add(new THREEJS.Mesh(geometry, material));
} else E{
group.add(new THREEJS.Mesh(geometry));
}
} else {
let scene = null;
Eif (addToScene) {
scene = this.context.scene;
}
group = new THREEJS.Group();
group.name = this.generateEntityId("surface");
scene.add(group);
const geometry = createMesh();
if (material) {
group.add(new THREEJS.Mesh(geometry, material));
} else E{
group.add(new THREEJS.Mesh(geometry));
}
}
if (hidden) {
group.visible = false;
}
return group;
}
drawSurface(inputs: Inputs.Verb.DrawSurfaceDto<THREEJS.Group>): THREEJS.Group {
const meshData = inputs.surface.tessellate();
const meshDataConverted: MeshData = {
positions: [],
indices: [],
normals: [],
};
let countIndices = 0;
meshData.faces.forEach((faceIndices: number[]) => {
countIndices = this.parseFaces(faceIndices, meshData, meshDataConverted, countIndices);
});
const hex = Array.isArray(inputs.colours) ? inputs.colours[0] : inputs.colours;
const pbr = this.getOrCreateMaterial(hex, inputs.opacity, 0, () => {
const mat = new THREEJS.MeshPhysicalMaterial();
mat.name = this.generateEntityId("surfaceMaterial");
mat.color = new THREEJS.Color(hex);
mat.metalness = MATERIAL_DEFAULTS.METALNESS.SURFACE;
mat.roughness = MATERIAL_DEFAULTS.ROUGHNESS.SURFACE;
mat.opacity = inputs.opacity;
// Enable transparency for semi-transparent materials
if (inputs.opacity < 1) {
mat.transparent = true;
}
return mat;
});
const surfaceGroup = this.createOrUpdateSurfacesMesh(
[meshDataConverted],
inputs.surfaceMesh,
inputs.updatable,
pbr,
true,
inputs.hidden,
);
// Draw back faces with different color when two-sided rendering is enabled
Eif (inputs.drawTwoSided !== false) {
const backFaceMesh = this.createBackFaceMesh(
[meshDataConverted],
inputs.backFaceColour || DEFAULT_COLORS.BACK_FACE,
inputs.backFaceOpacity ?? inputs.opacity,
0
);
surfaceGroup.add(backFaceMesh);
}
return surfaceGroup;
}
private parseFaces(
faceIndices: number[],
meshData: { points: number[][]; normals: number[][]; },
meshDataConverted: { positions: number[]; indices: number[]; normals: number[]; },
countIndices: number): number {
faceIndices.forEach((x) => {
const vn = meshData.normals[x];
meshDataConverted.normals.push(vn[0], vn[1], vn[2]);
const pt = meshData.points[x];
meshDataConverted.positions.push(pt[0], pt[1], pt[2]);
meshDataConverted.indices.push(countIndices);
countIndices++;
});
return countIndices;
}
private makeMesh(inputs: { updatable: boolean, opacity: number, colour: string, hidden: boolean, drawTwoSided?: boolean, backFaceColour?: string, backFaceOpacity?: number }, meshToUpdate: THREEJS.Group, res: { positions: number[]; normals: number[]; indices: number[]; transforms: []; }) {
const pbr = this.getOrCreateMaterial(inputs.colour, inputs.opacity, 0, () => {
const mat = new THREEJS.MeshPhysicalMaterial();
mat.name = this.generateEntityId("jscadMaterial");
mat.color = new THREEJS.Color(inputs.colour);
mat.metalness = MATERIAL_DEFAULTS.METALNESS.JSCAD;
mat.roughness = MATERIAL_DEFAULTS.ROUGHNESS.JSCAD;
mat.alphaTest = inputs.opacity;
mat.polygonOffsetFactor = 0;
return mat;
});
this.createMesh(res.positions, res.indices, res.normals, meshToUpdate, res.transforms, inputs.updatable, pbr);
// Draw back faces with different color when two-sided rendering is enabled
// Default is true (when undefined), explicitly set to false for single-sided
if (inputs.drawTwoSided !== false) {
const meshData: MeshData[] = [{
positions: res.positions,
indices: res.indices,
normals: res.normals
}];
const backFaceMesh = this.createBackFaceMesh(
meshData,
inputs.backFaceColour || DEFAULT_COLORS.BACK_FACE,
inputs.backFaceOpacity ?? inputs.opacity,
0
);
meshToUpdate.add(backFaceMesh);
}
if (inputs.hidden) {
meshToUpdate.visible = false;
}
return meshToUpdate;
}
private createMesh(
positions: number[], indices: number[], normals: number[], jscadMesh: THREEJS.Group, transforms: number[], updatable: boolean, material: THREEJS.MeshPhysicalMaterial
): void {
// Validate worker response
Iif (!positions || !indices || !transforms) {
console.warn("Corrupted worker response, creating empty mesh");
return;
}
const geometry = new THREEJS.BufferGeometry();
geometry.setAttribute("position", new THREEJS.BufferAttribute(Float32Array.from(positions), 3));
geometry.setIndex(new THREEJS.BufferAttribute(Uint32Array.from(indices), 1));
geometry.computeVertexNormals();
const matrix4 = new THREEJS.Matrix4();
matrix4.fromArray(transforms);
jscadMesh.clear();
jscadMesh.add(new THREEJS.Mesh(geometry, material));
jscadMesh.applyMatrix4(matrix4);
}
private async handleDecomposedMesh(inputs: Inputs.OCCT.DrawShapeDto<Inputs.OCCT.TopoDSShapePointer>, decomposedMesh: Inputs.OCCT.DecomposedMeshDto, options: Partial<Inputs.Draw.DrawOcctShapeOptions>) {
const shapeGroup = new THREEJS.Group();
shapeGroup.name = this.generateEntityId("brepMesh");
this.context.scene.add(shapeGroup);
let dummy;
if (inputs.drawFaces && decomposedMesh && decomposedMesh.faceList && decomposedMesh.faceList.length) {
let pbr: THREEJS.MeshPhysicalMaterial;
if (inputs.faceMaterial) {
pbr = inputs.faceMaterial;
} else {
const hex = Array.isArray(inputs.faceColour) ? inputs.faceColour[0] : inputs.faceColour;
const alpha = inputs.faceOpacity;
const zOffset = inputs.drawEdges ? 2 : 0;
pbr = this.getOrCreateMaterial(hex, alpha, zOffset, () => {
const pbmat = new THREEJS.MeshPhysicalMaterial();
pbmat.name = this.generateEntityId("brepMaterial");
pbmat.color = new THREEJS.Color(hex);
pbmat.metalness = MATERIAL_DEFAULTS.METALNESS.OCCT;
pbmat.roughness = MATERIAL_DEFAULTS.ROUGHNESS.OCCT;
pbmat.alphaTest = alpha;
pbmat.polygonOffset = true;
pbmat.polygonOffsetFactor = zOffset;
return pbmat;
});
}
const meshData: MeshData[] = decomposedMesh.faceList.map(face => {
return {
positions: face.vertex_coord,
normals: face.normal_coord,
indices: face.tri_indexes,
uvs: face.uvs,
};
});
const mesh = this.createOrUpdateSurfacesMesh(meshData, dummy, false, pbr, true, false);
shapeGroup.add(mesh);
// Draw back faces with different color when two-sided rendering is enabled
Eif (inputs.drawTwoSided !== false) {
const backFaceMesh = this.createBackFaceMesh(
meshData,
inputs.backFaceColour || DEFAULT_COLORS.BACK_FACE,
inputs.backFaceOpacity ?? inputs.faceOpacity,
inputs.drawEdges ? 2 : 0
);
shapeGroup.add(backFaceMesh);
}
}
if (inputs.drawEdges && decomposedMesh && decomposedMesh.edgeList && decomposedMesh.edgeList.length) {
const polylineEdgePoints = [];
decomposedMesh.edgeList.forEach(edge => {
const ev = edge.vertex_coord.filter(s => s !== undefined);
polylineEdgePoints.push(ev);
});
const line = this.drawPolylines(
undefined,
polylineEdgePoints,
false,
inputs.edgeWidth,
inputs.edgeOpacity,
inputs.edgeColour,
Inputs.Base.colorMapStrategyEnum.lastColorRemainder,
options.edgeArrowSize,
options.edgeArrowAngle
);
shapeGroup.add(line);
}
if (inputs.drawVertices && decomposedMesh && decomposedMesh.pointsList && decomposedMesh.pointsList.length) {
const mesh = this.drawPoints({
points: decomposedMesh.pointsList,
opacity: 1,
size: inputs.vertexSize,
colours: inputs.vertexColour,
updatable: false,
});
shapeGroup.add(mesh);
}
if (inputs.drawEdgeIndexes) {
const promises = decomposedMesh.edgeList.map(async (edge) => {
let edgeMiddle = edge.middle_point;
Iif (edgeMiddle === undefined) {
edgeMiddle = this.computeEdgeMiddlePos(edge);
}
const tdto = new Inputs.JSCAD.TextDto();
tdto.text = `${edge.edge_index + 1}`;
tdto.height = inputs.edgeIndexHeight;
tdto.lineSpacing = 1.5;
const t = await this.solidText.createVectorText(tdto);
const texts = t.map(s => {
const res = s.map(c => {
return [
c[0],
c[1] + 0.05,
0
] as Inputs.Base.Vector3;
});
const movedOnPosition = res.map(r => this.vector.add({ first: r, second: edgeMiddle }));
return movedOnPosition as Inputs.Base.Vector3[];
});
// texts.forEach(te => textPolylines.push(te));
return texts;
});
const textPolylines = await Promise.all(promises);
const edgeMesh = this.drawPolylines(undefined, textPolylines.flat(), false, 0.2, 1, inputs.edgeIndexColour);
shapeGroup.add(edgeMesh);
}
if (inputs.drawFaceIndexes) {
const promises = decomposedMesh.faceList.map(async (face) => {
let faceMiddle = face.center_point;
Iif (faceMiddle === undefined) {
faceMiddle = this.computeFaceMiddlePos(face.vertex_coord_vec) as Inputs.Base.Point3;
}
const tdto = new Inputs.JSCAD.TextDto();
tdto.text = `${face.face_index}`;
tdto.height = inputs.faceIndexHeight;
tdto.lineSpacing = 1.5;
const t = await this.solidText.createVectorText(tdto);
const texts = t.map(s => {
const res = s.map(c => {
return [
c[0],
c[1] + 0.05,
0
] as Inputs.Base.Point3;
});
const movedOnPosition = res.map(r => this.vector.add({ first: r, second: faceMiddle }));
return movedOnPosition as Inputs.Base.Point3[];
});
return texts;
});
const textPolylines = await Promise.all(promises);
const faceMesh = this.drawPolylines(undefined, textPolylines.flat(), false, 0.2, 1, inputs.faceIndexColour);
faceMesh.parent = shapeGroup;
}
return shapeGroup;
}
private drawPolylines(lineSegments: THREEJS.LineSegments, polylinesPoints: Inputs.Base.Vector3[][], updatable: boolean,
size: number, opacity: number, colours: string | string[], colorMapStrategy: Inputs.Base.colorMapStrategyEnum = Inputs.Base.colorMapStrategyEnum.lastColorRemainder,
arrowSize = 0, arrowAngle = 30) {
if (polylinesPoints && polylinesPoints.length > 0) {
const lineVertices = [];
// Track how many line segments (pairs of vertices) each polyline/arrow has
const polylineSegmentCounts: number[] = [];
// Track colors in order of segments (polyline, then its arrows, then next polyline, etc.)
const allColors: string[] = [];
polylinesPoints.forEach((pts, polylineIndex) => {
const polylineColor = this.resolveColorForEntity(colours, polylineIndex, polylinesPoints.length, colorMapStrategy);
let segmentCount = 0;
for (let i = 0; i < pts.length - 1; i++) {
const c = pts[i];
const n = pts[i + 1];
lineVertices.push(new THREEJS.Vector3(
c[0],
c[1],
c[2]
));
lineVertices.push(new THREEJS.Vector3(
n[0],
n[1],
n[2]
));
segmentCount++;
}
polylineSegmentCounts.push(segmentCount);
allColors.push(polylineColor);
// Compute arrow head lines if arrowSize > 0
if (arrowSize > 0 && pts.length >= 2) {
const arrowLines = this.computeArrowHeadLines(pts as Inputs.Base.Point3[], arrowSize, arrowAngle);
arrowLines.forEach(arrowLine => {
lineVertices.push(new THREEJS.Vector3(arrowLine[0][0], arrowLine[0][1], arrowLine[0][2]));
lineVertices.push(new THREEJS.Vector3(arrowLine[1][0], arrowLine[1][1], arrowLine[1][2]));
polylineSegmentCounts.push(1); // Each arrow line is 1 segment
allColors.push(polylineColor); // Arrow uses same color as its parent polyline
});
}
});
let lines: THREEJS.LineSegments;
if (lineSegments && updatable) {
if (lineSegments?.userData?.linesForRenderLengths === polylinesPoints.map(l => l.length).toString()) {
lineSegments.geometry.clearGroups();
lineSegments.geometry.setFromPoints(lineVertices);
// Update colors when updating geometry
const lineColors = this.computePolylineColorsWithExplicit(polylineSegmentCounts, allColors);
lineSegments.geometry.setAttribute("color", new THREEJS.Float32BufferAttribute(lineColors, 3));
return lineSegments;
} else {
lines = this.createLineGeometry(lineVertices, colours, size, polylineSegmentCounts, colorMapStrategy, allColors);
lines.userData = { linesForRenderLengths: polylinesPoints.map(l => l.length).toString() };
return lines;
}
} else {
lines = this.createLineGeometry(lineVertices, colours, size, polylineSegmentCounts, colorMapStrategy, allColors);
lines.userData = { linesForRenderLengths: polylinesPoints.map(l => l.length).toString() };
return lines;
}
} else E{
return undefined;
}
}
/**
* Compute per-vertex colors for polylines based on color mapping strategy
* @param colours - Single color or array of colors
* @param polylineSegmentCounts - Number of line segments per polyline
* @param colorMapStrategy - Strategy for mapping colors to polylines
* @returns Flat array of RGB values for each vertex
*/
private computePolylineColors(
colours: string | string[],
polylineSegmentCounts: number[],
colorMapStrategy: Inputs.Base.colorMapStrategyEnum
): number[] {
const lineColors: number[] = [];
const totalPolylines = polylineSegmentCounts.length;
polylineSegmentCounts.forEach((segmentCount, polylineIndex) => {
// Get the color for this polyline using the strategy
const colorHex = this.resolveColorForEntity(colours, polylineIndex, totalPolylines, colorMapStrategy);
const color = new THREEJS.Color(colorHex);
// Each segment has 2 vertices, apply the same color to both
for (let i = 0; i < segmentCount * 2; i++) {
lineColors.push(color.r, color.g, color.b);
}
});
return lineColors;
}
/**
* Compute per-vertex colors for polylines using an explicit color array
* @param polylineSegmentCounts - Number of line segments per polyline/arrow line
* @param explicitColors - Array of colors, one per polyline/arrow line
* @returns Flat array of RGB values for each vertex
*/
private computePolylineColorsWithExplicit(
polylineSegmentCounts: number[],
explicitColors: string[]
): number[] {
const lineColors: number[] = [];
polylineSegmentCounts.forEach((segmentCount, index) => {
const colorHex = explicitColors[index] || explicitColors[0] || "#ff0000";
const color = new THREEJS.Color(colorHex);
// Each segment has 2 vertices, apply the same color to both
for (let i = 0; i < segmentCount * 2; i++) {
lineColors.push(color.r, color.g, color.b);
}
});
return lineColors;
}
private createLineGeometry(
lineVertices: THREEJS.Vector3[],
colours: string | string[],
size: number,
polylineSegmentCounts: number[] = [],
colorMapStrategy: Inputs.Base.colorMapStrategyEnum = Inputs.Base.colorMapStrategyEnum.lastColorRemainder,
explicitColors?: string[]
) {
const lineGeometry = new THREEJS.BufferGeometry().setFromPoints(lineVertices);
let lineColors: number[];
if (explicitColors && explicitColors.length > 0) {
// Use explicit colors when provided (includes arrow colors)
lineColors = this.computePolylineColorsWithExplicit(polylineSegmentCounts, explicitColors);
} else Eif (polylineSegmentCounts.length > 0) {
// Use per-polyline coloring with the specified strategy
lineColors = this.computePolylineColors(colours, polylineSegmentCounts, colorMapStrategy);
} else {
// Fallback: single color for all vertices
const color = Array.isArray(colours) ? new THREEJS.Color(colours[0]) : new THREEJS.Color(colours);
lineColors = [];
for (let i = 0; i < lineVertices.length; i++) {
lineColors.push(color.r, color.g, color.b);
}
}
lineGeometry.setAttribute("color", new THREEJS.Float32BufferAttribute(lineColors, 3));
const lineMaterial = new THREEJS.LineBasicMaterial({
color: 0xffffff, linewidth: size, vertexColors: true
});
const line = new THREEJS.LineSegments(lineGeometry, lineMaterial);
line.name = this.generateEntityId("lines");
return line;
}
private handleDecomposedManifold(
decomposedManifold: Inputs.Manifold.DecomposedManifoldMeshDto | Inputs.Base.Vector2[][],
options: Inputs.Draw.DrawManifoldOrCrossSectionOptions): THREEJS.Group {
if ((decomposedManifold as Inputs.Manifold.DecomposedManifoldMeshDto).vertProperties) {
const decomposedMesh = decomposedManifold as Inputs.Manifold.DecomposedManifoldMeshDto;
if (decomposedMesh.triVerts.length !== 0) {
const geometry = new THREEJS.BufferGeometry();
geometry.setAttribute("position", new THREEJS.BufferAttribute(decomposedMesh.vertProperties, 3));
geometry.setIndex(new THREEJS.BufferAttribute(decomposedMesh.triVerts, 1));
geometry.computeVertexNormals();
const group = new THREEJS.Group();
group.name = this.generateEntityId("manifoldMesh");
let material: THREEJS.MeshPhysicalMaterial;
if (options.faceMaterial === undefined) {
material = this.getOrCreateMaterial(options.faceColour, options.faceOpacity, 0, () => {
const mat = new THREEJS.MeshPhysicalMaterial();
mat.name = this.generateEntityId("manifoldMaterial");
mat.color = new THREEJS.Color(options.faceColour);
mat.metalness = MATERIAL_DEFAULTS.METALNESS.MANIFOLD;
mat.roughness = MATERIAL_DEFAULTS.ROUGHNESS.MANIFOLD;
mat.opacity = options.faceOpacity;
mat.alphaTest = 1;
Eif (!options.computeNormals) {
mat.flatShading = true;
}
return mat;
});
} else E{
material = options.faceMaterial as THREEJS.MeshPhysicalMaterial;
}
group.add(new THREEJS.Mesh(geometry, material));
// Draw back faces with different color when two-sided rendering is enabled
Eif (options.drawTwoSided !== false) {
// Prepare mesh data for back face mesh creation
const positions = Array.from(decomposedMesh.vertProperties);
const indices = Array.from(decomposedMesh.triVerts);
// Get normals from the geometry (they were computed above)
const normalAttribute = geometry.getAttribute("normal");
const normals = normalAttribute ? Array.from(normalAttribute.array as Float32Array) : [];
const meshData: MeshData[] = [{
positions,
indices,
normals
}];
const backFaceMesh = this.createBackFaceMesh(
meshData,
options.backFaceColour || DEFAULT_COLORS.BACK_FACE,
options.backFaceOpacity ?? options.faceOpacity,
0
);
group.add(backFaceMesh);
}
this.context.scene.add(group);
return group;
} else {
return undefined;
}
} else {
const decompsoedPolygons = decomposedManifold as Inputs.Base.Vector2[][];
if (decompsoedPolygons.length > 0) {
const group = new THREEJS.Group();
group.name = this.generateEntityId("manifoldCrossSection");
const polylines = decompsoedPolygons.map(polygon => ({
points: polygon.map(p => [p[0], p[1], 0] as Inputs.Base.Point3),
isClosed: true
}));
const polylineMesh = this.drawPolylinesWithColours({
polylinesMesh: undefined,
polylines,
updatable: false,
size: options.crossSectionWidth,
opacity: options.crossSectionOpacity,
colours: options.crossSectionColour
});
polylineMesh.parent = group;
this.context.scene.add(group);
return group;
}
else E{
return undefined;
}
}
}
// Creates a shallow copy of inputs without the faceMaterial property for safe worker communication
// Workers cannot handle complex circular objects like Three.js materials
private getSafeWorkerOptions<T extends { faceMaterial?: THREEJS.Material }>(inputs: T): Omit<T, "faceMaterial"> {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { faceMaterial, ...safeOptions } = inputs;
return safeOptions as Omit<T, "faceMaterial">;
}
/**
* Generate a unique entity ID with semantic naming
* @param type - The type of entity (e.g., 'manifoldMeshContainer', 'jscadMesh')
* @param parentId - Optional parent ID for hierarchical naming
* @returns Unique entity ID string
*/
private generateEntityId(type: string, parentId?: string): string {
const id = `${this.instanceId}-${type}-${++this.entityIdCounter}`;
return parentId ? `${parentId}/${id}` : id;
}
/**
* Get or create a cached material with the specified properties
* Implements LRU-like eviction when cache is full
* @param hex - Hex color string
* @param alpha - Alpha value (0-1)
* @param zOffset - Z-offset value
* @param createFn - Function to create new material if not cached
* @param unlit - Whether the material is unlit (no lighting, for points/lines)
* @returns Cached or newly created material
*/
private getOrCreateMaterial(
hex: string,
alpha: number,
zOffset: number,
createFn: () => THREEJS.MeshPhysicalMaterial,
unlit = false
): THREEJS.MeshPhysicalMaterial {
const key = this.getMaterialKey(hex, alpha, zOffset, unlit);
// Check cache first
const cached = this.materialCache.get(key);
if (cached) {
return cached;
}
// Evict oldest if at capacity (simple FIFO)
if (this.materialCache.size >= CACHE_CONFIG.MAX_MATERIALS) {
const firstKey = this.materialCache.keys().next().value;
const material = this.materialCache.get(firstKey);
if (material && material.dispose) {
material.dispose();
}
this.materialCache.delete(firstKey);
console.warn(`Material cache full, evicted: ${firstKey}`);
}
// Create new material
const material = createFn();
this.materialCache.set(key, material);
return material;
}
/**
* Get or create a cached unlit material (MeshBasicMaterial) for points and lines.
* Uses a separate cache from MeshPhysicalMaterial since these have different types.
* @param hex - Hex color string
* @param alpha - Alpha value (0-1)
* @param createFn - Function to create new material if not cached
* @returns Cached or newly created MeshBasicMaterial
*/
private getOrCreateUnlitMaterial(
hex: string,
alpha: number,
createFn: () => THREEJS.MeshBasicMaterial
): THREEJS.MeshBasicMaterial {
const key = this.getMaterialKey(hex, alpha, 0, true); // unlit=true, zOffset=0
// Check cache first
const cached = this.unlitMaterialCache.get(key);
if (cached) {
return cached;
}
// Evict oldest if at capacity (simple FIFO)
Iif (this.unlitMaterialCache.size >= CACHE_CONFIG.MAX_MATERIALS) {
const firstKey = this.unlitMaterialCache.keys().next().value;
const material = this.unlitMaterialCache.get(firstKey);
if (material && material.dispose) {
material.dispose();
}
this.unlitMaterialCache.delete(firstKey);
console.warn(`Unlit material cache full, evicted: ${firstKey}`);
}
// Create new material
const material = createFn();
this.unlitMaterialCache.set(key, material);
return material;
}
/**
* Create a back face mesh with flipped normals and reversed winding order
* This is used for two-sided rendering of CAD geometries
* @param meshDataConverted - Original mesh data
* @param backFaceColour - Color for the back face
* @param backFaceOpacity - Opacity for the back face
* @param zOffset - Depth bias to prevent z-fighting
* @returns Group containing the back face mesh
*/
private createBackFaceMesh(
meshDataConverted: MeshData[],
backFaceColour: string,
backFaceOpacity: number,
zOffset: number
): THREEJS.Group {
// Create material for back face using the caching system
const backMaterial = this.getOrCreateMaterial(backFaceColour + "-back", backFaceOpacity, zOffset + 0.1, () => {
const mat = new THREEJS.MeshPhysicalMaterial();
mat.name = this.generateEntityId("backFaceMaterial");
mat.color = new THREEJS.Color(backFaceColour);
mat.metalness = MATERIAL_DEFAULTS.METALNESS.SURFACE;
mat.roughness = MATERIAL_DEFAULTS.ROUGHNESS.SURFACE;
mat.opacity = backFaceOpacity;
mat.polygonOffset = true;
mat.polygonOffsetFactor = zOffset + 0.1;
return mat;
});
// Use base class to prepare back face mesh data (flip normals, reverse winding)
// prepareBackFaceMeshData merges all mesh data into one combined mesh
const backFaceMeshData = this.prepareBackFaceMeshData(meshDataConverted);
// Create geometry from the combined mesh data
const geometry = new THREEJS.BufferGeometry();
geometry.setAttribute("position", new THREEJS.BufferAttribute(Float32Array.from(backFaceMeshData.positions), 3));
geometry.setAttribute("normal", new THREEJS.BufferAttribute(Float32Array.from(backFaceMeshData.normals), 3));
if (backFaceMeshData.uvs && backFaceMeshData.uvs.length > 0) {
geometry.setAttribute("uv", new THREEJS.BufferAttribute(Float32Array.from(backFaceMeshData.uvs), 2));
}
geometry.setIndex(new THREEJS.BufferAttribute(Uint32Array.from(backFaceMeshData.indices), 1));
const group = new THREEJS.Group();
group.name = this.generateEntityId("backFaceSurface");
const mesh = new THREEJS.Mesh(geometry, backMaterial);
mesh.name = this.generateEntityId("backFaceSurfaceChild");
group.add(mesh);
return group;
}
private createPointSpheresMesh(
meshName: string, positions: Inputs.Base.Point3[], colors: string[], opacity: number, size: number, _updatable: boolean): THREEJS.Group {
const positionsModel = positions.map((pos, posIndex) => {
return {
position: pos,
color: colors[posIndex],
posIndex
};
});
const colorSet = Array.from(new Set(colors));
const materialSet = colorSet.map((colour) => {
// Use cached unlit material for points
const mat = this.getOrCreateUnlitMaterial(colour, opacity, () => {
const material = new THREEJS.MeshBasicMaterial({ name: this.generateEntityId("pointMaterial") });
material.opacity = opacity;
material.transparent = opacity < 1;
material.color = new THREEJS.Color(colour);
return material;
});
const filteredPositions = positionsModel.filter(s => s.color === colour);
return { hex: colour, material: mat, positions: filteredPositions };
});
const pointsGroup = new THREEJS.Group();
pointsGroup.name = meshName;
this.context.scene.add(pointsGroup);
// Create one InstancedMesh per unique color for efficient rendering
materialSet.forEach(ms => {
const pointCount = ms.positions.length;
if (pointCount === 0) return;
// Use fewer segments for large point counts to improve performance
const segments = pointCount > 1000 ? 1 : 6;
const geom = new THREEJS.SphereGeometry(size, segments, segments);
// Create a single InstancedMesh for all points of this color
const instancedMesh = new THREEJS.InstancedMesh(geom, ms.material, pointCount);
instancedMesh.name = this.generateEntityId(`points-${ms.hex}`);
// Store the original point indices for updating later
const pointIndices: number[] = [];
const matrix = new THREEJS.Matrix4();
ms.positions.forEach((pos, instanceIndex) => {
matrix.setPosition(pos.position[0], pos.position[1], pos.position[2]);
instancedMesh.setMatrixAt(instanceIndex, matrix);
pointIndices.push(pos.posIndex);
});
instancedMesh.instanceMatrix.needsUpdate = true;
instancedMesh.userData = { pointIndices };
pointsGroup.add(instancedMesh);
});
return pointsGroup;
}
}
|