@faicad/cq-compat-compare 0.29.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Assembly STEP equivalence comparison.
3
+ *
4
+ * Four-level comparison:
5
+ * 1. Assembly structure (leaf count, part names, hierarchy)
6
+ * 2. Part pose (center of mass / bbox center in assembly coords)
7
+ * 3. Part geometry (volume, topology — per-part, name-matched)
8
+ * 4. Overall geometry (fuse all parts → boolean difference)
9
+ *
10
+ * Part names must match exactly (port verification scenario).
11
+ */
12
+ import type { BrepBoundingBox, BrepVec3 } from '@faicad/faijs';
13
+ /** Tolerance options. */
14
+ export interface AssemblyCompareOptions {
15
+ linearTolerance?: number;
16
+ volumeRelativeTolerance?: number;
17
+ booleanVolumeTolerance?: number;
18
+ strictTopology?: boolean;
19
+ /**
20
+ * Require part names to match between the two files (default true).
21
+ * Set to false for files whose PRODUCT names are not under our control
22
+ * (e.g. CadQuery/OCC references named "SOLID" vs our "shape_x") — parts are
23
+ * then paired by index in sorted order. Structure still requires the same
24
+ * leaf count, so the compound-vs-parts check remains intact.
25
+ */
26
+ matchNames?: boolean;
27
+ /**
28
+ * Part-pairing strategy for the per-part comparison (P0b):
29
+ * - `'names'` (default): exact PRODUCT-name match — faijs-vs-faijs.
30
+ * - `'order-index'`: pair leaves by index after sorting both lists by name
31
+ * (legacy fallback for foreign PRODUCT names; safe only when leaf count
32
+ * matches and parts line up in the same sorted order).
33
+ * - `'order-centroid'`: pair each A-leaf to the nearest B-leaf by assembly
34
+ * centroid (greedy nearest-first); robust to arbitrary naming/ordering,
35
+ * used for CadQuery-reference vs faijs-candidate cross-naming compare.
36
+ * When `pairing` is omitted it is derived from `matchNames`
37
+ * (`true` → `'names'`, `false` → `'order-index'`).
38
+ */
39
+ pairing?: 'names' | 'order-index' | 'order-centroid';
40
+ /**
41
+ * Skip the fused (A∪B → cut) boolean-difference computation entirely
42
+ * (default false). The fused cut is expensive on near-coincident B-spline
43
+ * faces and the occt-wasm kernel can return inverted/garbage solids for it
44
+ * (documented in faijs-gears analysis docs); per-part volume/CoM/bbox
45
+ * checks remain the verdict. When true, `booleanDiff` is reported as
46
+ * {aMinusB: NaN, bMinusA: NaN, match: true}.
47
+ */
48
+ skipFusedBoolean?: boolean;
49
+ }
50
+ /** Per-part comparison result. */
51
+ export interface PartCompareResult {
52
+ name: string;
53
+ found: boolean;
54
+ volume?: {
55
+ a: number;
56
+ b: number;
57
+ match: boolean;
58
+ diffPct: number;
59
+ };
60
+ centerOfMass?: {
61
+ a: BrepVec3;
62
+ b: BrepVec3;
63
+ match: boolean;
64
+ maxDiff: number;
65
+ };
66
+ bbox?: {
67
+ a: BrepBoundingBox;
68
+ b: BrepBoundingBox;
69
+ match: boolean;
70
+ maxDiff: number;
71
+ };
72
+ topology?: {
73
+ a: {
74
+ faces: number;
75
+ edges: number;
76
+ vertices: number;
77
+ };
78
+ b: {
79
+ faces: number;
80
+ edges: number;
81
+ vertices: number;
82
+ };
83
+ match: boolean;
84
+ };
85
+ color?: {
86
+ a: [number, number, number] | null;
87
+ b: [number, number, number] | null;
88
+ match: boolean;
89
+ };
90
+ }
91
+ /** Full assembly comparison result. */
92
+ export interface AssemblyCompareResult {
93
+ fileA: string;
94
+ fileB: string;
95
+ equivalent: boolean;
96
+ structure: {
97
+ leafCountA: number;
98
+ leafCountB: number;
99
+ namesA: string[];
100
+ namesB: string[];
101
+ match: boolean;
102
+ missingInB: string[];
103
+ missingInA: string[];
104
+ };
105
+ parts: PartCompareResult[];
106
+ overall: {
107
+ volumeA: number;
108
+ volumeB: number;
109
+ volumeMatch: boolean;
110
+ volumeDiffPct: number;
111
+ bboxMatch: boolean;
112
+ bboxMaxDiff: number;
113
+ booleanDiff: {
114
+ aMinusB: number;
115
+ bMinusA: number;
116
+ match: boolean;
117
+ };
118
+ };
119
+ details: string[];
120
+ }
121
+ /**
122
+ * Compare two assembly STEP files for equivalence.
123
+ *
124
+ * @param fileA - Path to reference STEP.
125
+ * @param fileB - Path to candidate STEP.
126
+ * @param options - Comparison tolerances.
127
+ * @returns Detailed per-level comparison result.
128
+ */
129
+ export declare function compareAssemblyFiles(fileA: string, fileB: string, options?: AssemblyCompareOptions): Promise<AssemblyCompareResult>;
130
+ /**
131
+ * Print a human-readable assembly comparison report.
132
+ * @param result - Comparison result from compareAssemblyFiles.
133
+ */
134
+ export declare function printAssemblyReport(result: AssemblyCompareResult): void;
135
+ //# sourceMappingURL=assembly-compare.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assembly-compare.d.ts","sourceRoot":"","sources":["../src/assembly-compare.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAQH,OAAO,KAAK,EAA2B,eAAe,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAGvF,yBAAyB;AACzB,MAAM,WAAW,sBAAsB;IACrC,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,uBAAuB,CAAC,EAAE,MAAM,CAAA;IAChC,sBAAsB,CAAC,EAAE,MAAM,CAAA;IAC/B,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB;;;;;;OAMG;IACH,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,EAAE,OAAO,GAAG,aAAa,GAAG,gBAAgB,CAAA;IACpD;;;;;;;OAOG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAC3B;AAED,kCAAkC;AAClC,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,OAAO,CAAA;IACd,MAAM,CAAC,EAAE;QAAE,CAAC,EAAE,MAAM,CAAC;QAAC,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,OAAO,CAAC;QAAC,OAAO,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AU,EAAE,MAAM,EAAE,CAAA;KACrB,CAAA;IACD,KAAK,EAAE,iBAAiB,EAAE,CAAA;IAC1B,OAAO,EAAE;QACP,OAAO,EAAE,MAAM,CAAA;QACf,OAAO,EAAE,MAAM,CAAA;QACf,WAAW,EAAE,OAAO,CAAA;QACpB,aAAa,EAAE,MAAM,CAAA;QACrB,SAAS,EAAE,OAAO,CAAA;QAClB,WAAW,EAAE,MAAM,CAAA;QACnB,WAAW,EAAE;YAAE,OAAO,EAAE,MAAM,CAAC;YAAC,OAAO,EAAE,MAAM,CAAC;YAAC,KAAK,EAAE,OAAO,CAAA;SAAE,CAAA;KAClE,CAAA;IACD,OAAO,EAAE,MAAM,EAAE,CAAA;CAClB;AA4CD;;;;;;;GAOG;AACH,wBAAsB,oBAAoB,CACxC,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,OAAO,GAAE,sBAA2B,GACnC,OAAO,CAAC,qBAAqB,CAAC,CA6LhC;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,qBAAqB,GAAG,IAAI,CA2BvE"}
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Assembly STEP equivalence comparison.
3
+ *
4
+ * Four-level comparison:
5
+ * 1. Assembly structure (leaf count, part names, hierarchy)
6
+ * 2. Part pose (center of mass / bbox center in assembly coords)
7
+ * 3. Part geometry (volume, topology — per-part, name-matched)
8
+ * 4. Overall geometry (fuse all parts → boolean difference)
9
+ *
10
+ * Part names must match exactly (port verification scenario).
11
+ */
12
+ import { readFileSync } from 'node:fs';
13
+ import { initOcctWasm, importAssemblyFromStep, collectLeafParts, } from '@faicad/faijs';
14
+ // pairing 由 matchNames 推导(见 compareAssemblyFiles 内部),不进 DEFAULT_OPTS,
15
+ // 否则会覆盖「matchNames:false 但缺 pairing」的推定语义。
16
+ const DEFAULT_OPTS = {
17
+ linearTolerance: 1e-3,
18
+ volumeRelativeTolerance: 1e-3,
19
+ booleanVolumeTolerance: 1e-1,
20
+ strictTopology: false,
21
+ matchNames: true,
22
+ skipFusedBoolean: false,
23
+ };
24
+ function vmax(a, b) {
25
+ return Math.max(Math.abs(a.x - b.x), Math.abs(a.y - b.y), Math.abs(a.z - b.z));
26
+ }
27
+ function bbmax(a, b) {
28
+ return Math.max(Math.abs(a.xmin - b.xmin), Math.abs(a.xmax - b.xmax), Math.abs(a.ymin - b.ymin), Math.abs(a.ymax - b.ymax), Math.abs(a.zmin - b.zmin), Math.abs(a.zmax - b.zmax));
29
+ }
30
+ function topoStats(kernel, shape) {
31
+ return {
32
+ faces: kernel.getSubShapes(shape, 'face').length,
33
+ edges: kernel.getSubShapes(shape, 'edge').length,
34
+ vertices: kernel.getSubShapes(shape, 'vertex').length,
35
+ };
36
+ }
37
+ function fuseAll(kernel, shapes) {
38
+ if (shapes.length === 0)
39
+ return null;
40
+ let acc = shapes[0];
41
+ for (let i = 1; i < shapes.length; i++) {
42
+ const fused = kernel.fuse(acc, shapes[i]);
43
+ if (i > 1)
44
+ kernel.release(acc);
45
+ acc = fused;
46
+ }
47
+ return acc;
48
+ }
49
+ /**
50
+ * Compare two assembly STEP files for equivalence.
51
+ *
52
+ * @param fileA - Path to reference STEP.
53
+ * @param fileB - Path to candidate STEP.
54
+ * @param options - Comparison tolerances.
55
+ * @returns Detailed per-level comparison result.
56
+ */
57
+ export async function compareAssemblyFiles(fileA, fileB, options = {}) {
58
+ const opts = { ...DEFAULT_OPTS, ...options };
59
+ const details = [];
60
+ const kernel = await initOcctWasm();
61
+ const bufA = readFileSync(fileA);
62
+ const bufB = readFileSync(fileB);
63
+ // readFileSync returns pooled Buffers for small files: buf.buffer is the
64
+ // whole pool with garbage beyond byteLength, which corrupts STEP imports
65
+ // of files < ~4KB. Pass exact copies.
66
+ const exact = (buf) => buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
67
+ const nodesA = await importAssemblyFromStep(exact(bufA));
68
+ const nodesB = await importAssemblyFromStep(exact(bufB));
69
+ const leavesA = collectLeafParts(nodesA).filter(n => n.shapeHandle !== null);
70
+ const leavesB = collectLeafParts(nodesB).filter(n => n.shapeHandle !== null);
71
+ // ── Level 1: Structure ──
72
+ const namesA = leavesA.map(n => n.name).sort();
73
+ const namesB = leavesB.map(n => n.name).sort();
74
+ const missingInB = namesA.filter(n => !namesB.includes(n));
75
+ const missingInA = namesB.filter(n => !namesA.includes(n));
76
+ // P0b:pairing 模式(缺省由 matchNames 推导)
77
+ const pairing = opts.pairing ?? (opts.matchNames ? 'names' : 'order-index');
78
+ const namesMatch = pairing === 'names' && missingInB.length === 0 && missingInA.length === 0;
79
+ const structureMatch = leavesA.length === leavesB.length && (pairing !== 'names' || namesMatch);
80
+ details.push(`structure: ${leavesA.length} vs ${leavesB.length} leaves, names match=${structureMatch} (pairing=${pairing})`);
81
+ if (missingInB.length)
82
+ details.push(` missing in B: ${missingInB.join(', ')}`);
83
+ if (missingInA.length)
84
+ details.push(` missing in A: ${missingInA.join(', ')}`);
85
+ // ── Level 2 & 3: Per-part pose + geometry ──
86
+ const partResults = [];
87
+ // 配对:按 pairing 模式生成 (A-leaf, B-leaf) 对。
88
+ const byName = (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
89
+ const centroidOf = (leaf) => kernel.getCenterOfMass(leaf.shapeHandle);
90
+ const pairs = [];
91
+ if (pairing === 'names') {
92
+ const mapB = new Map(leavesB.map(n => [n.name, n]));
93
+ for (const a of leavesA)
94
+ pairs.push([a, mapB.get(a.name) ?? null]);
95
+ }
96
+ else if (pairing === 'order-index') {
97
+ const sortedA = [...leavesA].sort(byName);
98
+ const sortedB = [...leavesB].sort(byName);
99
+ for (let i = 0; i < sortedA.length; i++)
100
+ pairs.push([sortedA[i], sortedB[i] ?? null]);
101
+ }
102
+ else {
103
+ // order-centroid:贪心最近质心配对(leaf 数相等由 structureMatch 保证)
104
+ const centB = leavesB.map(centroidOf);
105
+ const usedB = new Set();
106
+ for (const a of leavesA) {
107
+ const ca = centroidOf(a);
108
+ let best = -1;
109
+ let bestD = Infinity;
110
+ for (let j = 0; j < leavesB.length; j++) {
111
+ if (usedB.has(j))
112
+ continue;
113
+ const d = vmax(ca, centB[j]);
114
+ if (d < bestD) {
115
+ bestD = d;
116
+ best = j;
117
+ }
118
+ }
119
+ if (best >= 0) {
120
+ usedB.add(best);
121
+ pairs.push([a, leavesB[best]]);
122
+ }
123
+ else
124
+ pairs.push([a, null]);
125
+ }
126
+ }
127
+ for (const [leafA, leafB] of pairs) {
128
+ if (!leafB) {
129
+ partResults.push({ name: leafA.name, found: false });
130
+ continue;
131
+ }
132
+ const shapeA = leafA.shapeHandle;
133
+ const shapeB = leafB.shapeHandle;
134
+ const volA = kernel.getVolume(shapeA);
135
+ const volB = kernel.getVolume(shapeB);
136
+ const volDiffPct = volA > 0 ? (Math.abs(volA - volB) / volA) * 100 : 0;
137
+ const volMatch = volDiffPct <= opts.volumeRelativeTolerance * 100;
138
+ const comA = kernel.getCenterOfMass(shapeA);
139
+ const comB = kernel.getCenterOfMass(shapeB);
140
+ const comDiff = vmax(comA, comB);
141
+ const comMatch = comDiff <= opts.linearTolerance;
142
+ const bbA = kernel.getBoundingBox(shapeA);
143
+ const bbB = kernel.getBoundingBox(shapeB);
144
+ const bbDiff = bbmax(bbA, bbB);
145
+ const bbMatch = bbDiff <= opts.linearTolerance;
146
+ const topA = topoStats(kernel, shapeA);
147
+ const topB = topoStats(kernel, shapeB);
148
+ const topoMatch = opts.strictTopology
149
+ ? topA.faces === topB.faces && topA.edges === topB.edges && topA.vertices === topB.vertices
150
+ : true;
151
+ const colA = leafA.color;
152
+ const colB = leafB.color;
153
+ const colMatch = Boolean((!colA && !colB) || (colA && colB &&
154
+ Math.abs(colA[0] - colB[0]) < 0.01 &&
155
+ Math.abs(colA[1] - colB[1]) < 0.01 &&
156
+ Math.abs(colA[2] - colB[2]) < 0.01));
157
+ partResults.push({
158
+ name: leafA.name,
159
+ found: true,
160
+ volume: { a: volA, b: volB, match: volMatch, diffPct: volDiffPct },
161
+ centerOfMass: { a: comA, b: comB, match: comMatch, maxDiff: comDiff },
162
+ bbox: { a: bbA, b: bbB, match: bbMatch, maxDiff: bbDiff },
163
+ topology: { a: topA, b: topB, match: topoMatch },
164
+ color: { a: colA, b: colB, match: colMatch },
165
+ });
166
+ details.push(`part "${leafA.name}": vol ${volA.toFixed(1)} vs ${volB.toFixed(1)} (${volDiffPct.toFixed(3)}%), com diff=${comDiff.toExponential(2)}, bbox diff=${bbDiff.toExponential(2)}, color=${colMatch}`);
167
+ }
168
+ // ── Level 4: Overall fused geometry ──
169
+ const shapesA = leavesA.map(n => n.shapeHandle);
170
+ const shapesB = leavesB.map(n => n.shapeHandle);
171
+ const fusedA = fuseAll(kernel, shapesA);
172
+ const fusedB = fuseAll(kernel, shapesB);
173
+ let overallVolumeA = 0, overallVolumeB = 0, overallVolMatch = false, overallVolDiffPct = 0;
174
+ let overallBboxMatch = false, overallBboxDiff = 0;
175
+ let boolAB = 0, boolBA = 0, boolMatch = false;
176
+ if (fusedA && fusedB) {
177
+ overallVolumeA = kernel.getVolume(fusedA);
178
+ overallVolumeB = kernel.getVolume(fusedB);
179
+ overallVolDiffPct = overallVolumeA > 0 ? (Math.abs(overallVolumeA - overallVolumeB) / overallVolumeA) * 100 : 0;
180
+ overallVolMatch = overallVolDiffPct <= opts.volumeRelativeTolerance * 100;
181
+ const fbbA = kernel.getBoundingBox(fusedA);
182
+ const fbbB = kernel.getBoundingBox(fusedB);
183
+ overallBboxDiff = bbmax(fbbA, fbbB);
184
+ overallBboxMatch = overallBboxDiff <= opts.linearTolerance;
185
+ if (opts.skipFusedBoolean) {
186
+ boolAB = NaN;
187
+ boolBA = NaN;
188
+ boolMatch = true;
189
+ }
190
+ else {
191
+ const cutAB = kernel.cut(fusedA, fusedB);
192
+ const cutBA = kernel.cut(fusedB, fusedA);
193
+ boolAB = kernel.getVolume(cutAB);
194
+ boolBA = kernel.getVolume(cutBA);
195
+ boolMatch = boolAB <= opts.booleanVolumeTolerance && boolBA <= opts.booleanVolumeTolerance;
196
+ kernel.release(cutAB);
197
+ kernel.release(cutBA);
198
+ }
199
+ }
200
+ details.push(`overall: vol ${overallVolumeA.toFixed(1)} vs ${overallVolumeB.toFixed(1)} (${overallVolDiffPct.toFixed(3)}%), bbox diff=${overallBboxDiff.toExponential(2)}, bool A-B=${boolAB.toExponential(2)}, B-A=${boolBA.toExponential(2)}`);
201
+ // Cleanup
202
+ if (fusedA)
203
+ kernel.release(fusedA);
204
+ if (fusedB)
205
+ kernel.release(fusedB);
206
+ // Note: leaf shapeHandles are owned by the assembly tree, not released here
207
+ const partsAllMatch = partResults.every(p => p.found && p.volume?.match && p.centerOfMass?.match && p.bbox?.match && p.topology?.match && p.color?.match);
208
+ const equivalent = structureMatch && partsAllMatch && overallVolMatch && overallBboxMatch && boolMatch;
209
+ return {
210
+ fileA,
211
+ fileB,
212
+ equivalent,
213
+ structure: {
214
+ leafCountA: leavesA.length,
215
+ leafCountB: leavesB.length,
216
+ namesA,
217
+ namesB,
218
+ match: structureMatch,
219
+ missingInB,
220
+ missingInA,
221
+ },
222
+ parts: partResults,
223
+ overall: {
224
+ volumeA: overallVolumeA,
225
+ volumeB: overallVolumeB,
226
+ volumeMatch: overallVolMatch,
227
+ volumeDiffPct: overallVolDiffPct,
228
+ bboxMatch: overallBboxMatch,
229
+ bboxMaxDiff: overallBboxDiff,
230
+ booleanDiff: { aMinusB: boolAB, bMinusA: boolBA, match: boolMatch },
231
+ },
232
+ details,
233
+ };
234
+ }
235
+ /**
236
+ * Print a human-readable assembly comparison report.
237
+ * @param result - Comparison result from compareAssemblyFiles.
238
+ */
239
+ export function printAssemblyReport(result) {
240
+ console.log(`\n=== Assembly Comparison: ${result.fileA} vs ${result.fileB} ===`);
241
+ console.log(`Overall: ${result.equivalent ? '✓ EQUIVALENT' : '✗ DIFFERENT'}\n`);
242
+ console.log('── Level 1: Structure ──');
243
+ console.log(` Leaves: ${result.structure.leafCountA} vs ${result.structure.leafCountB} — ${result.structure.match ? '✓' : '✗'}`);
244
+ console.log(` Names A: [${result.structure.namesA.join(', ')}]`);
245
+ console.log(` Names B: [${result.structure.namesB.join(', ')}]`);
246
+ if (result.structure.missingInB.length)
247
+ console.log(` ✗ Missing in B: ${result.structure.missingInB.join(', ')}`);
248
+ if (result.structure.missingInA.length)
249
+ console.log(` ✗ Missing in A: ${result.structure.missingInA.join(', ')}`);
250
+ console.log('\n── Level 2 & 3: Per-part pose + geometry ──');
251
+ for (const p of result.parts) {
252
+ if (!p.found) {
253
+ console.log(` ✗ "${p.name}": not found in B`);
254
+ continue;
255
+ }
256
+ const ok = p.volume?.match && p.centerOfMass?.match && p.bbox?.match && p.color?.match;
257
+ console.log(` ${ok ? '✓' : '✗'} "${p.name}": vol ${p.volume?.a.toFixed(1)} vs ${p.volume?.b.toFixed(1)} (${p.volume?.diffPct.toFixed(3)}%), com diff=${p.centerOfMass?.maxDiff.toExponential(2)}, bbox diff=${p.bbox?.maxDiff.toExponential(2)}, color=${p.color?.match ? '✓' : '✗'}`);
258
+ }
259
+ console.log('\n── Level 4: Overall fused geometry ──');
260
+ console.log(` Volume: ${result.overall.volumeA.toFixed(1)} vs ${result.overall.volumeB.toFixed(1)} (${result.overall.volumeDiffPct.toFixed(3)}%) — ${result.overall.volumeMatch ? '✓' : '✗'}`);
261
+ console.log(` BBox diff: ${result.overall.bboxMaxDiff.toExponential(2)} — ${result.overall.bboxMatch ? '✓' : '✗'}`);
262
+ console.log(` Boolean A-B: ${result.overall.booleanDiff.aMinusB.toExponential(2)} mm³`);
263
+ console.log(` Boolean B-A: ${result.overall.booleanDiff.bMinusA.toExponential(2)} mm³ — ${result.overall.booleanDiff.match ? '✓' : '✗'}`);
264
+ console.log('');
265
+ }
266
+ //# sourceMappingURL=assembly-compare.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assembly-compare.js","sourceRoot":"","sources":["../src/assembly-compare.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE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AAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAA;IAC1I,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;AACjB,CAAC","sourcesContent":["/**\n * Assembly STEP equivalence comparison.\n *\n * Four-level comparison:\n * 1. Assembly structure (leaf count, part names, hierarchy)\n * 2. Part pose (center of mass / bbox center in assembly coords)\n * 3. Part geometry (volume, topology — per-part, name-matched)\n * 4. Overall geometry (fuse all parts → boolean difference)\n *\n * Part names must match exactly (port verification scenario).\n */\n\nimport { readFileSync } from 'node:fs'\nimport {\n initOcctWasm,\n importAssemblyFromStep,\n collectLeafParts,\n} from '@faicad/faijs'\nimport type { OcctKernel, ShapeHandle, BrepBoundingBox, BrepVec3 } from '@faicad/faijs'\nimport type { AssemblyPartNode } from '@faicad/faijs'\n\n/** Tolerance options. */\nexport interface AssemblyCompareOptions {\n linearTolerance?: number\n volumeRelativeTolerance?: number\n booleanVolumeTolerance?: number\n strictTopology?: boolean\n /**\n * Require part names to match between the two files (default true).\n * Set to false for files whose PRODUCT names are not under our control\n * (e.g. CadQuery/OCC references named \"SOLID\" vs our \"shape_x\") — parts are\n * then paired by index in sorted order. Structure still requires the same\n * leaf count, so the compound-vs-parts check remains intact.\n */\n matchNames?: boolean\n /**\n * Part-pairing strategy for the per-part comparison (P0b):\n * - `'names'` (default): exact PRODUCT-name match — faijs-vs-faijs.\n * - `'order-index'`: pair leaves by index after sorting both lists by name\n * (legacy fallback for foreign PRODUCT names; safe only when leaf count\n * matches and parts line up in the same sorted order).\n * - `'order-centroid'`: pair each A-leaf to the nearest B-leaf by assembly\n * centroid (greedy nearest-first); robust to arbitrary naming/ordering,\n * used for CadQuery-reference vs faijs-candidate cross-naming compare.\n * When `pairing` is omitted it is derived from `matchNames`\n * (`true` → `'names'`, `false` → `'order-index'`).\n */\n pairing?: 'names' | 'order-index' | 'order-centroid'\n /**\n * Skip the fused (A∪B → cut) boolean-difference computation entirely\n * (default false). The fused cut is expensive on near-coincident B-spline\n * faces and the occt-wasm kernel can return inverted/garbage solids for it\n * (documented in faijs-gears analysis docs); per-part volume/CoM/bbox\n * checks remain the verdict. When true, `booleanDiff` is reported as\n * {aMinusB: NaN, bMinusA: NaN, match: true}.\n */\n skipFusedBoolean?: boolean\n}\n\n/** Per-part comparison result. */\nexport interface PartCompareResult {\n name: string\n found: boolean\n volume?: { a: number; b: number; match: boolean; diffPct: number }\n centerOfMass?: { a: BrepVec3; b: BrepVec3; match: boolean; maxDiff: number }\n bbox?: { a: BrepBoundingBox; b: BrepBoundingBox; match: boolean; maxDiff: number }\n topology?: {\n a: { faces: number; edges: number; vertices: number }\n b: { faces: number; edges: number; vertices: number }\n match: boolean\n }\n color?: { a: [number, number, number] | null; b: [number, number, number] | null; match: boolean }\n}\n\n/** Full assembly comparison result. */\nexport interface AssemblyCompareResult {\n fileA: string\n fileB: string\n equivalent: boolean\n structure: {\n leafCountA: number\n leafCountB: number\n namesA: string[]\n namesB: string[]\n match: boolean\n missingInB: string[]\n missingInA: string[]\n }\n parts: PartCompareResult[]\n overall: {\n volumeA: number\n volumeB: number\n volumeMatch: boolean\n volumeDiffPct: number\n bboxMatch: boolean\n bboxMaxDiff: number\n booleanDiff: { aMinusB: number; bMinusA: number; match: boolean }\n }\n details: string[]\n}\n\n// pairing 由 matchNames 推导(见 compareAssemblyFiles 内部),不进 DEFAULT_OPTS,\n// 否则会覆盖「matchNames:false 但缺 pairing」的推定语义。\nconst DEFAULT_OPTS = {\n linearTolerance: 1e-3,\n volumeRelativeTolerance: 1e-3,\n booleanVolumeTolerance: 1e-1,\n strictTopology: false,\n matchNames: true,\n skipFusedBoolean: false,\n}\n\nfunction vmax(a: BrepVec3, b: BrepVec3): number {\n return Math.max(Math.abs(a.x - b.x), Math.abs(a.y - b.y), Math.abs(a.z - b.z))\n}\n\nfunction bbmax(a: BrepBoundingBox, b: BrepBoundingBox): number {\n return Math.max(\n Math.abs(a.xmin - b.xmin), Math.abs(a.xmax - b.xmax),\n Math.abs(a.ymin - b.ymin), Math.abs(a.ymax - b.ymax),\n Math.abs(a.zmin - b.zmin), Math.abs(a.zmax - b.zmax),\n )\n}\n\nfunction topoStats(kernel: OcctKernel, shape: ShapeHandle) {\n return {\n faces: kernel.getSubShapes(shape, 'face').length,\n edges: kernel.getSubShapes(shape, 'edge').length,\n vertices: kernel.getSubShapes(shape, 'vertex').length,\n }\n}\n\nfunction fuseAll(kernel: OcctKernel, shapes: ShapeHandle[]): ShapeHandle | null {\n if (shapes.length === 0) return null\n let acc = shapes[0]\n for (let i = 1; i < shapes.length; i++) {\n const fused = kernel.fuse(acc, shapes[i])\n if (i > 1) kernel.release(acc)\n acc = fused\n }\n return acc\n}\n\n/**\n * Compare two assembly STEP files for equivalence.\n *\n * @param fileA - Path to reference STEP.\n * @param fileB - Path to candidate STEP.\n * @param options - Comparison tolerances.\n * @returns Detailed per-level comparison result.\n */\nexport async function compareAssemblyFiles(\n fileA: string,\n fileB: string,\n options: AssemblyCompareOptions = {},\n): Promise<AssemblyCompareResult> {\n const opts = { ...DEFAULT_OPTS, ...options }\n const details: string[] = []\n\n const kernel = await initOcctWasm()\n\n const bufA = readFileSync(fileA)\n const bufB = readFileSync(fileB)\n // readFileSync returns pooled Buffers for small files: buf.buffer is the\n // whole pool with garbage beyond byteLength, which corrupts STEP imports\n // of files < ~4KB. Pass exact copies.\n const exact = (buf: Buffer): ArrayBuffer =>\n buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) as ArrayBuffer\n const nodesA = await importAssemblyFromStep(exact(bufA))\n const nodesB = await importAssemblyFromStep(exact(bufB))\n const leavesA = collectLeafParts(nodesA).filter(n => n.shapeHandle !== null)\n const leavesB = collectLeafParts(nodesB).filter(n => n.shapeHandle !== null)\n\n // ── Level 1: Structure ──\n const namesA = leavesA.map(n => n.name).sort()\n const namesB = leavesB.map(n => n.name).sort()\n const missingInB = namesA.filter(n => !namesB.includes(n))\n const missingInA = namesB.filter(n => !namesA.includes(n))\n // P0b:pairing 模式(缺省由 matchNames 推导)\n const pairing: 'names' | 'order-index' | 'order-centroid' =\n opts.pairing ?? (opts.matchNames ? 'names' : 'order-index')\n const namesMatch = pairing === 'names' && missingInB.length === 0 && missingInA.length === 0\n const structureMatch = leavesA.length === leavesB.length && (pairing !== 'names' || namesMatch)\n details.push(`structure: ${leavesA.length} vs ${leavesB.length} leaves, names match=${structureMatch} (pairing=${pairing})`)\n if (missingInB.length) details.push(` missing in B: ${missingInB.join(', ')}`)\n if (missingInA.length) details.push(` missing in A: ${missingInA.join(', ')}`)\n\n // ── Level 2 & 3: Per-part pose + geometry ──\n const partResults: PartCompareResult[] = []\n\n // 配对:按 pairing 模式生成 (A-leaf, B-leaf) 对。\n const byName = (a: AssemblyPartNode, b: AssemblyPartNode): number =>\n a.name < b.name ? -1 : a.name > b.name ? 1 : 0\n const centroidOf = (leaf: AssemblyPartNode): BrepVec3 =>\n kernel.getCenterOfMass(leaf.shapeHandle as unknown as ShapeHandle)\n\n const pairs: Array<[AssemblyPartNode, AssemblyPartNode | null]> = []\n if (pairing === 'names') {\n const mapB = new Map(leavesB.map(n => [n.name, n]))\n for (const a of leavesA) pairs.push([a, mapB.get(a.name) ?? null])\n } else if (pairing === 'order-index') {\n const sortedA = [...leavesA].sort(byName)\n const sortedB = [...leavesB].sort(byName)\n for (let i = 0; i < sortedA.length; i++) pairs.push([sortedA[i], sortedB[i] ?? null])\n } else {\n // order-centroid:贪心最近质心配对(leaf 数相等由 structureMatch 保证)\n const centB = leavesB.map(centroidOf)\n const usedB = new Set<number>()\n for (const a of leavesA) {\n const ca = centroidOf(a)\n let best = -1\n let bestD = Infinity\n for (let j = 0; j < leavesB.length; j++) {\n if (usedB.has(j)) continue\n const d = vmax(ca, centB[j])\n if (d < bestD) { bestD = d; best = j }\n }\n if (best >= 0) { usedB.add(best); pairs.push([a, leavesB[best]]) }\n else pairs.push([a, null])\n }\n }\n\n for (const [leafA, leafB] of pairs) {\n if (!leafB) {\n partResults.push({ name: leafA.name, found: false })\n continue\n }\n const shapeA = leafA.shapeHandle! as unknown as ShapeHandle\n const shapeB = leafB.shapeHandle! as unknown as ShapeHandle\n\n const volA = kernel.getVolume(shapeA)\n const volB = kernel.getVolume(shapeB)\n const volDiffPct = volA > 0 ? (Math.abs(volA - volB) / volA) * 100 : 0\n const volMatch = volDiffPct <= opts.volumeRelativeTolerance * 100\n\n const comA = kernel.getCenterOfMass(shapeA)\n const comB = kernel.getCenterOfMass(shapeB)\n const comDiff = vmax(comA, comB)\n const comMatch = comDiff <= opts.linearTolerance\n\n const bbA = kernel.getBoundingBox(shapeA)\n const bbB = kernel.getBoundingBox(shapeB)\n const bbDiff = bbmax(bbA, bbB)\n const bbMatch = bbDiff <= opts.linearTolerance\n\n const topA = topoStats(kernel, shapeA)\n const topB = topoStats(kernel, shapeB)\n const topoMatch = opts.strictTopology\n ? topA.faces === topB.faces && topA.edges === topB.edges && topA.vertices === topB.vertices\n : true\n\n const colA = leafA.color\n const colB = leafB.color\n const colMatch = Boolean((!colA && !colB) || (colA && colB &&\n Math.abs(colA[0] - colB[0]) < 0.01 &&\n Math.abs(colA[1] - colB[1]) < 0.01 &&\n Math.abs(colA[2] - colB[2]) < 0.01))\n\n partResults.push({\n name: leafA.name,\n found: true,\n volume: { a: volA, b: volB, match: volMatch, diffPct: volDiffPct },\n centerOfMass: { a: comA, b: comB, match: comMatch, maxDiff: comDiff },\n bbox: { a: bbA, b: bbB, match: bbMatch, maxDiff: bbDiff },\n topology: { a: topA, b: topB, match: topoMatch },\n color: { a: colA, b: colB, match: colMatch },\n })\n\n details.push(`part \"${leafA.name}\": vol ${volA.toFixed(1)} vs ${volB.toFixed(1)} (${volDiffPct.toFixed(3)}%), com diff=${comDiff.toExponential(2)}, bbox diff=${bbDiff.toExponential(2)}, color=${colMatch}`)\n }\n\n // ── Level 4: Overall fused geometry ──\n const shapesA = leavesA.map(n => n.shapeHandle! as unknown as ShapeHandle)\n const shapesB = leavesB.map(n => n.shapeHandle! as unknown as ShapeHandle)\n const fusedA = fuseAll(kernel, shapesA)\n const fusedB = fuseAll(kernel, shapesB)\n\n let overallVolumeA = 0, overallVolumeB = 0, overallVolMatch = false, overallVolDiffPct = 0\n let overallBboxMatch = false, overallBboxDiff = 0\n let boolAB = 0, boolBA = 0, boolMatch = false\n\n if (fusedA && fusedB) {\n overallVolumeA = kernel.getVolume(fusedA)\n overallVolumeB = kernel.getVolume(fusedB)\n overallVolDiffPct = overallVolumeA > 0 ? (Math.abs(overallVolumeA - overallVolumeB) / overallVolumeA) * 100 : 0\n overallVolMatch = overallVolDiffPct <= opts.volumeRelativeTolerance * 100\n\n const fbbA = kernel.getBoundingBox(fusedA)\n const fbbB = kernel.getBoundingBox(fusedB)\n overallBboxDiff = bbmax(fbbA, fbbB)\n overallBboxMatch = overallBboxDiff <= opts.linearTolerance\n\n if (opts.skipFusedBoolean) {\n boolAB = NaN\n boolBA = NaN\n boolMatch = true\n } else {\n const cutAB = kernel.cut(fusedA, fusedB)\n const cutBA = kernel.cut(fusedB, fusedA)\n boolAB = kernel.getVolume(cutAB)\n boolBA = kernel.getVolume(cutBA)\n boolMatch = boolAB <= opts.booleanVolumeTolerance && boolBA <= opts.booleanVolumeTolerance\n kernel.release(cutAB)\n kernel.release(cutBA)\n }\n }\n\n details.push(`overall: vol ${overallVolumeA.toFixed(1)} vs ${overallVolumeB.toFixed(1)} (${overallVolDiffPct.toFixed(3)}%), bbox diff=${overallBboxDiff.toExponential(2)}, bool A-B=${boolAB.toExponential(2)}, B-A=${boolBA.toExponential(2)}`)\n\n // Cleanup\n if (fusedA) kernel.release(fusedA)\n if (fusedB) kernel.release(fusedB)\n // Note: leaf shapeHandles are owned by the assembly tree, not released here\n\n const partsAllMatch = partResults.every(p =>\n p.found && p.volume?.match && p.centerOfMass?.match && p.bbox?.match && p.topology?.match && p.color?.match\n )\n const equivalent = structureMatch && partsAllMatch && overallVolMatch && overallBboxMatch && boolMatch\n\n return {\n fileA,\n fileB,\n equivalent,\n structure: {\n leafCountA: leavesA.length,\n leafCountB: leavesB.length,\n namesA,\n namesB,\n match: structureMatch,\n missingInB,\n missingInA,\n },\n parts: partResults,\n overall: {\n volumeA: overallVolumeA,\n volumeB: overallVolumeB,\n volumeMatch: overallVolMatch,\n volumeDiffPct: overallVolDiffPct,\n bboxMatch: overallBboxMatch,\n bboxMaxDiff: overallBboxDiff,\n booleanDiff: { aMinusB: boolAB, bMinusA: boolBA, match: boolMatch },\n },\n details,\n }\n}\n\n/**\n * Print a human-readable assembly comparison report.\n * @param result - Comparison result from compareAssemblyFiles.\n */\nexport function printAssemblyReport(result: AssemblyCompareResult): void {\n console.log(`\\n=== Assembly Comparison: ${result.fileA} vs ${result.fileB} ===`)\n console.log(`Overall: ${result.equivalent ? '✓ EQUIVALENT' : '✗ DIFFERENT'}\\n`)\n\n console.log('── Level 1: Structure ──')\n console.log(` Leaves: ${result.structure.leafCountA} vs ${result.structure.leafCountB} — ${result.structure.match ? '✓' : '✗'}`)\n console.log(` Names A: [${result.structure.namesA.join(', ')}]`)\n console.log(` Names B: [${result.structure.namesB.join(', ')}]`)\n if (result.structure.missingInB.length) console.log(` ✗ Missing in B: ${result.structure.missingInB.join(', ')}`)\n if (result.structure.missingInA.length) console.log(` ✗ Missing in A: ${result.structure.missingInA.join(', ')}`)\n\n console.log('\\n── Level 2 & 3: Per-part pose + geometry ──')\n for (const p of result.parts) {\n if (!p.found) {\n console.log(` ✗ \"${p.name}\": not found in B`)\n continue\n }\n const ok = p.volume?.match && p.centerOfMass?.match && p.bbox?.match && p.color?.match\n console.log(` ${ok ? '✓' : '✗'} \"${p.name}\": vol ${p.volume?.a.toFixed(1)} vs ${p.volume?.b.toFixed(1)} (${p.volume?.diffPct.toFixed(3)}%), com diff=${p.centerOfMass?.maxDiff.toExponential(2)}, bbox diff=${p.bbox?.maxDiff.toExponential(2)}, color=${p.color?.match ? '✓' : '✗'}`)\n }\n\n console.log('\\n── Level 4: Overall fused geometry ──')\n console.log(` Volume: ${result.overall.volumeA.toFixed(1)} vs ${result.overall.volumeB.toFixed(1)} (${result.overall.volumeDiffPct.toFixed(3)}%) — ${result.overall.volumeMatch ? '✓' : '✗'}`)\n console.log(` BBox diff: ${result.overall.bboxMaxDiff.toExponential(2)} — ${result.overall.bboxMatch ? '✓' : '✗'}`)\n console.log(` Boolean A-B: ${result.overall.booleanDiff.aMinusB.toExponential(2)} mm³`)\n console.log(` Boolean B-A: ${result.overall.booleanDiff.bMinusA.toExponential(2)} mm³ — ${result.overall.booleanDiff.match ? '✓' : '✗'}`)\n console.log('')\n}\n"]}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @faicad/cq-compat-compare — STEP / assembly geometry equivalence comparers
3
+ * (dev-only tooling), split from @faicad/faijs-cadquery.
4
+ *
5
+ * This package is NOT part of any runtime dependency chain: it is consumed only
6
+ * by test harnesses, parity scripts and verification tooling. The CadQuery
7
+ * compatibility surface lives in @faicad/faijs-cadquery (workplane / 2D drawing /
8
+ * features / selectors) and @faicad/cq-compat-assembly (assembly solve API).
9
+ */
10
+ export { compareStepFiles, printCompareReport } from './step-compare.js';
11
+ export type { CompareOptions, StepCompareResult, MetricResult, TopologyStats, } from './step-compare.js';
12
+ export { compareAssemblyFiles, printAssemblyReport } from './assembly-compare.js';
13
+ export type { AssemblyCompareOptions, AssemblyCompareResult, PartCompareResult, } from './assembly-compare.js';
14
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAA;AACrE,YAAY,EACV,cAAc,EACd,iBAAiB,EACjB,YAAY,EACZ,aAAa,GACd,MAAM,gBAAgB,CAAA;AAEvB,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAA;AAC9E,YAAY,EACV,sBAAsB,EACtB,qBAAqB,EACrB,iBAAiB,GAClB,MAAM,oBAAoB,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @faicad/cq-compat-compare — STEP / assembly geometry equivalence comparers
3
+ * (dev-only tooling), split from @faicad/faijs-cadquery.
4
+ *
5
+ * This package is NOT part of any runtime dependency chain: it is consumed only
6
+ * by test harnesses, parity scripts and verification tooling. The CadQuery
7
+ * compatibility surface lives in @faicad/faijs-cadquery (workplane / 2D drawing /
8
+ * features / selectors) and @faicad/cq-compat-assembly (assembly solve API).
9
+ */
10
+ export { compareStepFiles, printCompareReport } from './step-compare.js';
11
+ export { compareAssemblyFiles, printAssemblyReport } from './assembly-compare.js';
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAA;AAQrE,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAA","sourcesContent":["/**\n * @faicad/cq-compat-compare — STEP / assembly geometry equivalence comparers\n * (dev-only tooling), split from @faicad/faijs-cadquery.\n *\n * This package is NOT part of any runtime dependency chain: it is consumed only\n * by test harnesses, parity scripts and verification tooling. The CadQuery\n * compatibility surface lives in @faicad/faijs-cadquery (workplane / 2D drawing /\n * features / selectors) and @faicad/cq-compat-assembly (assembly solve API).\n */\n\nexport { compareStepFiles, printCompareReport } from './step-compare'\nexport type {\n CompareOptions,\n StepCompareResult,\n MetricResult,\n TopologyStats,\n} from './step-compare'\n\nexport { compareAssemblyFiles, printAssemblyReport } from './assembly-compare'\nexport type {\n AssemblyCompareOptions,\n AssemblyCompareResult,\n PartCompareResult,\n} from './assembly-compare'\n"]}
@@ -0,0 +1,83 @@
1
+ /**
2
+ * STEP file equivalence comparison using BREP geometry.
3
+ *
4
+ * Compares two STEP files across five dimensions:
5
+ * 1. Bounding box
6
+ * 2. Volume
7
+ * 3. Center of mass
8
+ * 4. Topology statistics (face/edge/vertex/solid counts)
9
+ * 5. Boolean difference (A-B and B-A volumes)
10
+ *
11
+ * Usage:
12
+ * const result = await compareStepFiles('a.step', 'b.step')
13
+ * console.log(result.equivalent)
14
+ */
15
+ import type { BrepBoundingBox, BrepVec3 } from '@faicad/faijs';
16
+ /** Tolerance options for comparison. */
17
+ export interface CompareOptions {
18
+ /** Absolute tolerance for bbox / center-of-mass coordinates (mm). Default 1e-4. */
19
+ linearTolerance?: number;
20
+ /** Relative tolerance for volume comparison (0.001 = 0.1%). Default 1e-4. */
21
+ volumeRelativeTolerance?: number;
22
+ /** Absolute tolerance for boolean difference volume (mm³). Default 1e-3. */
23
+ booleanVolumeTolerance?: number;
24
+ /** Whether to require topology counts to match exactly. Default true. */
25
+ strictTopology?: boolean;
26
+ }
27
+ /** Per-metric comparison result. */
28
+ export interface MetricResult<T> {
29
+ a: T;
30
+ b: T;
31
+ match: boolean;
32
+ }
33
+ /** Topology statistics for a shape. */
34
+ export interface TopologyStats {
35
+ faces: number;
36
+ edges: number;
37
+ vertices: number;
38
+ solids: number;
39
+ }
40
+ /** Full comparison result. */
41
+ export interface StepCompareResult {
42
+ fileA: string;
43
+ fileB: string;
44
+ equivalent: boolean;
45
+ bbox: MetricResult<BrepBoundingBox> & {
46
+ maxDiff: number;
47
+ };
48
+ volume: MetricResult<number> & {
49
+ diff: number;
50
+ diffPct: number;
51
+ };
52
+ centerOfMass: MetricResult<BrepVec3> & {
53
+ maxDiff: number;
54
+ };
55
+ topology: MetricResult<TopologyStats>;
56
+ booleanDiff: {
57
+ aMinusB: {
58
+ volume: number;
59
+ nonEmpty: boolean;
60
+ };
61
+ bMinusA: {
62
+ volume: number;
63
+ nonEmpty: boolean;
64
+ };
65
+ match: boolean;
66
+ };
67
+ details: string[];
68
+ }
69
+ /**
70
+ * Compare two STEP files for geometric equivalence.
71
+ *
72
+ * @param fileA - Path to the first STEP file.
73
+ * @param fileB - Path to the second STEP file.
74
+ * @param options - Comparison tolerances.
75
+ * @returns Detailed comparison result with per-metric match status.
76
+ */
77
+ export declare function compareStepFiles(fileA: string, fileB: string, options?: CompareOptions): Promise<StepCompareResult>;
78
+ /**
79
+ * Print a human-readable comparison report to stdout.
80
+ * @param result - The comparison result from compareStepFiles.
81
+ */
82
+ export declare function printCompareReport(result: StepCompareResult): void;
83
+ //# sourceMappingURL=step-compare.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"step-compare.d.ts","sourceRoot":"","sources":["../src/step-compare.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAIH,OAAO,KAAK,EAA2B,eAAe,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAEvF,wCAAwC;AACxC,MAAM,WAAW,cAAc;IAC7B,mFAAmF;IACnF,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,6EAA6E;IAC7E,uBAAuB,CAAC,EAAE,MAAM,CAAA;IAChC,4EAA4E;IAC5E,sBAAsB,CAAC,EAAE,MAAM,CAAA;IAC/B,yEAAyE;IACzE,cAAc,CAAC,EAAE,OAAO,CAAA;CACzB;AAED,oCAAoC;AACpC,MAAM,WAAW,YAAY,CAAC,CAAC;IAC7B,CAAC,EAAE,CAAC,CAAA;IACJ,CAAC,EAAE,CAAC,CAAA;IACJ,KAAK,EAAE,OAAO,CAAA;CACf;AAED,uCAAuC;AACvC,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,MAAM,CAAA;IACb,KAAK,EAAE,MAAM,CAAA;IACb,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;CACf;AAED,8BAA8B;AAC9B,MAAM,WAAW,iBAAiB;IAChC,KAAK,EAAE,MAAM,CAAA;IACb,KAAK,EAAE,MAAM,CAAA;IACb,UAAU,EAAE,OAAO,CAAA;IACnB,IAAI,EAAE,YAAY,CAAC,eAAe,CAAC,GAAG;QAAE,OAAO,EAAE,MAAM,CAAA;KAAE,CAAA;IACzD,MAAM,EAAE,YAAY,CAAC,MAAM,CAAC,GAAG;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAA;IAChE,YAAY,EAAE,YAAY,CAAC,QAAQ,CAAC,GAAG;QAAE,OAAO,EAAE,MAAM,CAAA;KAAE,CAAA;IAC1D,QAAQ,EAAE,YAAY,CAAC,aAAa,CAAC,CAAA;IACrC,WAAW,EAAE;QACX,OAAO,EAAE;YAAE,MAAM,EAAE,MAAM,CAAC;YAAC,QAAQ,EAAE,OAAO,CAAA;SAAE,CAAA;QAC9C,OAAO,EAAE;YAAE,MAAM,EAAE,MAAM,CAAC;YAAC,QAAQ,EAAE,OAAO,CAAA;SAAE,CAAA;QAC9C,KAAK,EAAE,OAAO,CAAA;KACf,CAAA;IACD,OAAO,EAAE,MAAM,EAAE,CAAA;CAClB;AAqCD;;;;;;;GAOG;AACH,wBAAsB,gBAAgB,CACpC,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,OAAO,GAAE,cAAmB,GAC3B,OAAO,CAAC,iBAAiB,CAAC,CA6F5B;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,iBAAiB,GAAG,IAAI,CAclE"}
@@ -0,0 +1,158 @@
1
+ /**
2
+ * STEP file equivalence comparison using BREP geometry.
3
+ *
4
+ * Compares two STEP files across five dimensions:
5
+ * 1. Bounding box
6
+ * 2. Volume
7
+ * 3. Center of mass
8
+ * 4. Topology statistics (face/edge/vertex/solid counts)
9
+ * 5. Boolean difference (A-B and B-A volumes)
10
+ *
11
+ * Usage:
12
+ * const result = await compareStepFiles('a.step', 'b.step')
13
+ * console.log(result.equivalent)
14
+ */
15
+ import { readFileSync } from 'node:fs';
16
+ import { initOcctWasm } from '@faicad/faijs';
17
+ const DEFAULT_OPTIONS = {
18
+ linearTolerance: 1e-4,
19
+ volumeRelativeTolerance: 1e-4,
20
+ booleanVolumeTolerance: 1e-3,
21
+ strictTopology: true,
22
+ };
23
+ function bboxMaxDiff(a, b) {
24
+ return Math.max(Math.abs(a.xmin - b.xmin), Math.abs(a.xmax - b.xmax), Math.abs(a.ymin - b.ymin), Math.abs(a.ymax - b.ymax), Math.abs(a.zmin - b.zmin), Math.abs(a.zmax - b.zmax));
25
+ }
26
+ function comMaxDiff(a, b) {
27
+ return Math.max(Math.abs(a.x - b.x), Math.abs(a.y - b.y), Math.abs(a.z - b.z));
28
+ }
29
+ function getTopologyStats(kernel, shape) {
30
+ return {
31
+ faces: kernel.getSubShapes(shape, 'face').length,
32
+ edges: kernel.getSubShapes(shape, 'edge').length,
33
+ vertices: kernel.getSubShapes(shape, 'vertex').length,
34
+ solids: kernel.getSubShapes(shape, 'solid').length,
35
+ };
36
+ }
37
+ function topologyMatch(a, b, strict) {
38
+ if (strict) {
39
+ return a.faces === b.faces && a.edges === b.edges && a.vertices === b.vertices && a.solids === b.solids;
40
+ }
41
+ return a.solids === b.solids;
42
+ }
43
+ /**
44
+ * Compare two STEP files for geometric equivalence.
45
+ *
46
+ * @param fileA - Path to the first STEP file.
47
+ * @param fileB - Path to the second STEP file.
48
+ * @param options - Comparison tolerances.
49
+ * @returns Detailed comparison result with per-metric match status.
50
+ */
51
+ export async function compareStepFiles(fileA, fileB, options = {}) {
52
+ const opts = { ...DEFAULT_OPTIONS, ...options };
53
+ const details = [];
54
+ const kernel = await initOcctWasm();
55
+ const bufA = readFileSync(fileA);
56
+ const bufB = readFileSync(fileB);
57
+ // readFileSync returns pooled Buffers for small files: buf.buffer is the
58
+ // whole 8KB pool (with garbage beyond byteLength), which makes importStep
59
+ // fail on every STEP < ~4KB (e.g. single-sphere files). Pass an exact copy.
60
+ const exact = (buf) => buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
61
+ const shapeA = kernel.importStep(exact(bufA));
62
+ const shapeB = kernel.importStep(exact(bufB));
63
+ // 1. Bounding box
64
+ const bboxA = kernel.getBoundingBox(shapeA);
65
+ const bboxB = kernel.getBoundingBox(shapeB);
66
+ const bboxDiff = bboxMaxDiff(bboxA, bboxB);
67
+ const bboxMatch = bboxDiff <= opts.linearTolerance;
68
+ details.push(`bbox diff: ${bboxDiff.toExponential(3)} mm (tol ${opts.linearTolerance})`);
69
+ // 2. Topology (needed to decide whether volume/COM/boolean are meaningful)
70
+ const topoA = getTopologyStats(kernel, shapeA);
71
+ const topoB = getTopologyStats(kernel, shapeB);
72
+ const topoMatch = topologyMatch(topoA, topoB, opts.strictTopology);
73
+ details.push(`topology: A(f=${topoA.faces},e=${topoA.edges},v=${topoA.vertices},s=${topoA.solids}) B(f=${topoB.faces},e=${topoB.edges},v=${topoB.vertices},s=${topoB.solids})`);
74
+ // 3. Volume / COM / boolean difference: only meaningful when BOTH shapes
75
+ // contain solids or faces (e.g. `siblings(..., "Vertex", ...)` yields a
76
+ // pure edges compound; BRepGProp volume / BRepAlgoAPI_Cut throw on those).
77
+ const hasMass = (topoA.solids > 0 || topoA.faces > 0) && (topoB.solids > 0 || topoB.faces > 0);
78
+ let volA = 0;
79
+ let volB = 0;
80
+ let volDiff = 0;
81
+ let volPct = 0;
82
+ let volMatch = true;
83
+ let comA = { x: 0, y: 0, z: 0 };
84
+ let comB = { x: 0, y: 0, z: 0 };
85
+ let comDiff = 0;
86
+ let comMatch = true;
87
+ let volAB = 0;
88
+ let volBA = 0;
89
+ let boolMatch = true;
90
+ if (hasMass) {
91
+ volA = kernel.getVolume(shapeA);
92
+ volB = kernel.getVolume(shapeB);
93
+ volDiff = Math.abs(volA - volB);
94
+ volPct = volA > 0 ? (volDiff / volA) * 100 : 0;
95
+ volMatch = volPct <= opts.volumeRelativeTolerance * 100;
96
+ details.push(`volume diff: ${volDiff.toExponential(3)} mm³ (${volPct.toFixed(4)}%, tol ${opts.volumeRelativeTolerance * 100}%)`);
97
+ comA = kernel.getCenterOfMass(shapeA);
98
+ comB = kernel.getCenterOfMass(shapeB);
99
+ comDiff = comMaxDiff(comA, comB);
100
+ comMatch = comDiff <= opts.linearTolerance;
101
+ details.push(`center-of-mass diff: ${comDiff.toExponential(3)} mm (tol ${opts.linearTolerance})`);
102
+ const aMinusB = kernel.cut(shapeA, shapeB);
103
+ const bMinusA = kernel.cut(shapeB, shapeA);
104
+ volAB = kernel.getVolume(aMinusB);
105
+ volBA = kernel.getVolume(bMinusA);
106
+ boolMatch = volAB <= opts.booleanVolumeTolerance && volBA <= opts.booleanVolumeTolerance;
107
+ details.push(`boolean diff: A-B=${volAB.toExponential(3)} mm³, B-A=${volBA.toExponential(3)} mm³ (tol ${opts.booleanVolumeTolerance})`);
108
+ kernel.release(aMinusB);
109
+ kernel.release(bMinusA);
110
+ }
111
+ else {
112
+ details.push('volume/COM/boolean: skipped (no solid or face topology in either shape)');
113
+ }
114
+ // Cleanup
115
+ kernel.release(shapeA);
116
+ kernel.release(shapeB);
117
+ const equivalent = bboxMatch && volMatch && comMatch && topoMatch && boolMatch;
118
+ return {
119
+ fileA,
120
+ fileB,
121
+ equivalent,
122
+ bbox: { a: bboxA, b: bboxB, match: bboxMatch, maxDiff: bboxDiff },
123
+ volume: { a: volA, b: volB, match: volMatch, diff: volDiff, diffPct: volPct },
124
+ centerOfMass: { a: comA, b: comB, match: comMatch, maxDiff: comDiff },
125
+ topology: { a: topoA, b: topoB, match: topoMatch },
126
+ booleanDiff: {
127
+ aMinusB: { volume: volAB, nonEmpty: volAB > opts.booleanVolumeTolerance },
128
+ bMinusA: { volume: volBA, nonEmpty: volBA > opts.booleanVolumeTolerance },
129
+ match: boolMatch,
130
+ },
131
+ details,
132
+ };
133
+ }
134
+ /**
135
+ * Print a human-readable comparison report to stdout.
136
+ * @param result - The comparison result from compareStepFiles.
137
+ */
138
+ export function printCompareReport(result) {
139
+ console.log(`\n=== STEP Comparison: ${result.fileA} vs ${result.fileB} ===`);
140
+ console.log(`Overall: ${result.equivalent ? '✓ EQUIVALENT' : '✗ DIFFERENT'}\n`);
141
+ for (const d of result.details) {
142
+ console.log(` ${d}`);
143
+ }
144
+ console.log('');
145
+ if (!result.equivalent) {
146
+ if (!result.bbox.match)
147
+ console.log(' ✗ Bounding box mismatch');
148
+ if (!result.volume.match)
149
+ console.log(' ✗ Volume mismatch');
150
+ if (!result.centerOfMass.match)
151
+ console.log(' ✗ Center of mass mismatch');
152
+ if (!result.topology.match)
153
+ console.log(' ✗ Topology mismatch');
154
+ if (!result.booleanDiff.match)
155
+ console.log(' ✗ Boolean difference non-empty');
156
+ }
157
+ }
158
+ //# sourceMappingURL=step-compare.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"step-compare.js","sourceRoot":"","sources":["../src/step-compare.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AACtC,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAA;AA+C5C,MAAM,eAAe,GAA6B;IAChD,eAAe,EAAE,IAAI;IACrB,uBAAuB,EAAE,IAAI;IAC7B,sBAAsB,EAAE,IAAI;IAC5B,cAAc,EAAE,IAAI;CACrB,CAAA;AAED,SAAS,WAAW,CAAC,CAAkB,EAAE,CAAkB;IACzD,OAAO,IAAI,CAAC,GAAG,CACb,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,EACpD,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,EACpD,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IA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K,GAAG,IAAI,CAAC,sBAAsB,EAAE;YACzE,KAAK,EAAE,SAAS;SACjB;QACD,OAAO;KACR,CAAA;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CAAC,MAAyB;IAC1D,OAAO,CAAC,GAAG,CAAC,0BAA0B,MAAM,CAAC,KAAK,OAAO,MAAM,CAAC,KAAK,MAAM,CAAC,CAAA;IAC5E,OAAO,CAAC,GAAG,CAAC,YAAY,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,aAAa,IAAI,CAAC,CAAA;IAC/E,KAAK,MAAM,CAAC,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;QAC/B,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;IACvB,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;IACf,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;QACvB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK;YAAE,OAAO,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAA;QAChE,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK;YAAE,OAAO,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAA;QAC5D,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,KAAK;YAAE,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAA;QAC1E,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK;YAAE,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAA;QAChE,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,KAAK;YAAE,OAAO,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAA;IAChF,CAAC;AACH,CAAC","sourcesContent":["/**\n * STEP file equivalence comparison using BREP geometry.\n *\n * Compares two STEP files across five dimensions:\n * 1. Bounding box\n * 2. Volume\n * 3. Center of mass\n * 4. Topology statistics (face/edge/vertex/solid counts)\n * 5. Boolean difference (A-B and B-A volumes)\n *\n * Usage:\n * const result = await compareStepFiles('a.step', 'b.step')\n * console.log(result.equivalent)\n */\n\nimport { readFileSync } from 'node:fs'\nimport { initOcctWasm } from '@faicad/faijs'\nimport type { OcctKernel, ShapeHandle, BrepBoundingBox, BrepVec3 } from '@faicad/faijs'\n\n/** Tolerance options for comparison. */\nexport interface CompareOptions {\n /** Absolute tolerance for bbox / center-of-mass coordinates (mm). Default 1e-4. */\n linearTolerance?: number\n /** Relative tolerance for volume comparison (0.001 = 0.1%). Default 1e-4. */\n volumeRelativeTolerance?: number\n /** Absolute tolerance for boolean difference volume (mm³). Default 1e-3. */\n booleanVolumeTolerance?: number\n /** Whether to require topology counts to match exactly. Default true. */\n strictTopology?: boolean\n}\n\n/** Per-metric comparison result. */\nexport interface MetricResult<T> {\n a: T\n b: T\n match: boolean\n}\n\n/** Topology statistics for a shape. */\nexport interface TopologyStats {\n faces: number\n edges: number\n vertices: number\n solids: number\n}\n\n/** Full comparison result. */\nexport interface StepCompareResult {\n fileA: string\n fileB: string\n equivalent: boolean\n bbox: MetricResult<BrepBoundingBox> & { maxDiff: number }\n volume: MetricResult<number> & { diff: number; diffPct: number }\n centerOfMass: MetricResult<BrepVec3> & { maxDiff: number }\n topology: MetricResult<TopologyStats>\n booleanDiff: {\n aMinusB: { volume: number; nonEmpty: boolean }\n bMinusA: { volume: number; nonEmpty: boolean }\n match: boolean\n }\n details: string[]\n}\n\nconst DEFAULT_OPTIONS: Required<CompareOptions> = {\n linearTolerance: 1e-4,\n volumeRelativeTolerance: 1e-4,\n booleanVolumeTolerance: 1e-3,\n strictTopology: true,\n}\n\nfunction bboxMaxDiff(a: BrepBoundingBox, b: BrepBoundingBox): number {\n return Math.max(\n Math.abs(a.xmin - b.xmin), Math.abs(a.xmax - b.xmax),\n Math.abs(a.ymin - b.ymin), Math.abs(a.ymax - b.ymax),\n Math.abs(a.zmin - b.zmin), Math.abs(a.zmax - b.zmax),\n )\n}\n\nfunction comMaxDiff(a: BrepVec3, b: BrepVec3): number {\n return Math.max(Math.abs(a.x - b.x), Math.abs(a.y - b.y), Math.abs(a.z - b.z))\n}\n\nfunction getTopologyStats(kernel: OcctKernel, shape: ShapeHandle): TopologyStats {\n return {\n faces: kernel.getSubShapes(shape, 'face').length,\n edges: kernel.getSubShapes(shape, 'edge').length,\n vertices: kernel.getSubShapes(shape, 'vertex').length,\n solids: kernel.getSubShapes(shape, 'solid').length,\n }\n}\n\nfunction topologyMatch(a: TopologyStats, b: TopologyStats, strict: boolean): boolean {\n if (strict) {\n return a.faces === b.faces && a.edges === b.edges && a.vertices === b.vertices && a.solids === b.solids\n }\n return a.solids === b.solids\n}\n\n/**\n * Compare two STEP files for geometric equivalence.\n *\n * @param fileA - Path to the first STEP file.\n * @param fileB - Path to the second STEP file.\n * @param options - Comparison tolerances.\n * @returns Detailed comparison result with per-metric match status.\n */\nexport async function compareStepFiles(\n fileA: string,\n fileB: string,\n options: CompareOptions = {},\n): Promise<StepCompareResult> {\n const opts = { ...DEFAULT_OPTIONS, ...options }\n const details: string[] = []\n\n const kernel = await initOcctWasm()\n\n const bufA = readFileSync(fileA)\n const bufB = readFileSync(fileB)\n // readFileSync returns pooled Buffers for small files: buf.buffer is the\n // whole 8KB pool (with garbage beyond byteLength), which makes importStep\n // fail on every STEP < ~4KB (e.g. single-sphere files). Pass an exact copy.\n const exact = (buf: Buffer): ArrayBuffer =>\n buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) as ArrayBuffer\n const shapeA = kernel.importStep(exact(bufA))\n const shapeB = kernel.importStep(exact(bufB))\n\n // 1. Bounding box\n const bboxA = kernel.getBoundingBox(shapeA)\n const bboxB = kernel.getBoundingBox(shapeB)\n const bboxDiff = bboxMaxDiff(bboxA, bboxB)\n const bboxMatch = bboxDiff <= opts.linearTolerance\n details.push(`bbox diff: ${bboxDiff.toExponential(3)} mm (tol ${opts.linearTolerance})`)\n\n // 2. Topology (needed to decide whether volume/COM/boolean are meaningful)\n const topoA = getTopologyStats(kernel, shapeA)\n const topoB = getTopologyStats(kernel, shapeB)\n const topoMatch = topologyMatch(topoA, topoB, opts.strictTopology)\n details.push(`topology: A(f=${topoA.faces},e=${topoA.edges},v=${topoA.vertices},s=${topoA.solids}) B(f=${topoB.faces},e=${topoB.edges},v=${topoB.vertices},s=${topoB.solids})`)\n\n // 3. Volume / COM / boolean difference: only meaningful when BOTH shapes\n // contain solids or faces (e.g. `siblings(..., \"Vertex\", ...)` yields a\n // pure edges compound; BRepGProp volume / BRepAlgoAPI_Cut throw on those).\n const hasMass =\n (topoA.solids > 0 || topoA.faces > 0) && (topoB.solids > 0 || topoB.faces > 0)\n let volA = 0\n let volB = 0\n let volDiff = 0\n let volPct = 0\n let volMatch = true\n let comA: BrepVec3 = { x: 0, y: 0, z: 0 }\n let comB: BrepVec3 = { x: 0, y: 0, z: 0 }\n let comDiff = 0\n let comMatch = true\n let volAB = 0\n let volBA = 0\n let boolMatch = true\n if (hasMass) {\n volA = kernel.getVolume(shapeA)\n volB = kernel.getVolume(shapeB)\n volDiff = Math.abs(volA - volB)\n volPct = volA > 0 ? (volDiff / volA) * 100 : 0\n volMatch = volPct <= opts.volumeRelativeTolerance * 100\n details.push(`volume diff: ${volDiff.toExponential(3)} mm³ (${volPct.toFixed(4)}%, tol ${opts.volumeRelativeTolerance * 100}%)`)\n\n comA = kernel.getCenterOfMass(shapeA)\n comB = kernel.getCenterOfMass(shapeB)\n comDiff = comMaxDiff(comA, comB)\n comMatch = comDiff <= opts.linearTolerance\n details.push(`center-of-mass diff: ${comDiff.toExponential(3)} mm (tol ${opts.linearTolerance})`)\n\n const aMinusB = kernel.cut(shapeA, shapeB)\n const bMinusA = kernel.cut(shapeB, shapeA)\n volAB = kernel.getVolume(aMinusB)\n volBA = kernel.getVolume(bMinusA)\n boolMatch = volAB <= opts.booleanVolumeTolerance && volBA <= opts.booleanVolumeTolerance\n details.push(`boolean diff: A-B=${volAB.toExponential(3)} mm³, B-A=${volBA.toExponential(3)} mm³ (tol ${opts.booleanVolumeTolerance})`)\n kernel.release(aMinusB)\n kernel.release(bMinusA)\n } else {\n details.push('volume/COM/boolean: skipped (no solid or face topology in either shape)')\n }\n\n // Cleanup\n kernel.release(shapeA)\n kernel.release(shapeB)\n\n const equivalent = bboxMatch && volMatch && comMatch && topoMatch && boolMatch\n\n return {\n fileA,\n fileB,\n equivalent,\n bbox: { a: bboxA, b: bboxB, match: bboxMatch, maxDiff: bboxDiff },\n volume: { a: volA, b: volB, match: volMatch, diff: volDiff, diffPct: volPct },\n centerOfMass: { a: comA, b: comB, match: comMatch, maxDiff: comDiff },\n topology: { a: topoA, b: topoB, match: topoMatch },\n booleanDiff: {\n aMinusB: { volume: volAB, nonEmpty: volAB > opts.booleanVolumeTolerance },\n bMinusA: { volume: volBA, nonEmpty: volBA > opts.booleanVolumeTolerance },\n match: boolMatch,\n },\n details,\n }\n}\n\n/**\n * Print a human-readable comparison report to stdout.\n * @param result - The comparison result from compareStepFiles.\n */\nexport function printCompareReport(result: StepCompareResult): void {\n console.log(`\\n=== STEP Comparison: ${result.fileA} vs ${result.fileB} ===`)\n console.log(`Overall: ${result.equivalent ? '✓ EQUIVALENT' : '✗ DIFFERENT'}\\n`)\n for (const d of result.details) {\n console.log(` ${d}`)\n }\n console.log('')\n if (!result.equivalent) {\n if (!result.bbox.match) console.log(' ✗ Bounding box mismatch')\n if (!result.volume.match) console.log(' ✗ Volume mismatch')\n if (!result.centerOfMass.match) console.log(' ✗ Center of mass mismatch')\n if (!result.topology.match) console.log(' ✗ Topology mismatch')\n if (!result.booleanDiff.match) console.log(' ✗ Boolean difference non-empty')\n }\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@faicad/cq-compat-compare",
3
+ "version": "0.29.5",
4
+ "type": "module",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://gitcode.com/Faicad/faijs.git"
9
+ },
10
+ "description": "STEP / assembly geometry equivalence comparers (dev-only) - split from @faicad/faijs-cadquery",
11
+ "keywords": [
12
+ "cad",
13
+ "faijs",
14
+ "cadquery",
15
+ "step",
16
+ "compare",
17
+ "testing"
18
+ ],
19
+ "main": "./dist/index.js",
20
+ "types": "./dist/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/index.d.ts",
24
+ "default": "./dist/index.js"
25
+ }
26
+ },
27
+ "files": [
28
+ "dist"
29
+ ],
30
+ "faijs": {
31
+ "autoLift": false
32
+ },
33
+ "dependencies": {},
34
+ "peerDependencies": {
35
+ "@faicad/faijs": "^0.29.0",
36
+ "occt-wasm": "^5.6.0"
37
+ },
38
+ "devDependencies": {
39
+ "@faicad/faijs": "file:../core",
40
+ "typescript": "*",
41
+ "vitest": "*"
42
+ },
43
+ "scripts": {
44
+ "build": "tsc -p tsconfig.build.json && node ../../scripts/fix-import-extensions.mjs dist",
45
+ "typecheck": "tsc --noEmit",
46
+ "pretest": "npm run build",
47
+ "test": "vitest run",
48
+ "lint": "eslint src"
49
+ }
50
+ }