@metamesh/modeling 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/CHANGELOG.md +105 -0
  2. package/LICENSE +200 -0
  3. package/README.md +314 -2
  4. package/THIRD_PARTY_NOTICES.md +153 -0
  5. package/dist/api/engine.d.ts +54 -0
  6. package/dist/api/geometry.d.ts +2912 -0
  7. package/dist/api/index.d.ts +1648 -0
  8. package/dist/api/text.d.ts +77 -0
  9. package/dist/engine/construction-operations.js +189 -0
  10. package/dist/engine/execution.js +227 -0
  11. package/dist/engine/export-3mf.js +100 -0
  12. package/dist/engine/extrusion-finishing.js +82 -0
  13. package/dist/engine/finalization.js +214 -0
  14. package/dist/engine/index.js +72 -0
  15. package/dist/engine/inspection-operations.js +52 -0
  16. package/dist/engine/kernel/LICENSE +201 -0
  17. package/dist/engine/kernel/manifold.js +2 -0
  18. package/dist/engine/kernel/manifold.wasm +0 -0
  19. package/dist/engine/loft-operations.js +156 -0
  20. package/dist/engine/mechanical-operations.js +51 -0
  21. package/dist/engine/modeling-context.js +38 -0
  22. package/dist/engine/native/adapter.js +20 -0
  23. package/dist/engine/native/context.js +209 -0
  24. package/dist/engine/native/copied-views.js +46 -0
  25. package/dist/engine/native/index.js +13 -0
  26. package/dist/engine/native/operations.js +115 -0
  27. package/dist/engine/native/ownership.js +98 -0
  28. package/dist/engine/native/regions.js +138 -0
  29. package/dist/engine/native/scoped-primitives.js +127 -0
  30. package/dist/engine/native/scoped-threads.js +34 -0
  31. package/dist/engine/native/threads.js +52 -0
  32. package/dist/engine/native/transforms.js +111 -0
  33. package/dist/engine/operation-environment.js +20 -0
  34. package/dist/engine/pattern-operations.js +36 -0
  35. package/dist/engine/pattern-placements.js +176 -0
  36. package/dist/engine/primitive-anchors.js +70 -0
  37. package/dist/engine/primitive-correspondence.js +74 -0
  38. package/dist/engine/primitive-operations.js +151 -0
  39. package/dist/engine/primitive-profile-types.js +1 -0
  40. package/dist/engine/primitive-profiles.js +250 -0
  41. package/dist/engine/profile-mesh.js +279 -0
  42. package/dist/engine/section-operations.js +93 -0
  43. package/dist/engine/shape-anchors.js +88 -0
  44. package/dist/engine/transform-operations.js +225 -0
  45. package/dist/engine/types.js +1 -0
  46. package/dist/geometry/anchors.js +226 -0
  47. package/dist/geometry/curves/evaluation.js +162 -0
  48. package/dist/geometry/curves/sampling.js +265 -0
  49. package/dist/geometry/curves/types.js +1 -0
  50. package/dist/geometry/cylinder.js +117 -0
  51. package/dist/geometry/edge-finishing.js +160 -0
  52. package/dist/geometry/errors.js +76 -0
  53. package/dist/geometry/extrusion.js +150 -0
  54. package/dist/geometry/heightfield.js +107 -0
  55. package/dist/geometry/index.js +42 -0
  56. package/dist/geometry/loft-correspondence.js +204 -0
  57. package/dist/geometry/loft-geometry.js +184 -0
  58. package/dist/geometry/loft-options.js +56 -0
  59. package/dist/geometry/loft-simple-mesh.js +92 -0
  60. package/dist/geometry/loft-triangulation.js +64 -0
  61. package/dist/geometry/loft.js +80 -0
  62. package/dist/geometry/math/vector3.js +41 -0
  63. package/dist/geometry/mechanical/gear-motion.js +94 -0
  64. package/dist/geometry/mechanical/gears.js +484 -0
  65. package/dist/geometry/mechanical/index.js +13 -0
  66. package/dist/geometry/mechanical/standards.js +67 -0
  67. package/dist/geometry/mechanical/thread-helices.js +44 -0
  68. package/dist/geometry/mechanical/thread-mesh-plan.js +358 -0
  69. package/dist/geometry/mechanical/thread-mesh.js +142 -0
  70. package/dist/geometry/mechanical/thread-profiles.js +368 -0
  71. package/dist/geometry/mechanical/thread-solids.js +230 -0
  72. package/dist/geometry/mechanical/thread-surface.js +433 -0
  73. package/dist/geometry/mechanical/threads.js +138 -0
  74. package/dist/geometry/mesh-planar.js +408 -0
  75. package/dist/geometry/mesh-quality.js +396 -0
  76. package/dist/geometry/mesh-signature.js +137 -0
  77. package/dist/geometry/mesh.js +300 -0
  78. package/dist/geometry/model-limits.js +50 -0
  79. package/dist/geometry/numeric.js +11 -0
  80. package/dist/geometry/paths/frames.js +118 -0
  81. package/dist/geometry/paths/helix.js +49 -0
  82. package/dist/geometry/paths/path.js +30 -0
  83. package/dist/geometry/paths/planar.js +135 -0
  84. package/dist/geometry/paths/resampling.js +124 -0
  85. package/dist/geometry/polygon-clipping.js +52 -0
  86. package/dist/geometry/primitive-options.js +1 -0
  87. package/dist/geometry/primitive-resolution.js +17 -0
  88. package/dist/geometry/primitive-resolvers.js +235 -0
  89. package/dist/geometry/profiles/matched.js +184 -0
  90. package/dist/geometry/profiles/open-profile.js +137 -0
  91. package/dist/geometry/profiles/profiles.js +70 -0
  92. package/dist/geometry/profiles/rectangle.js +235 -0
  93. package/dist/geometry/profiles/shapes.js +34 -0
  94. package/dist/geometry/profiles/span-sampling.js +28 -0
  95. package/dist/geometry/profiles/types.js +1 -0
  96. package/dist/geometry/profiles/validation.js +20 -0
  97. package/dist/geometry/regions.js +371 -0
  98. package/dist/geometry/resolution.js +236 -0
  99. package/dist/geometry/revolve/revolve-mesh.js +123 -0
  100. package/dist/geometry/sampling-limits.js +29 -0
  101. package/dist/geometry/stroke-path.js +181 -0
  102. package/dist/geometry/svg/errors.js +23 -0
  103. package/dist/geometry/svg/fill.js +172 -0
  104. package/dist/geometry/svg/index.js +1 -0
  105. package/dist/geometry/svg/matrix.js +130 -0
  106. package/dist/geometry/svg/parser.js +536 -0
  107. package/dist/geometry/svg/path.js +349 -0
  108. package/dist/geometry/svg/types.js +1 -0
  109. package/dist/geometry/svg-import.js +662 -0
  110. package/dist/geometry/sweeps/options.js +28 -0
  111. package/dist/geometry/sweeps/orientation.js +106 -0
  112. package/dist/geometry/sweeps/stations.js +161 -0
  113. package/dist/geometry/sweeps/sweep-closed.js +96 -0
  114. package/dist/geometry/sweeps/sweep-mesh.js +20 -0
  115. package/dist/geometry/sweeps/sweep-open.js +76 -0
  116. package/dist/geometry/sweeps/validation.js +116 -0
  117. package/dist/geometry/text-contours.js +32 -0
  118. package/dist/geometry/text-layout.js +1 -0
  119. package/dist/geometry/tolerance.js +53 -0
  120. package/dist/geometry/transform-geometry.js +41 -0
  121. package/dist/geometry/transform3.js +340 -0
  122. package/dist/geometry/types.js +1 -0
  123. package/dist/index.js +1 -0
  124. package/dist/model/execution-binding.js +30 -0
  125. package/dist/model/operations.js +152 -0
  126. package/dist/model/options.js +1 -0
  127. package/dist/model/types.js +1 -0
  128. package/dist/text/index.js +48 -0
  129. package/dist/text/vector-text-layout.js +279 -0
  130. package/package.json +100 -3
@@ -0,0 +1,82 @@
1
+ import { edgeTreatmentPointCount, edgeTreatmentSetbacks, sampleEdgeTreatment, } from "../geometry/edge-finishing.js";
2
+ import { GeometryError } from "../geometry/errors.js";
3
+ import { resolveExtrusionControls } from "../geometry/extrusion.js";
4
+ import { assertMeshAllocationWithinLimits } from "../geometry/model-limits.js";
5
+ import { assertSamplingCount } from "../geometry/sampling-limits.js";
6
+ import { buildProfileLoftMesh } from "./profile-mesh.js";
7
+ const fail = (message) => {
8
+ throw new GeometryError("INVALID_ARGUMENT", message, { operation: "extrude" });
9
+ };
10
+ /** Finishes inward convex extrusion rims with exact parallel-edge offsets and retained correspondence. */
11
+ export function buildFinishedExtrusion(module, profile, options) {
12
+ const controls = resolveExtrusionControls(options.height, options, "extrude");
13
+ if (controls.twistDegrees !== 0 ||
14
+ controls.scales.some((scale) => scale !== 1) ||
15
+ options.divisions !== undefined)
16
+ fail("End treatments require a straight extrusion without twist, top scaling or divisions.");
17
+ if (typeof options.ends !== "object" || options.ends === null || Array.isArray(options.ends))
18
+ fail("ends must be an object.");
19
+ if (profile.components.length !== 1 || profile.components[0].holes.length !== 0)
20
+ fail("End treatments require one convex contour without holes; use explicit loft profiles for other topology.");
21
+ const contour = profile.components[0].outer, points = contour.points;
22
+ const edges = points.map((point, index) => {
23
+ const next = points[(index + 1) % points.length], dx = next[0] - point[0], dy = next[1] - point[1];
24
+ const length = Math.hypot(dx, dy);
25
+ if (!(length > 0) || !Number.isFinite(length))
26
+ fail("End treatment contours must have distinct finite vertices.");
27
+ return [dx / length, dy / length];
28
+ });
29
+ const miters = edges.map((edge, index) => {
30
+ const previous = edges[(index + edges.length - 1) % edges.length];
31
+ const turn = previous[0] * edge[1] - previous[1] * edge[0];
32
+ if (!(turn > 1e-12))
33
+ fail("End treatments require a strictly convex counterclockwise contour without collinear vertices.");
34
+ const denominator = 1 + previous[0] * edge[0] + previous[1] * edge[1];
35
+ return [(-previous[1] - edge[1]) / denominator, (previous[0] + edge[0]) / denominator];
36
+ });
37
+ const magnification = miters.reduce((maximum, [x, y]) => Math.max(maximum, Math.hypot(x, y)), 1);
38
+ const sampling = {
39
+ resolution: options.resolution,
40
+ limits: options.limits,
41
+ magnification,
42
+ };
43
+ const bottom = options.ends.bottom, top = options.ends.top;
44
+ const bottomSize = bottom === undefined
45
+ ? [0, 0]
46
+ : edgeTreatmentSetbacks(bottom, "extrude", Math.PI / 2, options.limits);
47
+ const topSize = top === undefined ? [0, 0] : edgeTreatmentSetbacks(top, "extrude", Math.PI / 2, options.limits);
48
+ if (bottomSize[1] + topSize[1] >= options.height)
49
+ fail("End treatments must leave positive length between their side setbacks.");
50
+ const rowCount = (bottom === undefined ? 1 : edgeTreatmentPointCount(bottom, "extrude", sampling)) +
51
+ (top === undefined ? 1 : edgeTreatmentPointCount(top, "extrude", sampling));
52
+ assertSamplingCount(rowCount, "extrude", options.limits.maxPathPoints);
53
+ const vertexCount = rowCount * points.length, triangleCount = 2 * vertexCount - 4;
54
+ assertMeshAllocationWithinLimits(vertexCount, triangleCount, 12 * (vertexCount + triangleCount), "extrude", options.limits);
55
+ const bottomPoints = bottom === undefined ? [[0, 0]] : sampleEdgeTreatment(bottom, "extrude", sampling);
56
+ const topPoints = top === undefined ? [[0, 0]] : sampleEdgeTreatment(top, "extrude", sampling);
57
+ const rows = [
58
+ ...bottomPoints.map(([inset, depth]) => ({ inset, z: depth })),
59
+ ...[...topPoints].reverse().map(([inset, depth]) => ({ inset, z: options.height - depth })),
60
+ ];
61
+ const offset = (inset) => {
62
+ const result = points.map(([x, y], index) => [
63
+ x + miters[index][0] * inset,
64
+ y + miters[index][1] * inset,
65
+ ]);
66
+ for (let index = 0; index < result.length; index++) {
67
+ const point = result[index], next = result[(index + 1) % result.length], edge = edges[index];
68
+ if (!point.every(Number.isFinite) ||
69
+ !((next[0] - point[0]) * edge[0] + (next[1] - point[1]) * edge[1] > 0))
70
+ fail("End treatment inset collapses or reverses a contour edge.");
71
+ }
72
+ return result;
73
+ };
74
+ offset(Math.max(bottomSize[0], topSize[0])); // fit fails before allocating the full station family
75
+ const stations = rows.map(({ inset, z }) => ({
76
+ z: controls.center ? z - options.height / 2 : z,
77
+ profile: {
78
+ components: [{ ...profile.components[0], outer: { ...contour, points: offset(inset) } }],
79
+ },
80
+ }));
81
+ return buildProfileLoftMesh(module, stations, options.limits);
82
+ }
@@ -0,0 +1,214 @@
1
+ import { GeometryError } from "../geometry/errors.js";
2
+ import { optimizePlanarPatches } from "../geometry/mesh-planar.js";
3
+ import { analyzeTriangleMesh } from "../geometry/mesh.js";
4
+ import { copiedMeshViews, copiedUint32Array } from "./native/copied-views.js";
5
+ const isArray = (value) => Array.isArray(value);
6
+ function finalPartTotals(parts) {
7
+ const buffers = new Set();
8
+ let vertices = 0, triangles = 0, bytes = 0, volumeMm3 = 0;
9
+ for (const part of parts) {
10
+ vertices += part.measurements.vertexCount;
11
+ triangles += part.measurements.triangleCount;
12
+ volumeMm3 += part.measurements.signedVolume;
13
+ for (const buffer of [part.positions.buffer, part.indices.buffer]) {
14
+ if (!buffers.has(buffer)) {
15
+ buffers.add(buffer);
16
+ bytes += buffer.byteLength;
17
+ }
18
+ }
19
+ }
20
+ return { vertices, triangles, bytes, volumeMm3 };
21
+ }
22
+ function fitsLimits(totals, limits) {
23
+ return (totals.vertices <= limits.maxVertices &&
24
+ totals.triangles <= limits.maxTriangles &&
25
+ totals.bytes <= limits.maxBytes);
26
+ }
27
+ /** Finalizes one complete build under the selected limits, preserving usable originals when optional cleanup fails. */
28
+ export function finalizeModel(execution, output, limits, options, startedAt, builtAt) {
29
+ const descriptors = execution.isSolid(output) ? [{ id: "model", solid: output }] : output;
30
+ if (!isArray(descriptors) || descriptors.length === 0)
31
+ throw new GeometryError("INVALID_ARGUMENT", "Build must return a solid or at least one named part.", { operation: "finalize" });
32
+ if (descriptors.length > limits.maxParts)
33
+ throw new GeometryError("COMPLEXITY_LIMIT", `Output exceeds ${limits.maxParts} parts.`, {
34
+ operation: "finalize",
35
+ });
36
+ const ids = new Set();
37
+ const backingBuffers = new Set();
38
+ const meshCopies = new Map();
39
+ const min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
40
+ let vertices = 0, triangles = 0, bytes = 0;
41
+ let parts = descriptors.map((descriptor) => {
42
+ if (typeof descriptor !== "object" ||
43
+ descriptor === null ||
44
+ typeof descriptor.id !== "string" ||
45
+ !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(descriptor.id) ||
46
+ descriptor.id.length > 64 ||
47
+ ids.has(descriptor.id))
48
+ throw new GeometryError("INVALID_ARGUMENT", "Part IDs must be unique canonical lowercase identifiers of at most 64 characters.", { operation: "finalize" });
49
+ ids.add(descriptor.id);
50
+ if (descriptor.color !== undefined &&
51
+ (typeof descriptor.color !== "string" || !/^#[\da-f]{6}$/i.test(descriptor.color)))
52
+ throw new GeometryError("INVALID_ARGUMENT", "Part colors must be six-digit hex strings.", {
53
+ operation: "finalize",
54
+ });
55
+ if ((descriptor.solid === undefined) === (descriptor.mesh === undefined))
56
+ throw new GeometryError("INVALID_ARGUMENT", "Each part must contain exactly one solid or mesh.", { operation: "finalize" });
57
+ const nativeAnalysis = descriptor.solid === undefined ? undefined : execution.analyzedMeshFor(descriptor.solid);
58
+ const source = descriptor.solid === undefined ? descriptor.mesh : nativeAnalysis.mesh;
59
+ if (!(source.positions instanceof Float32Array) ||
60
+ !(source.indices instanceof Uint32Array) ||
61
+ !(source.positions.buffer instanceof ArrayBuffer) ||
62
+ !(source.indices.buffer instanceof ArrayBuffer))
63
+ throw new GeometryError("INVALID_MESH", "Parts require transferable Float32 positions and Uint32 indices.", { operation: "finalize" });
64
+ const sourceVertices = source.positions.length / 3, sourceTriangles = source.indices.length / 3;
65
+ let sourceBytes = 0;
66
+ for (const buffer of [source.positions.buffer, source.indices.buffer]) {
67
+ if (!backingBuffers.has(buffer)) {
68
+ backingBuffers.add(buffer);
69
+ sourceBytes += buffer.byteLength;
70
+ }
71
+ }
72
+ vertices += sourceVertices;
73
+ triangles += sourceTriangles;
74
+ bytes += sourceBytes;
75
+ if (vertices > limits.maxVertices || triangles > limits.maxTriangles || bytes > limits.maxBytes)
76
+ throw new GeometryError("COMPLEXITY_LIMIT", "Aggregate output exceeds the execution limits.", { operation: "finalize" });
77
+ // Direct meshes are copied before analysis so later caller mutation cannot invalidate facts.
78
+ const mesh = descriptor.mesh === undefined ? source : copiedMeshViews(source, meshCopies);
79
+ const measurements = nativeAnalysis?.measurements ??
80
+ analyzeTriangleMesh(mesh, { requireClosed: true, includeTopology: true });
81
+ if (descriptor.mesh !== undefined)
82
+ execution.validateMesh(mesh);
83
+ if (!(measurements.signedVolume > 0))
84
+ throw new GeometryError("INVALID_TOPOLOGY", "Manufacturing parts must enclose positive oriented volume.", { operation: "finalize" });
85
+ for (let axis = 0; axis < 3; axis += 1) {
86
+ min[axis] = Math.min(min[axis], measurements.bounds.min[axis]);
87
+ max[axis] = Math.max(max[axis], measurements.bounds.max[axis]);
88
+ }
89
+ return Object.freeze({
90
+ id: descriptor.id,
91
+ ...mesh,
92
+ ...(descriptor.color === undefined ? {} : { color: descriptor.color.toLowerCase() }),
93
+ measurements,
94
+ });
95
+ });
96
+ const originalParts = parts;
97
+ if (options.meshTopologyMode === "optimized" && triangles <= 200_000) {
98
+ const candidates = new Map();
99
+ parts = parts.map((part) => {
100
+ let indexBuffers = candidates.get(part.positions.buffer);
101
+ if (indexBuffers === undefined) {
102
+ indexBuffers = new Map();
103
+ candidates.set(part.positions.buffer, indexBuffers);
104
+ }
105
+ let views = indexBuffers.get(part.indices.buffer);
106
+ if (views === undefined) {
107
+ views = new Map();
108
+ indexBuffers.set(part.indices.buffer, views);
109
+ }
110
+ const key = `${part.positions.byteOffset}:${part.positions.length}:${part.indices.byteOffset}:${part.indices.length}`;
111
+ const cached = views.get(key);
112
+ if (cached !== undefined)
113
+ return Object.freeze({ ...part, ...cached });
114
+ let selected = {
115
+ positions: part.positions,
116
+ indices: part.indices,
117
+ measurements: part.measurements,
118
+ };
119
+ try {
120
+ const optimized = optimizePlanarPatches(part);
121
+ if (optimized.changed) {
122
+ const mesh = {
123
+ positions: part.positions,
124
+ indices: copiedUint32Array(optimized.mesh.indices),
125
+ };
126
+ const measurements = analyzeTriangleMesh(mesh, {
127
+ requireClosed: true,
128
+ includeTopology: true,
129
+ });
130
+ execution.validateMesh(mesh);
131
+ selected = { ...mesh, measurements };
132
+ }
133
+ }
134
+ catch {
135
+ // Optional optimization preserves the usable original on unsupported geometry.
136
+ }
137
+ views.set(key, selected);
138
+ return Object.freeze({ ...part, ...selected });
139
+ });
140
+ }
141
+ // Statistics describe the exact selected buffers after optional finalization.
142
+ let totals = finalPartTotals(parts);
143
+ if (!fitsLimits(totals, limits) && parts !== originalParts) {
144
+ parts = originalParts;
145
+ totals = finalPartTotals(parts);
146
+ }
147
+ if (!fitsLimits(totals, limits))
148
+ throw new GeometryError("COMPLEXITY_LIMIT", "Selected output exceeds the execution limits.", {
149
+ operation: "finalize",
150
+ });
151
+ const finalizedAt = performance.now();
152
+ return Object.freeze({
153
+ parts: Object.freeze(parts),
154
+ bounds: Object.freeze({ min: Object.freeze(min), max: Object.freeze(max) }),
155
+ stats: Object.freeze({
156
+ ...totals,
157
+ buildMs: builtAt - startedAt,
158
+ finalizationMs: finalizedAt - builtAt,
159
+ generationMs: finalizedAt - startedAt,
160
+ }),
161
+ });
162
+ }
163
+ /** Captures mutable external buffers once before an asynchronous snapshot export begins. */
164
+ export function captureExportParts(parts, limits) {
165
+ if (!isArray(parts) || parts.length === 0 || parts.length > limits.maxParts)
166
+ throw new GeometryError("COMPLEXITY_LIMIT", `Export requires one through ${limits.maxParts} parts.`, {
167
+ operation: "export3mf",
168
+ });
169
+ const identifiers = new Set();
170
+ const buffers = new Set();
171
+ let vertexCount = 0, triangleCount = 0, byteCount = 0;
172
+ for (const part of parts) {
173
+ if (typeof part !== "object" ||
174
+ part === null ||
175
+ typeof part.id !== "string" ||
176
+ !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(part.id) ||
177
+ part.id.length > 64 ||
178
+ identifiers.has(part.id))
179
+ throw new GeometryError("INVALID_ARGUMENT", "Export part IDs must be unique canonical identifiers.", { operation: "export3mf" });
180
+ identifiers.add(part.id);
181
+ if (part.color !== undefined &&
182
+ (typeof part.color !== "string" || !/^#[\da-f]{6}$/i.test(part.color)))
183
+ throw new GeometryError("INVALID_ARGUMENT", "Export colors must be six-digit hex strings.", {
184
+ operation: "export3mf",
185
+ });
186
+ if (!(part.positions instanceof Float32Array) ||
187
+ !(part.indices instanceof Uint32Array) ||
188
+ !(part.positions.buffer instanceof ArrayBuffer) ||
189
+ !(part.indices.buffer instanceof ArrayBuffer))
190
+ throw new GeometryError("INVALID_MESH", "Export requires transferable copied mesh arrays.", {
191
+ operation: "export3mf",
192
+ });
193
+ vertexCount += part.positions.length / 3;
194
+ triangleCount += part.indices.length / 3;
195
+ for (const buffer of [part.positions.buffer, part.indices.buffer]) {
196
+ if (!buffers.has(buffer)) {
197
+ buffers.add(buffer);
198
+ byteCount += buffer.byteLength;
199
+ }
200
+ }
201
+ if (vertexCount > limits.maxVertices ||
202
+ triangleCount > limits.maxTriangles ||
203
+ byteCount > limits.maxBytes)
204
+ throw new GeometryError("COMPLEXITY_LIMIT", "Export snapshot exceeds the execution limits.", {
205
+ operation: "export3mf",
206
+ });
207
+ }
208
+ const copiedBuffers = new Map();
209
+ return parts.map((part) => ({
210
+ id: part.id,
211
+ ...copiedMeshViews(part, copiedBuffers),
212
+ ...(part.color === undefined ? {} : { color: part.color }),
213
+ }));
214
+ }
@@ -0,0 +1,72 @@
1
+ import { GeometryError } from "../geometry/errors.js";
2
+ import { defaultModelingLimits, resolveModelingLimits } from "../geometry/model-limits.js";
3
+ import { bindModelContext } from "../model/execution-binding.js";
4
+ import { createExecutionContext } from "./execution.js";
5
+ import { captureExportParts, finalizeModel } from "./finalization.js";
6
+ import createManifoldModule from "./kernel/manifold.js";
7
+ import { withManifoldScope } from "./native/context.js";
8
+ import { assertSynchronousScopeResult } from "./native/ownership.js";
9
+ export { defaultModelingLimits };
10
+ /** URL of the package's pinned WASM asset; browser bundlers may replace it with their emitted URL. */
11
+ export const modelingWasmUrl = new URL("./kernel/manifold.wasm", import.meta.url).href;
12
+ /** Creates an engine over one already initialized host kernel.
13
+ * Kept internal to host integration tests; ordinary consumers use createModelEngine.
14
+ * @internal
15
+ */
16
+ function engineFromModule(module, engineLimits) {
17
+ let building = false;
18
+ return Object.freeze({
19
+ limits: engineLimits,
20
+ async export3mf(parts, options = {}) {
21
+ if (building)
22
+ throw new GeometryError("INVALID_ARGUMENT", "An engine cannot export during another operation.", { operation: "export3mf" });
23
+ const snapshot = captureExportParts(parts, engineLimits);
24
+ const snapshotOptions = { ...options };
25
+ building = true;
26
+ try {
27
+ const { meshesTo3mf } = await import("./export-3mf.js");
28
+ return meshesTo3mf(snapshot, snapshotOptions);
29
+ }
30
+ finally {
31
+ building = false;
32
+ }
33
+ },
34
+ build(build, options = {}) {
35
+ if (building)
36
+ throw new GeometryError("INVALID_ARGUMENT", "An engine cannot run nested builds.", {
37
+ operation: "build",
38
+ });
39
+ const limits = resolveModelingLimits(options.limits, engineLimits);
40
+ building = true;
41
+ const startedAt = performance.now();
42
+ try {
43
+ return withManifoldScope(module, (scope) => {
44
+ const execution = createExecutionContext(module, scope, limits, options.resolution);
45
+ try {
46
+ const output = bindModelContext(execution.context, () => build(execution.context));
47
+ assertSynchronousScopeResult(output, () => new GeometryError("INVALID_ARGUMENT", "Build callbacks must be synchronous.", {
48
+ operation: "build",
49
+ }));
50
+ const builtAt = performance.now();
51
+ return finalizeModel(execution, output, limits, options, startedAt, builtAt);
52
+ }
53
+ finally {
54
+ execution.dispose();
55
+ }
56
+ });
57
+ }
58
+ finally {
59
+ building = false;
60
+ }
61
+ },
62
+ });
63
+ }
64
+ /** Initializes one host kernel and returns a lifecycle-safe engine. No generator initializes WASM. */
65
+ export async function createModelEngine(options = {}) {
66
+ const limits = resolveModelingLimits(options.limits);
67
+ const module = await createManifoldModule({
68
+ locateFile: options.locateFile ?? (() => modelingWasmUrl),
69
+ });
70
+ module.setup();
71
+ return engineFromModule(module, limits);
72
+ }
@@ -0,0 +1,52 @@
1
+ import { ownScopedManifoldValue } from "./native/context.js";
2
+ import { copiedMeshViews } from "./native/copied-views.js";
3
+ /** Internal host-bound inspection operations. */
4
+ export function createInspectionOperations(environment) {
5
+ const { scope, throwGeometryError, nativeSolid, nativeSection, ownSolid, validateFiniteNumber, requirePositiveNumber, validateCoordinates, analyzedMeshFor, } = environment;
6
+ const operations = {
7
+ toTriangleMesh: (value) => copiedMeshViews(analyzedMeshFor(value).mesh, new Map()),
8
+ inspectSection: (handle) => {
9
+ const native = nativeSection(handle), bounds = native.bounds();
10
+ const parts = native.decompose().map((part) => ownScopedManifoldValue(scope, part));
11
+ return {
12
+ ...bounds,
13
+ area: native.area(),
14
+ contours: native.toPolygons().length,
15
+ parts: parts.length,
16
+ vertices: native.numVert(),
17
+ };
18
+ },
19
+ inspectSolid: (handle) => {
20
+ const native = nativeSolid(handle), bounds = native.boundingBox();
21
+ const parts = native.decompose().map((part) => ownScopedManifoldValue(scope, part));
22
+ return { ...bounds, parts: parts.length, volume: native.volume() };
23
+ },
24
+ rayCast: (handle, origin, endpoint) => {
25
+ validateCoordinates(origin, 3, "rayCast");
26
+ validateCoordinates(endpoint, 3, "rayCast");
27
+ const segmentLength = Math.hypot(...origin.map((value, axis) => value - endpoint[axis]));
28
+ if (!Number.isFinite(segmentLength) || segmentLength === 0)
29
+ throwGeometryError("DEGENERATE_GEOMETRY", "rayCast", "Ray segment endpoints must differ.");
30
+ return Object.freeze(nativeSolid(handle)
31
+ .rayCast([...origin], [...endpoint])
32
+ .map((hit) => Object.freeze({
33
+ faceId: Number(hit.faceID),
34
+ distance: hit.distance * segmentLength,
35
+ position: Object.freeze([...hit.position]),
36
+ normal: Object.freeze([...hit.normal]),
37
+ })));
38
+ },
39
+ components: (handle) => nativeSolid(handle).decompose().map(ownSolid),
40
+ simplify: (handle, tolerance) => {
41
+ const native = nativeSolid(handle);
42
+ const original = ownScopedManifoldValue(scope, native.asOriginal());
43
+ return ownSolid(original.simplify(requirePositiveNumber(tolerance, "simplify")));
44
+ },
45
+ setTolerance: (handle, tolerance) => {
46
+ if (validateFiniteNumber(tolerance, "setTolerance") < 0)
47
+ throwGeometryError("INVALID_ARGUMENT", "setTolerance", "Tolerance must be nonnegative millimetres.");
48
+ return ownSolid(nativeSolid(handle).setTolerance(tolerance));
49
+ },
50
+ };
51
+ return operations;
52
+ }
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.