@carbonenginejs/runtime-resource 0.7.0 → 0.8.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 (219) hide show
  1. package/FORMAT-PROVENANCE.md +155 -144
  2. package/LICENSE +21 -21
  3. package/NOTICE +29 -29
  4. package/README.md +11 -0
  5. package/dist/CjsMotherLode.js +1271 -1271
  6. package/dist/CjsResMan.js +3005 -3005
  7. package/dist/CjsResManQueue.js +214 -214
  8. package/dist/CjsResource.js +566 -566
  9. package/dist/CjsResourceSource.js +59 -59
  10. package/dist/_virtual/_rollupPluginBabelHelpers.js +153 -153
  11. package/dist/format/CjsBlueReader.js +269 -269
  12. package/dist/format/CjsFormat.js +192 -192
  13. package/dist/format/CjsReader.js +18 -18
  14. package/dist/format/CjsResourceProbe.js +277 -277
  15. package/dist/format/payloadContract.js +173 -173
  16. package/dist/formats/black/CjsBlackFormat.js +278 -278
  17. package/dist/formats/black/core/CjsBlackBinaryReader.js +153 -153
  18. package/dist/formats/black/core/CjsBlackPropertyReaders.js +382 -382
  19. package/dist/formats/black/core/CjsBlackReader.js +639 -639
  20. package/dist/formats/black/core/CjsBlackSchemaRegistry.js +433 -433
  21. package/dist/formats/black/core/black-schema-v1-2026-07-11.json.js +4 -4
  22. package/dist/formats/black/core/blackConstants.js +7 -7
  23. package/dist/formats/black/core/blackDefinitions.js +10 -10
  24. package/dist/formats/black/core/blackEnums.js +6 -6
  25. package/dist/formats/black/core/blackSchema.js +3 -3
  26. package/dist/formats/black/core/blackVersion.js +22 -22
  27. package/dist/formats/black/core/helpers.js +182 -182
  28. package/dist/formats/black/core/schema.js +4 -4
  29. package/dist/formats/black/index.js +2 -2
  30. package/dist/formats/bnk/CjsBnkFormat.js +125 -125
  31. package/dist/formats/bnk/core/graph.js +140 -140
  32. package/dist/formats/bnk/core/helpers.js +409 -409
  33. package/dist/formats/bnk/core/musicNodes.js +489 -489
  34. package/dist/formats/bnk/core/soundbanksInfo.js +246 -246
  35. package/dist/formats/bnk/index.js +2 -2
  36. package/dist/formats/cmf/CjsCmfFormat.js +497 -497
  37. package/dist/formats/cmf/core/binary.js +118 -118
  38. package/dist/formats/cmf/core/buffers.js +233 -233
  39. package/dist/formats/cmf/core/constants.js +47 -47
  40. package/dist/formats/cmf/core/gr2Anim.js +453 -453
  41. package/dist/formats/cmf/core/helpers.js +287 -287
  42. package/dist/formats/cmf/core/pack.js +276 -276
  43. package/dist/formats/cmf/core/schema.js +364 -364
  44. package/dist/formats/cmf/core/shared.js +268 -268
  45. package/dist/formats/cmf/core/writer.js +517 -517
  46. package/dist/formats/cmf/index.js +2 -2
  47. package/dist/formats/dds/CjsDdsFormat.js +193 -193
  48. package/dist/formats/dds/core/bc6h.js +288 -0
  49. package/dist/formats/dds/core/bc6h.js.map +1 -0
  50. package/dist/formats/dds/core/bc7.js +251 -0
  51. package/dist/formats/dds/core/bc7.js.map +1 -0
  52. package/dist/formats/dds/core/helpers.js +815 -812
  53. package/dist/formats/dds/core/helpers.js.map +1 -1
  54. package/dist/formats/dds/index.js +2 -2
  55. package/dist/formats/fbx/CjsFbxFormat.js +266 -266
  56. package/dist/formats/fbx/core/helpers.js +3901 -3901
  57. package/dist/formats/fbx/index.js +2 -2
  58. package/dist/formats/flac/CjsFlacFormat.js +87 -87
  59. package/dist/formats/flac/core/helpers.js +295 -295
  60. package/dist/formats/flac/index.js +2 -2
  61. package/dist/formats/gif/CjsGifFormat.js +87 -87
  62. package/dist/formats/gif/core/helpers.js +360 -360
  63. package/dist/formats/gif/index.js +2 -2
  64. package/dist/formats/gltf/CjsGltfFormat.js +290 -290
  65. package/dist/formats/gltf/core/helpers.js +292 -292
  66. package/dist/formats/gltf/core/json.js +79 -79
  67. package/dist/formats/gltf/core/parser.js +666 -666
  68. package/dist/formats/gltf/core/targets.js +163 -163
  69. package/dist/formats/gltf/index.js +2 -2
  70. package/dist/formats/index.js +23 -23
  71. package/dist/formats/jpeg/CjsJpegFormat.js +206 -206
  72. package/dist/formats/jpeg/core/helpers.js +350 -350
  73. package/dist/formats/jpeg/core/jpeg.js +377 -377
  74. package/dist/formats/jpeg/index.js +2 -2
  75. package/dist/formats/mp3/CjsMp3Format.js +192 -192
  76. package/dist/formats/mp3/core/helpers.js +338 -338
  77. package/dist/formats/mp3/index.js +2 -2
  78. package/dist/formats/mp4/CjsMp4Format.js +191 -191
  79. package/dist/formats/mp4/core/helpers.js +449 -449
  80. package/dist/formats/mp4/index.js +2 -2
  81. package/dist/formats/obj/CjsObjFormat.js +253 -253
  82. package/dist/formats/obj/core/helpers.js +573 -573
  83. package/dist/formats/obj/core/json.js +64 -64
  84. package/dist/formats/obj/core/parser.js +321 -321
  85. package/dist/formats/obj/index.js +2 -2
  86. package/dist/formats/ogg/CjsOggFormat.js +88 -88
  87. package/dist/formats/ogg/core/helpers.js +387 -387
  88. package/dist/formats/ogg/core/imdct.js +178 -178
  89. package/dist/formats/ogg/core/vorbis.js +999 -999
  90. package/dist/formats/ogg/index.js +2 -2
  91. package/dist/formats/png/CjsPngFormat.js +195 -195
  92. package/dist/formats/png/core/helpers.js +583 -583
  93. package/dist/formats/png/index.js +2 -2
  94. package/dist/formats/red/CjsRedFormat.js +261 -261
  95. package/dist/formats/red/core/CjsRedReader.js +194 -194
  96. package/dist/formats/red/core/blackDefinitions.js +3 -3
  97. package/dist/formats/red/core/helpers.js +139 -139
  98. package/dist/formats/red/core/redGraph.js +68 -68
  99. package/dist/formats/red/core/schema.js +4 -4
  100. package/dist/formats/red/index.js +2 -2
  101. package/dist/formats/stl/CjsStlFormat.js +365 -365
  102. package/dist/formats/stl/core/helpers.js +261 -261
  103. package/dist/formats/stl/core/json.js +51 -51
  104. package/dist/formats/stl/core/stl.js +629 -629
  105. package/dist/formats/stl/core/targets.js +163 -163
  106. package/dist/formats/stl/index.js +2 -2
  107. package/dist/formats/tga/CjsTgaFormat.js +192 -192
  108. package/dist/formats/tga/core/helpers.js +446 -446
  109. package/dist/formats/tga/index.js +2 -2
  110. package/dist/formats/wav/CjsWavFormat.js +192 -192
  111. package/dist/formats/wav/core/helpers.js +328 -328
  112. package/dist/formats/wav/index.js +2 -2
  113. package/dist/formats/webm/CjsWebmFormat.js +191 -191
  114. package/dist/formats/webm/core/helpers.js +537 -537
  115. package/dist/formats/webm/index.js +2 -2
  116. package/dist/formats/webp/CjsWebpFormat.js +86 -86
  117. package/dist/formats/webp/core/helpers.js +214 -214
  118. package/dist/formats/webp/index.js +2 -2
  119. package/dist/formats/wem/CjsWemFormat.js +241 -241
  120. package/dist/formats/wem/core/bitStream.js +259 -259
  121. package/dist/formats/wem/core/codebookLibrary.js +164 -164
  122. package/dist/formats/wem/core/helpers.js +417 -417
  123. package/dist/formats/wem/core/packedCodebooksAotuv603.js +30 -30
  124. package/dist/formats/wem/core/ptadpcm.js +77 -77
  125. package/dist/formats/wem/core/resolve.js +121 -121
  126. package/dist/formats/wem/core/wemToOgg.js +485 -485
  127. package/dist/formats/wem/index.js +2 -2
  128. package/dist/formats/yaml/CjsYamlFormat.js +83 -83
  129. package/dist/formats/yaml/core/CjsYamlReader.js +305 -305
  130. package/dist/formats/yaml/core/helpers.js +160 -160
  131. package/dist/formats/yaml/index.js +2 -2
  132. package/dist/index.js +48 -48
  133. package/dist/resourcePath.js +18 -18
  134. package/dist/resourceStates.js +9 -9
  135. package/dist/resources/AudioGeometryResData.js +47 -47
  136. package/dist/resources/GStateBindingCallbackData.js +31 -31
  137. package/dist/resources/MeshDecalData.js +37 -37
  138. package/dist/resources/MeshDecalLodData.js +34 -34
  139. package/dist/resources/Tr2EffectRes.js +71 -71
  140. package/dist/resources/Tr2GrannyIntersectionResult.js +60 -60
  141. package/dist/resources/Tr2GrannyStateRes.js +44 -44
  142. package/dist/resources/Tr2ImageRes.js +114 -114
  143. package/dist/resources/Tr2LightProfileRes.js +40 -40
  144. package/dist/resources/Tr2MaterialArea.js +34 -34
  145. package/dist/resources/Tr2MaterialMesh.js +31 -31
  146. package/dist/resources/Tr2MaterialRes.js +34 -34
  147. package/dist/resources/Tr2ShaderPermutation.js +43 -43
  148. package/dist/resources/Tr2TextureLodManager.js +80 -80
  149. package/dist/resources/Tr2TextureLodUpdateRequest.js +37 -37
  150. package/dist/resources/Tr2TexturePackChannel.js +37 -37
  151. package/dist/resources/Tr2TexturePipeline.js +52 -52
  152. package/dist/resources/Tr2TexturePipelineParams.js +34 -34
  153. package/dist/resources/Tr2TexturePipelineStepCompress.js +40 -40
  154. package/dist/resources/Tr2TexturePipelineStepLimitSize.js +34 -34
  155. package/dist/resources/Tr2TexturePipelineStepLoad.js +31 -31
  156. package/dist/resources/Tr2TexturePipelineStepPack.js +43 -43
  157. package/dist/resources/TriGeometryRes.js +239 -216
  158. package/dist/resources/TriGeometryRes.js.map +1 -1
  159. package/dist/resources/TriGeometryResAreaData.js +59 -59
  160. package/dist/resources/TriGeometryResJointData.js +38 -38
  161. package/dist/resources/TriGeometryResLodData.js +88 -88
  162. package/dist/resources/TriGeometryResMeshData.js +63 -63
  163. package/dist/resources/TriGeometryResSkeletonData.js +34 -34
  164. package/dist/resources/TriGrannyRes.js +43 -43
  165. package/dist/resources/TriJointBinding.js +38 -38
  166. package/dist/resources/TriMorphTargetGeometryConstants.js +46 -46
  167. package/dist/resources/TriRtGeometryConstants.js +88 -88
  168. package/dist/resources/TriTextureRes.js +304 -304
  169. package/dist/resources/enums.js +18 -18
  170. package/dist/resources/resourceBoundary.js +47 -47
  171. package/dist/resources/texturePipelineBehavior.js +308 -308
  172. package/dist/texture/CjsTextureArrayRes.js +406 -406
  173. package/dist/texture/CjsTextureParameterProxy.js +133 -133
  174. package/format-notices/black/LICENSE +21 -21
  175. package/format-notices/black/NOTICE +47 -47
  176. package/format-notices/bnk/LICENSE +21 -21
  177. package/format-notices/bnk/NOTICE +20 -20
  178. package/format-notices/cmf/LICENSE +21 -21
  179. package/format-notices/cmf/NOTICE +36 -36
  180. package/format-notices/dds/LICENSE +21 -21
  181. package/format-notices/dds/NOTICE +14 -14
  182. package/format-notices/fbx/LICENSE +21 -21
  183. package/format-notices/fbx/NOTICE +14 -14
  184. package/format-notices/flac/LICENSE +21 -21
  185. package/format-notices/flac/NOTICE +14 -14
  186. package/format-notices/gif/LICENSE +21 -21
  187. package/format-notices/gif/NOTICE +14 -14
  188. package/format-notices/gltf/LICENSE +21 -21
  189. package/format-notices/gltf/NOTICE +27 -27
  190. package/format-notices/jpeg/LICENSE +21 -21
  191. package/format-notices/jpeg/NOTICE +14 -14
  192. package/format-notices/mp3/LICENSE +21 -21
  193. package/format-notices/mp3/NOTICE +14 -14
  194. package/format-notices/mp4/LICENSE +21 -21
  195. package/format-notices/mp4/NOTICE +14 -14
  196. package/format-notices/obj/LICENSE +21 -21
  197. package/format-notices/obj/NOTICE +26 -26
  198. package/format-notices/ogg/LICENSE +21 -21
  199. package/format-notices/ogg/NOTICE +28 -28
  200. package/format-notices/png/LICENSE +21 -21
  201. package/format-notices/png/NOTICE +14 -14
  202. package/format-notices/red/LICENSE +21 -21
  203. package/format-notices/red/NOTICE +31 -31
  204. package/format-notices/stl/LICENSE +21 -21
  205. package/format-notices/stl/NOTICE +21 -21
  206. package/format-notices/tga/LICENSE +21 -21
  207. package/format-notices/tga/NOTICE +14 -14
  208. package/format-notices/wav/LICENSE +21 -21
  209. package/format-notices/wav/NOTICE +14 -14
  210. package/format-notices/webm/LICENSE +21 -21
  211. package/format-notices/webm/NOTICE +14 -14
  212. package/format-notices/webp/LICENSE +21 -21
  213. package/format-notices/webp/NOTICE +14 -14
  214. package/format-notices/wem/LICENSE +57 -57
  215. package/format-notices/wem/NOTICE +33 -33
  216. package/format-notices/yaml/LICENSE +21 -21
  217. package/format-notices/yaml/NOTICE +44 -44
  218. package/package.json +2 -2
  219. package/resource-lifecycle.md +679 -679
@@ -1,629 +1,629 @@
1
- import { triangleNormal, generateNormals, computeBoundsFromPositions, isDegenerateTriangle, computeBoundsFromTriangles } from '@carbonenginejs/core-math/mesh';
2
- import { normalize } from '@carbonenginejs/core-math/vec3';
3
-
4
- /**
5
- * STL read/write and printability inspection helpers.
6
- */
7
-
8
- const BINARY_HEADER_BYTES = 80,
9
- BINARY_COUNT_BYTES = 4,
10
- BINARY_TRIANGLE_BYTES = 50,
11
- DEFAULT_SOLID_NAME = "carbonenginejs";
12
- function makeDecoder() {
13
- return new TextDecoder("utf-8");
14
- }
15
- function makeEncoder() {
16
- return new TextEncoder();
17
- }
18
- function assertFiniteNumber(value, feature) {
19
- if (typeof value !== "number" || !Number.isFinite(value)) {
20
- throw new TypeError(`CjsStlFormat: ${feature} must contain finite numbers`);
21
- }
22
- return value;
23
- }
24
-
25
- /**
26
- * Validate one shared-geometry triangle index before converting it to a byte
27
- * offset. Fractional, unsafe, negative, and out-of-range values are rejected
28
- * with the mesh and index-group context retained.
29
- *
30
- * @param {*} value Candidate vertex index.
31
- * @param {number} vertexCount Number of position triples in the mesh.
32
- * @param {number} meshIndex Zero-based mesh index in the shared root.
33
- * @param {string} groupName Source index-group name.
34
- * @returns {number} Valid non-negative vertex index.
35
- * @throws {RangeError} If the value cannot address a complete mesh vertex.
36
- */
37
- function assertTriangleIndex(value, vertexCount, meshIndex, groupName) {
38
- if (!Number.isSafeInteger(value) || value < 0 || value >= vertexCount) {
39
- throw new RangeError(`CjsStlFormat: mesh #${meshIndex} index group ${JSON.stringify(groupName)} ` + `contains invalid vertex index ${String(value)} for ${vertexCount} vertices`);
40
- }
41
- return value;
42
- }
43
- function cloneVertex(vertex, scale = 1) {
44
- const result = [];
45
- for (let component = 0; component < 3; component++) {
46
- const value = assertFiniteNumber(vertex[component], "vertex") * scale;
47
- result.push(assertFiniteNumber(value, "scaled vertex"));
48
- }
49
- return result;
50
- }
51
- function sanitizeSolidName(name) {
52
- const value = String(name || DEFAULT_SOLID_NAME).replace(/\s+/g, "_").replace(/[^\w.-]/g, "_");
53
- return value || DEFAULT_SOLID_NAME;
54
- }
55
-
56
- /**
57
- * Recover the caller's solid name from this writer's binary provenance header
58
- * while retaining compatibility with arbitrary third-party STL headers.
59
- *
60
- * @param {string} header Decoded and null-trimmed 80-byte binary STL header.
61
- * @returns {string} Sanitized shared-mesh name.
62
- */
63
- function readBinarySolidName(header) {
64
- return sanitizeSolidName(header.replace(/^CarbonEngineJS\s+/u, "") || DEFAULT_SOLID_NAME);
65
- }
66
- function formatNumber(value) {
67
- if (!Number.isFinite(value)) return "0";
68
- if (Object.is(value, -0)) return "0";
69
- return Number.parseFloat(value.toPrecision(9)).toString();
70
- }
71
- function binaryBytes(input) {
72
- if (input instanceof Uint8Array) return input;
73
- if (typeof ArrayBuffer !== "undefined" && input instanceof ArrayBuffer) return new Uint8Array(input);
74
- if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView(input)) {
75
- return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
76
- }
77
- return null;
78
- }
79
- function readFloat32(view, offset) {
80
- return view.getFloat32(offset, true);
81
- }
82
- function isZeroNormal(normal) {
83
- return Math.hypot(normal[0], normal[1], normal[2]) <= 1e-20;
84
- }
85
-
86
- /**
87
- * Return a finite unit facet normal, preferring an explicit non-zero normal
88
- * and otherwise deriving it from triangle winding.
89
- *
90
- * @param {object} triangle Triangle record with three vertices and optional normal.
91
- * @returns {number[]} Finite xyz unit normal.
92
- * @throws {TypeError} If normal calculation produces a non-finite component.
93
- */
94
- function resolveTriangleNormal(triangle) {
95
- const normal = triangle.normal && !isZeroNormal(triangle.normal) ? normalize([0, 0, 0], triangle.normal) : triangleNormal(triangle.vertices[0], triangle.vertices[1], triangle.vertices[2]);
96
- return [assertFiniteNumber(normal[0], "facet normal"), assertFiniteNumber(normal[1], "facet normal"), assertFiniteNumber(normal[2], "facet normal")];
97
- }
98
-
99
- /**
100
- * Store one finite binary STL float without silently overflowing to infinity.
101
- *
102
- * @param {DataView} view Destination byte view.
103
- * @param {number} offset Byte offset of the little-endian float.
104
- * @param {number} value Numeric component to encode.
105
- * @param {string} feature Context included in validation errors.
106
- * @returns {void}
107
- * @throws {TypeError|RangeError} If the value is non-finite or exceeds float32 range.
108
- */
109
- function writeFloat32(view, offset, value, feature) {
110
- const floatValue = Math.fround(assertFiniteNumber(value, feature));
111
- if (!Number.isFinite(floatValue)) {
112
- throw new RangeError(`CjsStlFormat: ${feature} exceeds binary STL float32 range`);
113
- }
114
- view.setFloat32(offset, floatValue, true);
115
- }
116
- function triangleWithNormal(vertices, normal) {
117
- const fallback = triangleNormal(vertices[0], vertices[1], vertices[2]);
118
- return {
119
- normal: isZeroNormal(normal) ? fallback : normalize([0, 0, 0], normal),
120
- vertices
121
- };
122
- }
123
- function quantizeNumber(value, tolerance) {
124
- if (tolerance <= 0) return formatNumber(value);
125
- return String(Math.round(value / tolerance));
126
- }
127
- function quantizeVertex(vertex, tolerance) {
128
- return `${quantizeNumber(vertex[0], tolerance)},${quantizeNumber(vertex[1], tolerance)},${quantizeNumber(vertex[2], tolerance)}`;
129
- }
130
- function bytesPerIndex(maxIndex) {
131
- return maxIndex > 65535 ? 4 : 2;
132
- }
133
- function addIssue(issues, key, count) {
134
- if (count > 0) issues.push({
135
- key,
136
- count
137
- });
138
- }
139
- function rootSource(input) {
140
- return input && typeof input === "object" && typeof input.grannyFileSource === "string" ? input.grannyFileSource : null;
141
- }
142
- class DisjointSet {
143
- constructor(size) {
144
- this.parent = new Array(size);
145
- for (let i = 0; i < size; i++) this.parent[i] = i;
146
- }
147
- find(value) {
148
- const parent = this.parent[value];
149
- if (parent === value) return value;
150
- this.parent[value] = this.find(parent);
151
- return this.parent[value];
152
- }
153
- union(a, b) {
154
- const ra = this.find(a),
155
- rb = this.find(b);
156
- if (ra !== rb) this.parent[rb] = ra;
157
- }
158
- }
159
-
160
- /**
161
- * Convert supported input into text.
162
- *
163
- * @param {string|Uint8Array|ArrayBuffer|DataView} input STL text or bytes.
164
- * @returns {string} STL text.
165
- */
166
- function toText(input) {
167
- if (typeof input === "string") return input;
168
- const bytes = binaryBytes(input);
169
- if (bytes) return makeDecoder().decode(bytes);
170
- throw new TypeError("CjsStlFormat: input must be STL text, bytes, or shared JSON geometry");
171
- }
172
-
173
- /**
174
- * Check whether byte-like input has an exact binary STL layout.
175
- *
176
- * @param {string|Uint8Array|ArrayBuffer|DataView} input Candidate STL input.
177
- * @returns {boolean} True when the byte length exactly matches a binary STL.
178
- */
179
- function isBinaryStl(input) {
180
- const bytes = binaryBytes(input);
181
- if (!bytes || bytes.byteLength < BINARY_HEADER_BYTES + BINARY_COUNT_BYTES) return false;
182
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
183
- const triangleCount = view.getUint32(BINARY_HEADER_BYTES, true);
184
- return BINARY_HEADER_BYTES + BINARY_COUNT_BYTES + triangleCount * BINARY_TRIANGLE_BYTES === bytes.byteLength;
185
- }
186
-
187
- /**
188
- * Cheap sniff for STL-like input.
189
- *
190
- * @param {string|Uint8Array|ArrayBuffer|DataView} input Candidate STL input.
191
- * @returns {boolean} True when the input looks like ASCII or binary STL.
192
- */
193
- function isStl(input) {
194
- if (isBinaryStl(input)) return true;
195
- try {
196
- const text = toText(input);
197
- return /^\s*solid\b/i.test(text) && /\bfacet\s+normal\b/i.test(text) && /\bvertex\b/i.test(text);
198
- } catch {
199
- return false;
200
- }
201
- }
202
-
203
- /**
204
- * Parse ASCII STL text into triangle records.
205
- *
206
- * @param {string} text ASCII STL text.
207
- * @returns {object} Parsed STL payload.
208
- */
209
- function parseAsciiStl(text) {
210
- const lines = text.split(/\r?\n/),
211
- triangles = [];
212
- let name = DEFAULT_SOLID_NAME,
213
- currentNormal = [0, 0, 0],
214
- vertices = [];
215
- for (const rawLine of lines) {
216
- const line = rawLine.trim();
217
- if (!line) continue;
218
- const solid = /^solid(?:\s+(.+))?$/i.exec(line);
219
- if (solid) {
220
- name = solid[1] ? solid[1].trim() : name;
221
- continue;
222
- }
223
- const facet = /^facet\s+normal\s+(.+)$/i.exec(line);
224
- if (facet) {
225
- const values = facet[1].trim().split(/\s+/).map(Number);
226
- currentNormal = values.length >= 3 && values.every(Number.isFinite) ? [values[0], values[1], values[2]] : [0, 0, 0];
227
- vertices = [];
228
- continue;
229
- }
230
- const vertex = /^vertex\s+(.+)$/i.exec(line);
231
- if (vertex) {
232
- const values = vertex[1].trim().split(/\s+/).map(Number);
233
- if (values.length < 3 || !values.every(Number.isFinite)) {
234
- throw new Error("CjsStlFormat: ASCII STL contains a malformed vertex line");
235
- }
236
- vertices.push([values[0], values[1], values[2]]);
237
- if (vertices.length === 3) {
238
- triangles.push(triangleWithNormal(vertices, currentNormal));
239
- vertices = [];
240
- }
241
- }
242
- }
243
- if (!triangles.length) {
244
- throw new Error("CjsStlFormat: ASCII STL contains no triangles");
245
- }
246
- return {
247
- format: "ascii",
248
- name: sanitizeSolidName(name),
249
- triangles
250
- };
251
- }
252
-
253
- /**
254
- * Parse binary STL bytes into triangle records.
255
- * Headers written as `CarbonEngineJS <solidName>` retain their provenance in
256
- * the file while exposing `<solidName>` as parsed mesh metadata.
257
- *
258
- * @param {Uint8Array} bytes Binary STL bytes.
259
- * @returns {object} Parsed format/name metadata and triangle records.
260
- * @throws {Error} If byte length/count disagree or no triangles are present.
261
- */
262
- function parseBinaryStl(bytes) {
263
- if (!isBinaryStl(bytes)) {
264
- throw new Error("CjsStlFormat: binary STL byte length does not match its triangle count");
265
- }
266
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength),
267
- header = makeDecoder().decode(bytes.subarray(0, BINARY_HEADER_BYTES)).replace(/\0+$/g, "").trim(),
268
- count = view.getUint32(BINARY_HEADER_BYTES, true),
269
- triangles = [];
270
- let offset = BINARY_HEADER_BYTES + BINARY_COUNT_BYTES;
271
- for (let i = 0; i < count; i++) {
272
- const normal = [readFloat32(view, offset), readFloat32(view, offset + 4), readFloat32(view, offset + 8)];
273
- const vertices = [];
274
- for (let v = 0; v < 3; v++) {
275
- const vo = offset + 12 + v * 12;
276
- vertices.push([readFloat32(view, vo), readFloat32(view, vo + 4), readFloat32(view, vo + 8)]);
277
- }
278
- triangles.push(triangleWithNormal(vertices, normal));
279
- offset += BINARY_TRIANGLE_BYTES;
280
- }
281
- if (!triangles.length) {
282
- throw new Error("CjsStlFormat: binary STL contains no triangles");
283
- }
284
- return {
285
- format: "binary",
286
- name: readBinarySolidName(header),
287
- triangles
288
- };
289
- }
290
-
291
- /**
292
- * Parse STL text or bytes.
293
- *
294
- * @param {string|Uint8Array|ArrayBuffer|DataView} input STL text or bytes.
295
- * @returns {object} Parsed STL payload.
296
- */
297
- function parseStl(input) {
298
- const bytes = binaryBytes(input);
299
- if (bytes && isBinaryStl(bytes)) return parseBinaryStl(bytes);
300
- return parseAsciiStl(toText(input));
301
- }
302
-
303
- /**
304
- * Build the shared CarbonEngineJS JSON mesh schema from STL triangles.
305
- *
306
- * @param {object[]} triangles Triangle records.
307
- * @param {object} values Normalized format values.
308
- * @param {object} [source] Parsed STL source metadata.
309
- * @returns {object} Shared JSON graph.
310
- */
311
- function trianglesToJson(triangles, values, source = {}) {
312
- const positions = [],
313
- normals = [],
314
- faces = [],
315
- vertexByKey = new Map();
316
- const addVertex = (vertex, normal) => {
317
- if (values.weldVertices) {
318
- const key = quantizeVertex(vertex, values.weldTolerance);
319
- const existing = vertexByKey.get(key);
320
- if (existing !== undefined) return existing;
321
- const next = positions.length / 3;
322
- vertexByKey.set(key, next);
323
- positions.push(vertex[0], vertex[1], vertex[2]);
324
- return next;
325
- }
326
- const next = positions.length / 3;
327
- positions.push(vertex[0], vertex[1], vertex[2]);
328
- normals.push(normal[0], normal[1], normal[2]);
329
- return next;
330
- };
331
- for (const triangle of triangles) {
332
- const vertices = triangle.vertices.map(vertex => cloneVertex(vertex));
333
- const normal = triangle.normal && !isZeroNormal(triangle.normal) ? normalize([0, 0, 0], triangle.normal) : triangleNormal(vertices[0], vertices[1], vertices[2]);
334
- for (const vertex of vertices) {
335
- faces.push(addVertex(vertex, normal));
336
- }
337
- }
338
- const resolvedNormals = values.weldVertices ? generateNormals(positions, faces) : normals;
339
- const bounds = computeBoundsFromPositions(positions);
340
- return {
341
- grannyFileFormatRevision: 0,
342
- grannyFileSource: values.source,
343
- meshes: [{
344
- name: source.name || values.solidName,
345
- morphTargets: [],
346
- minBounds: bounds.minBounds,
347
- maxBounds: bounds.maxBounds,
348
- boneBindings: [],
349
- vertex: {
350
- position: positions,
351
- blendIndice: [],
352
- tangent: [],
353
- normal: resolvedNormals,
354
- texcoord0: [],
355
- texcoord1: [],
356
- binormal: [],
357
- blendWeight: []
358
- },
359
- indices: [{
360
- name: "default",
361
- bytesPerIndex: bytesPerIndex(Math.max(0, positions.length / 3 - 1)),
362
- faces
363
- }]
364
- }],
365
- models: [],
366
- animations: []
367
- };
368
- }
369
-
370
- /**
371
- * Gather triangle records from the shared JSON geometry schema.
372
- * Meshes and index groups are flattened in encounter order. Coordinates are
373
- * copied and scaled, so the caller's shared graph remains unchanged. Only
374
- * positions, optional normals, and triangular indices participate in STL.
375
- *
376
- * @param {object} input Shared JSON graph or mesh record.
377
- * @param {object} values Normalized format values.
378
- * @returns {object[]} Scaled triangle records ready for inspection/encoding.
379
- * @throws {TypeError|RangeError|Error} If geometry, coordinates, or indices are invalid.
380
- */
381
- function jsonToTriangles(input, values) {
382
- const root = input && input.meshes ? input : {
383
- meshes: [input]
384
- },
385
- triangles = [];
386
- if (!root || !Array.isArray(root.meshes)) {
387
- throw new TypeError("CjsStlFormat: write input must be a shared JSON root or mesh");
388
- }
389
- for (const [meshIndex, mesh] of root.meshes.entries()) {
390
- const vertex = mesh && mesh.vertex,
391
- positions = vertex && vertex.position,
392
- normals = vertex && vertex.normal;
393
- if (!positions || positions.length % 3 !== 0) {
394
- throw new Error(`CjsStlFormat: mesh #${meshIndex} must provide flat vertex.position triples`);
395
- }
396
- for (const group of mesh.indices || []) {
397
- const faces = group && group.faces;
398
- if (!faces) continue;
399
- const groupName = group.name || "default";
400
- if (faces.length % 3 !== 0) {
401
- throw new Error(`CjsStlFormat: mesh #${meshIndex} index group ${JSON.stringify(groupName)} is not triangular`);
402
- }
403
- for (let i = 0; i < faces.length; i += 3) {
404
- const vertexCount = positions.length / 3,
405
- ia = assertTriangleIndex(faces[i], vertexCount, meshIndex, groupName) * 3,
406
- ib = assertTriangleIndex(faces[i + 1], vertexCount, meshIndex, groupName) * 3,
407
- ic = assertTriangleIndex(faces[i + 2], vertexCount, meshIndex, groupName) * 3;
408
- const vertices = [cloneVertex([positions[ia], positions[ia + 1], positions[ia + 2]], values.scale), cloneVertex([positions[ib], positions[ib + 1], positions[ib + 2]], values.scale), cloneVertex([positions[ic], positions[ic + 1], positions[ic + 2]], values.scale)];
409
- if (values.skipDegenerate && isDegenerateTriangle(vertices[0], vertices[1], vertices[2])) {
410
- continue;
411
- }
412
- let normal = triangleNormal(vertices[0], vertices[1], vertices[2]);
413
- if (!values.recalculateNormals && normals && normals.length >= positions.length) {
414
- const averaged = normalize([0, 0, 0], [normals[ia] + normals[ib] + normals[ic], normals[ia + 1] + normals[ib + 1] + normals[ic + 1], normals[ia + 2] + normals[ib + 2] + normals[ic + 2]]);
415
- if (!isZeroNormal(averaged)) normal = averaged;
416
- }
417
- triangles.push({
418
- normal,
419
- vertices
420
- });
421
- }
422
- }
423
- }
424
- return triangles;
425
- }
426
-
427
- /**
428
- * Convert STL or JSON input into triangle records for inspection.
429
- *
430
- * @param {any} input STL text/bytes or shared JSON.
431
- * @param {object} values Normalized format values.
432
- * @returns {object} Inspection source and triangles.
433
- */
434
- function trianglesFromInput(input, values) {
435
- if (input && typeof input === "object" && (input.meshes || input.vertex)) {
436
- return {
437
- format: "json",
438
- source: rootSource(input) || values.source,
439
- triangles: jsonToTriangles(input, {
440
- ...values,
441
- skipDegenerate: false
442
- })
443
- };
444
- }
445
- const bytes = binaryBytes(input);
446
- const parsed = parseStl(input);
447
- return {
448
- format: parsed.format,
449
- name: parsed.name,
450
- byteLength: bytes ? bytes.byteLength : typeof input === "string" ? makeEncoder().encode(input).byteLength : 0,
451
- source: values.source,
452
- triangles: parsed.triangles
453
- };
454
- }
455
-
456
- /**
457
- * Write triangle records as ASCII STL text.
458
- * Solid names and numeric components are normalized deterministically. The
459
- * function does not mutate triangle records.
460
- *
461
- * @param {object[]} triangles Triangle records.
462
- * @param {string} solidName STL solid name.
463
- * @returns {string} ASCII STL text.
464
- * @throws {TypeError} If a facet normal cannot be represented as finite text.
465
- */
466
- function writeAsciiStl(triangles, solidName) {
467
- const lines = [`solid ${sanitizeSolidName(solidName)}`];
468
- for (const triangle of triangles) {
469
- const normal = resolveTriangleNormal(triangle);
470
- lines.push(` facet normal ${formatNumber(normal[0])} ${formatNumber(normal[1])} ${formatNumber(normal[2])}`);
471
- lines.push(" outer loop");
472
- for (const vertex of triangle.vertices) {
473
- lines.push(` vertex ${formatNumber(vertex[0])} ${formatNumber(vertex[1])} ${formatNumber(vertex[2])}`);
474
- }
475
- lines.push(" endloop");
476
- lines.push(" endfacet");
477
- }
478
- lines.push(`endsolid ${sanitizeSolidName(solidName)}`);
479
- return `${lines.join("\n")}\n`;
480
- }
481
-
482
- /**
483
- * Write triangle records as binary STL bytes.
484
- * Output uses the standard 80-byte header, little-endian uint32 triangle
485
- * count, 50-byte triangle records, and zero attribute words. The header keeps
486
- * a `CarbonEngineJS` provenance prefix. Every numeric component is checked for
487
- * finite float32 representation before storage.
488
- *
489
- * @param {object[]} triangles Triangle records.
490
- * @param {string} solidName STL solid name.
491
- * @returns {Uint8Array} Binary STL bytes.
492
- * @throws {TypeError|RangeError} If count or numeric components exceed binary STL's representable domain.
493
- */
494
- function writeBinaryStl(triangles, solidName) {
495
- if (triangles.length > 0xffffffff) {
496
- throw new RangeError("CjsStlFormat: binary STL cannot contain more than 4294967295 triangles");
497
- }
498
- const bytes = new Uint8Array(BINARY_HEADER_BYTES + BINARY_COUNT_BYTES + triangles.length * BINARY_TRIANGLE_BYTES),
499
- view = new DataView(bytes.buffer),
500
- header = makeEncoder().encode(`CarbonEngineJS ${sanitizeSolidName(solidName)}`);
501
- bytes.set(header.subarray(0, BINARY_HEADER_BYTES), 0);
502
- view.setUint32(BINARY_HEADER_BYTES, triangles.length, true);
503
- let offset = BINARY_HEADER_BYTES + BINARY_COUNT_BYTES;
504
- for (const triangle of triangles) {
505
- const normal = resolveTriangleNormal(triangle);
506
- for (let c = 0; c < 3; c++) {
507
- writeFloat32(view, offset + c * 4, normal[c], "facet normal");
508
- }
509
- for (let v = 0; v < 3; v++) {
510
- const vertex = triangle.vertices[v];
511
- for (let c = 0; c < 3; c++) {
512
- writeFloat32(view, offset + 12 + v * 12 + c * 4, vertex[c], "vertex coordinate");
513
- }
514
- }
515
- view.setUint16(offset + 48, 0, true);
516
- offset += BINARY_TRIANGLE_BYTES;
517
- }
518
- return bytes;
519
- }
520
-
521
- /**
522
- * Inspect triangle topology for common 3D-printing blockers.
523
- *
524
- * @param {object[]} triangles Triangle records.
525
- * @param {object} values Normalized format values.
526
- * @param {object} [source] Source metadata.
527
- * @returns {object} Printability report.
528
- */
529
- function inspectTriangles(triangles, values, source = {}) {
530
- const vertices = new Map(),
531
- vertexKeys = [],
532
- edges = new Map(),
533
- dsu = new DisjointSet(triangles.length),
534
- issues = [];
535
- let degenerateTriangleCount = 0,
536
- validTriangleCount = 0;
537
- const vertexId = vertex => {
538
- const key = quantizeVertex(vertex, values.weldTolerance);
539
- const existing = vertices.get(key);
540
- if (existing !== undefined) return existing;
541
- const next = vertexKeys.length;
542
- vertices.set(key, next);
543
- vertexKeys.push(key);
544
- return next;
545
- };
546
- const addEdge = (triangleIndex, a, b) => {
547
- const ka = vertexKeys[a],
548
- kb = vertexKeys[b],
549
- key = ka < kb ? `${ka}|${kb}` : `${kb}|${ka}`,
550
- sign = ka < kb ? 1 : -1,
551
- entry = edges.get(key) || [];
552
- entry.push({
553
- triangleIndex,
554
- sign
555
- });
556
- edges.set(key, entry);
557
- };
558
- for (let triangleIndex = 0; triangleIndex < triangles.length; triangleIndex++) {
559
- const triangle = triangles[triangleIndex];
560
- if (isDegenerateTriangle(triangle.vertices[0], triangle.vertices[1], triangle.vertices[2], values.weldTolerance)) {
561
- degenerateTriangleCount++;
562
- continue;
563
- }
564
- const ids = triangle.vertices.map(vertexId);
565
- if (new Set(ids).size !== 3) {
566
- degenerateTriangleCount++;
567
- continue;
568
- }
569
- validTriangleCount++;
570
- addEdge(triangleIndex, ids[0], ids[1]);
571
- addEdge(triangleIndex, ids[1], ids[2]);
572
- addEdge(triangleIndex, ids[2], ids[0]);
573
- }
574
- let openEdgeCount = 0,
575
- nonManifoldEdgeCount = 0,
576
- inconsistentWindingEdgeCount = 0;
577
- for (const occurrences of edges.values()) {
578
- if (occurrences.length === 1) {
579
- openEdgeCount++;
580
- continue;
581
- }
582
- if (occurrences.length > 2) {
583
- nonManifoldEdgeCount++;
584
- }
585
- if (occurrences.length === 2 && occurrences[0].sign === occurrences[1].sign) {
586
- inconsistentWindingEdgeCount++;
587
- }
588
- for (let i = 1; i < occurrences.length; i++) {
589
- dsu.union(occurrences[0].triangleIndex, occurrences[i].triangleIndex);
590
- }
591
- }
592
- const shells = new Set();
593
- for (const occurrences of edges.values()) {
594
- for (const occurrence of occurrences) {
595
- shells.add(dsu.find(occurrence.triangleIndex));
596
- }
597
- }
598
- addIssue(issues, "no_triangles", triangles.length === 0 ? 1 : 0);
599
- addIssue(issues, "degenerate_triangles", degenerateTriangleCount);
600
- addIssue(issues, "open_edges", openEdgeCount);
601
- addIssue(issues, "non_manifold_edges", nonManifoldEdgeCount);
602
- addIssue(issues, "inconsistent_winding_edges", inconsistentWindingEdgeCount);
603
- const bounds = computeBoundsFromTriangles(triangles);
604
- const printable = triangles.length > 0 && degenerateTriangleCount === 0 && openEdgeCount === 0 && nonManifoldEdgeCount === 0 && inconsistentWindingEdgeCount === 0;
605
- return {
606
- format: source.format || "stl",
607
- name: source.name || "",
608
- byteLength: source.byteLength || 0,
609
- source: source.source || values.source,
610
- triangleCount: triangles.length,
611
- validTriangleCount,
612
- vertexCount: vertices.size,
613
- edgeCount: edges.size,
614
- shellCount: validTriangleCount > 0 ? shells.size : 0,
615
- openEdgeCount,
616
- nonManifoldEdgeCount,
617
- inconsistentWindingEdgeCount,
618
- degenerateTriangleCount,
619
- bounds: {
620
- min: bounds.minBounds,
621
- max: bounds.maxBounds
622
- },
623
- printable,
624
- issues
625
- };
626
- }
627
-
628
- export { inspectTriangles, isBinaryStl, isStl, jsonToTriangles, parseAsciiStl, parseBinaryStl, parseStl, toText, trianglesFromInput, trianglesToJson, writeAsciiStl, writeBinaryStl };
629
- //# sourceMappingURL=stl.js.map
1
+ import { triangleNormal, generateNormals, computeBoundsFromPositions, isDegenerateTriangle, computeBoundsFromTriangles } from '@carbonenginejs/core-math/mesh';
2
+ import { normalize } from '@carbonenginejs/core-math/vec3';
3
+
4
+ /**
5
+ * STL read/write and printability inspection helpers.
6
+ */
7
+
8
+ const BINARY_HEADER_BYTES = 80,
9
+ BINARY_COUNT_BYTES = 4,
10
+ BINARY_TRIANGLE_BYTES = 50,
11
+ DEFAULT_SOLID_NAME = "carbonenginejs";
12
+ function makeDecoder() {
13
+ return new TextDecoder("utf-8");
14
+ }
15
+ function makeEncoder() {
16
+ return new TextEncoder();
17
+ }
18
+ function assertFiniteNumber(value, feature) {
19
+ if (typeof value !== "number" || !Number.isFinite(value)) {
20
+ throw new TypeError(`CjsStlFormat: ${feature} must contain finite numbers`);
21
+ }
22
+ return value;
23
+ }
24
+
25
+ /**
26
+ * Validate one shared-geometry triangle index before converting it to a byte
27
+ * offset. Fractional, unsafe, negative, and out-of-range values are rejected
28
+ * with the mesh and index-group context retained.
29
+ *
30
+ * @param {*} value Candidate vertex index.
31
+ * @param {number} vertexCount Number of position triples in the mesh.
32
+ * @param {number} meshIndex Zero-based mesh index in the shared root.
33
+ * @param {string} groupName Source index-group name.
34
+ * @returns {number} Valid non-negative vertex index.
35
+ * @throws {RangeError} If the value cannot address a complete mesh vertex.
36
+ */
37
+ function assertTriangleIndex(value, vertexCount, meshIndex, groupName) {
38
+ if (!Number.isSafeInteger(value) || value < 0 || value >= vertexCount) {
39
+ throw new RangeError(`CjsStlFormat: mesh #${meshIndex} index group ${JSON.stringify(groupName)} ` + `contains invalid vertex index ${String(value)} for ${vertexCount} vertices`);
40
+ }
41
+ return value;
42
+ }
43
+ function cloneVertex(vertex, scale = 1) {
44
+ const result = [];
45
+ for (let component = 0; component < 3; component++) {
46
+ const value = assertFiniteNumber(vertex[component], "vertex") * scale;
47
+ result.push(assertFiniteNumber(value, "scaled vertex"));
48
+ }
49
+ return result;
50
+ }
51
+ function sanitizeSolidName(name) {
52
+ const value = String(name || DEFAULT_SOLID_NAME).replace(/\s+/g, "_").replace(/[^\w.-]/g, "_");
53
+ return value || DEFAULT_SOLID_NAME;
54
+ }
55
+
56
+ /**
57
+ * Recover the caller's solid name from this writer's binary provenance header
58
+ * while retaining compatibility with arbitrary third-party STL headers.
59
+ *
60
+ * @param {string} header Decoded and null-trimmed 80-byte binary STL header.
61
+ * @returns {string} Sanitized shared-mesh name.
62
+ */
63
+ function readBinarySolidName(header) {
64
+ return sanitizeSolidName(header.replace(/^CarbonEngineJS\s+/u, "") || DEFAULT_SOLID_NAME);
65
+ }
66
+ function formatNumber(value) {
67
+ if (!Number.isFinite(value)) return "0";
68
+ if (Object.is(value, -0)) return "0";
69
+ return Number.parseFloat(value.toPrecision(9)).toString();
70
+ }
71
+ function binaryBytes(input) {
72
+ if (input instanceof Uint8Array) return input;
73
+ if (typeof ArrayBuffer !== "undefined" && input instanceof ArrayBuffer) return new Uint8Array(input);
74
+ if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView(input)) {
75
+ return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
76
+ }
77
+ return null;
78
+ }
79
+ function readFloat32(view, offset) {
80
+ return view.getFloat32(offset, true);
81
+ }
82
+ function isZeroNormal(normal) {
83
+ return Math.hypot(normal[0], normal[1], normal[2]) <= 1e-20;
84
+ }
85
+
86
+ /**
87
+ * Return a finite unit facet normal, preferring an explicit non-zero normal
88
+ * and otherwise deriving it from triangle winding.
89
+ *
90
+ * @param {object} triangle Triangle record with three vertices and optional normal.
91
+ * @returns {number[]} Finite xyz unit normal.
92
+ * @throws {TypeError} If normal calculation produces a non-finite component.
93
+ */
94
+ function resolveTriangleNormal(triangle) {
95
+ const normal = triangle.normal && !isZeroNormal(triangle.normal) ? normalize([0, 0, 0], triangle.normal) : triangleNormal(triangle.vertices[0], triangle.vertices[1], triangle.vertices[2]);
96
+ return [assertFiniteNumber(normal[0], "facet normal"), assertFiniteNumber(normal[1], "facet normal"), assertFiniteNumber(normal[2], "facet normal")];
97
+ }
98
+
99
+ /**
100
+ * Store one finite binary STL float without silently overflowing to infinity.
101
+ *
102
+ * @param {DataView} view Destination byte view.
103
+ * @param {number} offset Byte offset of the little-endian float.
104
+ * @param {number} value Numeric component to encode.
105
+ * @param {string} feature Context included in validation errors.
106
+ * @returns {void}
107
+ * @throws {TypeError|RangeError} If the value is non-finite or exceeds float32 range.
108
+ */
109
+ function writeFloat32(view, offset, value, feature) {
110
+ const floatValue = Math.fround(assertFiniteNumber(value, feature));
111
+ if (!Number.isFinite(floatValue)) {
112
+ throw new RangeError(`CjsStlFormat: ${feature} exceeds binary STL float32 range`);
113
+ }
114
+ view.setFloat32(offset, floatValue, true);
115
+ }
116
+ function triangleWithNormal(vertices, normal) {
117
+ const fallback = triangleNormal(vertices[0], vertices[1], vertices[2]);
118
+ return {
119
+ normal: isZeroNormal(normal) ? fallback : normalize([0, 0, 0], normal),
120
+ vertices
121
+ };
122
+ }
123
+ function quantizeNumber(value, tolerance) {
124
+ if (tolerance <= 0) return formatNumber(value);
125
+ return String(Math.round(value / tolerance));
126
+ }
127
+ function quantizeVertex(vertex, tolerance) {
128
+ return `${quantizeNumber(vertex[0], tolerance)},${quantizeNumber(vertex[1], tolerance)},${quantizeNumber(vertex[2], tolerance)}`;
129
+ }
130
+ function bytesPerIndex(maxIndex) {
131
+ return maxIndex > 65535 ? 4 : 2;
132
+ }
133
+ function addIssue(issues, key, count) {
134
+ if (count > 0) issues.push({
135
+ key,
136
+ count
137
+ });
138
+ }
139
+ function rootSource(input) {
140
+ return input && typeof input === "object" && typeof input.grannyFileSource === "string" ? input.grannyFileSource : null;
141
+ }
142
+ class DisjointSet {
143
+ constructor(size) {
144
+ this.parent = new Array(size);
145
+ for (let i = 0; i < size; i++) this.parent[i] = i;
146
+ }
147
+ find(value) {
148
+ const parent = this.parent[value];
149
+ if (parent === value) return value;
150
+ this.parent[value] = this.find(parent);
151
+ return this.parent[value];
152
+ }
153
+ union(a, b) {
154
+ const ra = this.find(a),
155
+ rb = this.find(b);
156
+ if (ra !== rb) this.parent[rb] = ra;
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Convert supported input into text.
162
+ *
163
+ * @param {string|Uint8Array|ArrayBuffer|DataView} input STL text or bytes.
164
+ * @returns {string} STL text.
165
+ */
166
+ function toText(input) {
167
+ if (typeof input === "string") return input;
168
+ const bytes = binaryBytes(input);
169
+ if (bytes) return makeDecoder().decode(bytes);
170
+ throw new TypeError("CjsStlFormat: input must be STL text, bytes, or shared JSON geometry");
171
+ }
172
+
173
+ /**
174
+ * Check whether byte-like input has an exact binary STL layout.
175
+ *
176
+ * @param {string|Uint8Array|ArrayBuffer|DataView} input Candidate STL input.
177
+ * @returns {boolean} True when the byte length exactly matches a binary STL.
178
+ */
179
+ function isBinaryStl(input) {
180
+ const bytes = binaryBytes(input);
181
+ if (!bytes || bytes.byteLength < BINARY_HEADER_BYTES + BINARY_COUNT_BYTES) return false;
182
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
183
+ const triangleCount = view.getUint32(BINARY_HEADER_BYTES, true);
184
+ return BINARY_HEADER_BYTES + BINARY_COUNT_BYTES + triangleCount * BINARY_TRIANGLE_BYTES === bytes.byteLength;
185
+ }
186
+
187
+ /**
188
+ * Cheap sniff for STL-like input.
189
+ *
190
+ * @param {string|Uint8Array|ArrayBuffer|DataView} input Candidate STL input.
191
+ * @returns {boolean} True when the input looks like ASCII or binary STL.
192
+ */
193
+ function isStl(input) {
194
+ if (isBinaryStl(input)) return true;
195
+ try {
196
+ const text = toText(input);
197
+ return /^\s*solid\b/i.test(text) && /\bfacet\s+normal\b/i.test(text) && /\bvertex\b/i.test(text);
198
+ } catch {
199
+ return false;
200
+ }
201
+ }
202
+
203
+ /**
204
+ * Parse ASCII STL text into triangle records.
205
+ *
206
+ * @param {string} text ASCII STL text.
207
+ * @returns {object} Parsed STL payload.
208
+ */
209
+ function parseAsciiStl(text) {
210
+ const lines = text.split(/\r?\n/),
211
+ triangles = [];
212
+ let name = DEFAULT_SOLID_NAME,
213
+ currentNormal = [0, 0, 0],
214
+ vertices = [];
215
+ for (const rawLine of lines) {
216
+ const line = rawLine.trim();
217
+ if (!line) continue;
218
+ const solid = /^solid(?:\s+(.+))?$/i.exec(line);
219
+ if (solid) {
220
+ name = solid[1] ? solid[1].trim() : name;
221
+ continue;
222
+ }
223
+ const facet = /^facet\s+normal\s+(.+)$/i.exec(line);
224
+ if (facet) {
225
+ const values = facet[1].trim().split(/\s+/).map(Number);
226
+ currentNormal = values.length >= 3 && values.every(Number.isFinite) ? [values[0], values[1], values[2]] : [0, 0, 0];
227
+ vertices = [];
228
+ continue;
229
+ }
230
+ const vertex = /^vertex\s+(.+)$/i.exec(line);
231
+ if (vertex) {
232
+ const values = vertex[1].trim().split(/\s+/).map(Number);
233
+ if (values.length < 3 || !values.every(Number.isFinite)) {
234
+ throw new Error("CjsStlFormat: ASCII STL contains a malformed vertex line");
235
+ }
236
+ vertices.push([values[0], values[1], values[2]]);
237
+ if (vertices.length === 3) {
238
+ triangles.push(triangleWithNormal(vertices, currentNormal));
239
+ vertices = [];
240
+ }
241
+ }
242
+ }
243
+ if (!triangles.length) {
244
+ throw new Error("CjsStlFormat: ASCII STL contains no triangles");
245
+ }
246
+ return {
247
+ format: "ascii",
248
+ name: sanitizeSolidName(name),
249
+ triangles
250
+ };
251
+ }
252
+
253
+ /**
254
+ * Parse binary STL bytes into triangle records.
255
+ * Headers written as `CarbonEngineJS <solidName>` retain their provenance in
256
+ * the file while exposing `<solidName>` as parsed mesh metadata.
257
+ *
258
+ * @param {Uint8Array} bytes Binary STL bytes.
259
+ * @returns {object} Parsed format/name metadata and triangle records.
260
+ * @throws {Error} If byte length/count disagree or no triangles are present.
261
+ */
262
+ function parseBinaryStl(bytes) {
263
+ if (!isBinaryStl(bytes)) {
264
+ throw new Error("CjsStlFormat: binary STL byte length does not match its triangle count");
265
+ }
266
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength),
267
+ header = makeDecoder().decode(bytes.subarray(0, BINARY_HEADER_BYTES)).replace(/\0+$/g, "").trim(),
268
+ count = view.getUint32(BINARY_HEADER_BYTES, true),
269
+ triangles = [];
270
+ let offset = BINARY_HEADER_BYTES + BINARY_COUNT_BYTES;
271
+ for (let i = 0; i < count; i++) {
272
+ const normal = [readFloat32(view, offset), readFloat32(view, offset + 4), readFloat32(view, offset + 8)];
273
+ const vertices = [];
274
+ for (let v = 0; v < 3; v++) {
275
+ const vo = offset + 12 + v * 12;
276
+ vertices.push([readFloat32(view, vo), readFloat32(view, vo + 4), readFloat32(view, vo + 8)]);
277
+ }
278
+ triangles.push(triangleWithNormal(vertices, normal));
279
+ offset += BINARY_TRIANGLE_BYTES;
280
+ }
281
+ if (!triangles.length) {
282
+ throw new Error("CjsStlFormat: binary STL contains no triangles");
283
+ }
284
+ return {
285
+ format: "binary",
286
+ name: readBinarySolidName(header),
287
+ triangles
288
+ };
289
+ }
290
+
291
+ /**
292
+ * Parse STL text or bytes.
293
+ *
294
+ * @param {string|Uint8Array|ArrayBuffer|DataView} input STL text or bytes.
295
+ * @returns {object} Parsed STL payload.
296
+ */
297
+ function parseStl(input) {
298
+ const bytes = binaryBytes(input);
299
+ if (bytes && isBinaryStl(bytes)) return parseBinaryStl(bytes);
300
+ return parseAsciiStl(toText(input));
301
+ }
302
+
303
+ /**
304
+ * Build the shared CarbonEngineJS JSON mesh schema from STL triangles.
305
+ *
306
+ * @param {object[]} triangles Triangle records.
307
+ * @param {object} values Normalized format values.
308
+ * @param {object} [source] Parsed STL source metadata.
309
+ * @returns {object} Shared JSON graph.
310
+ */
311
+ function trianglesToJson(triangles, values, source = {}) {
312
+ const positions = [],
313
+ normals = [],
314
+ faces = [],
315
+ vertexByKey = new Map();
316
+ const addVertex = (vertex, normal) => {
317
+ if (values.weldVertices) {
318
+ const key = quantizeVertex(vertex, values.weldTolerance);
319
+ const existing = vertexByKey.get(key);
320
+ if (existing !== undefined) return existing;
321
+ const next = positions.length / 3;
322
+ vertexByKey.set(key, next);
323
+ positions.push(vertex[0], vertex[1], vertex[2]);
324
+ return next;
325
+ }
326
+ const next = positions.length / 3;
327
+ positions.push(vertex[0], vertex[1], vertex[2]);
328
+ normals.push(normal[0], normal[1], normal[2]);
329
+ return next;
330
+ };
331
+ for (const triangle of triangles) {
332
+ const vertices = triangle.vertices.map(vertex => cloneVertex(vertex));
333
+ const normal = triangle.normal && !isZeroNormal(triangle.normal) ? normalize([0, 0, 0], triangle.normal) : triangleNormal(vertices[0], vertices[1], vertices[2]);
334
+ for (const vertex of vertices) {
335
+ faces.push(addVertex(vertex, normal));
336
+ }
337
+ }
338
+ const resolvedNormals = values.weldVertices ? generateNormals(positions, faces) : normals;
339
+ const bounds = computeBoundsFromPositions(positions);
340
+ return {
341
+ grannyFileFormatRevision: 0,
342
+ grannyFileSource: values.source,
343
+ meshes: [{
344
+ name: source.name || values.solidName,
345
+ morphTargets: [],
346
+ minBounds: bounds.minBounds,
347
+ maxBounds: bounds.maxBounds,
348
+ boneBindings: [],
349
+ vertex: {
350
+ position: positions,
351
+ blendIndice: [],
352
+ tangent: [],
353
+ normal: resolvedNormals,
354
+ texcoord0: [],
355
+ texcoord1: [],
356
+ binormal: [],
357
+ blendWeight: []
358
+ },
359
+ indices: [{
360
+ name: "default",
361
+ bytesPerIndex: bytesPerIndex(Math.max(0, positions.length / 3 - 1)),
362
+ faces
363
+ }]
364
+ }],
365
+ models: [],
366
+ animations: []
367
+ };
368
+ }
369
+
370
+ /**
371
+ * Gather triangle records from the shared JSON geometry schema.
372
+ * Meshes and index groups are flattened in encounter order. Coordinates are
373
+ * copied and scaled, so the caller's shared graph remains unchanged. Only
374
+ * positions, optional normals, and triangular indices participate in STL.
375
+ *
376
+ * @param {object} input Shared JSON graph or mesh record.
377
+ * @param {object} values Normalized format values.
378
+ * @returns {object[]} Scaled triangle records ready for inspection/encoding.
379
+ * @throws {TypeError|RangeError|Error} If geometry, coordinates, or indices are invalid.
380
+ */
381
+ function jsonToTriangles(input, values) {
382
+ const root = input && input.meshes ? input : {
383
+ meshes: [input]
384
+ },
385
+ triangles = [];
386
+ if (!root || !Array.isArray(root.meshes)) {
387
+ throw new TypeError("CjsStlFormat: write input must be a shared JSON root or mesh");
388
+ }
389
+ for (const [meshIndex, mesh] of root.meshes.entries()) {
390
+ const vertex = mesh && mesh.vertex,
391
+ positions = vertex && vertex.position,
392
+ normals = vertex && vertex.normal;
393
+ if (!positions || positions.length % 3 !== 0) {
394
+ throw new Error(`CjsStlFormat: mesh #${meshIndex} must provide flat vertex.position triples`);
395
+ }
396
+ for (const group of mesh.indices || []) {
397
+ const faces = group && group.faces;
398
+ if (!faces) continue;
399
+ const groupName = group.name || "default";
400
+ if (faces.length % 3 !== 0) {
401
+ throw new Error(`CjsStlFormat: mesh #${meshIndex} index group ${JSON.stringify(groupName)} is not triangular`);
402
+ }
403
+ for (let i = 0; i < faces.length; i += 3) {
404
+ const vertexCount = positions.length / 3,
405
+ ia = assertTriangleIndex(faces[i], vertexCount, meshIndex, groupName) * 3,
406
+ ib = assertTriangleIndex(faces[i + 1], vertexCount, meshIndex, groupName) * 3,
407
+ ic = assertTriangleIndex(faces[i + 2], vertexCount, meshIndex, groupName) * 3;
408
+ const vertices = [cloneVertex([positions[ia], positions[ia + 1], positions[ia + 2]], values.scale), cloneVertex([positions[ib], positions[ib + 1], positions[ib + 2]], values.scale), cloneVertex([positions[ic], positions[ic + 1], positions[ic + 2]], values.scale)];
409
+ if (values.skipDegenerate && isDegenerateTriangle(vertices[0], vertices[1], vertices[2])) {
410
+ continue;
411
+ }
412
+ let normal = triangleNormal(vertices[0], vertices[1], vertices[2]);
413
+ if (!values.recalculateNormals && normals && normals.length >= positions.length) {
414
+ const averaged = normalize([0, 0, 0], [normals[ia] + normals[ib] + normals[ic], normals[ia + 1] + normals[ib + 1] + normals[ic + 1], normals[ia + 2] + normals[ib + 2] + normals[ic + 2]]);
415
+ if (!isZeroNormal(averaged)) normal = averaged;
416
+ }
417
+ triangles.push({
418
+ normal,
419
+ vertices
420
+ });
421
+ }
422
+ }
423
+ }
424
+ return triangles;
425
+ }
426
+
427
+ /**
428
+ * Convert STL or JSON input into triangle records for inspection.
429
+ *
430
+ * @param {any} input STL text/bytes or shared JSON.
431
+ * @param {object} values Normalized format values.
432
+ * @returns {object} Inspection source and triangles.
433
+ */
434
+ function trianglesFromInput(input, values) {
435
+ if (input && typeof input === "object" && (input.meshes || input.vertex)) {
436
+ return {
437
+ format: "json",
438
+ source: rootSource(input) || values.source,
439
+ triangles: jsonToTriangles(input, {
440
+ ...values,
441
+ skipDegenerate: false
442
+ })
443
+ };
444
+ }
445
+ const bytes = binaryBytes(input);
446
+ const parsed = parseStl(input);
447
+ return {
448
+ format: parsed.format,
449
+ name: parsed.name,
450
+ byteLength: bytes ? bytes.byteLength : typeof input === "string" ? makeEncoder().encode(input).byteLength : 0,
451
+ source: values.source,
452
+ triangles: parsed.triangles
453
+ };
454
+ }
455
+
456
+ /**
457
+ * Write triangle records as ASCII STL text.
458
+ * Solid names and numeric components are normalized deterministically. The
459
+ * function does not mutate triangle records.
460
+ *
461
+ * @param {object[]} triangles Triangle records.
462
+ * @param {string} solidName STL solid name.
463
+ * @returns {string} ASCII STL text.
464
+ * @throws {TypeError} If a facet normal cannot be represented as finite text.
465
+ */
466
+ function writeAsciiStl(triangles, solidName) {
467
+ const lines = [`solid ${sanitizeSolidName(solidName)}`];
468
+ for (const triangle of triangles) {
469
+ const normal = resolveTriangleNormal(triangle);
470
+ lines.push(` facet normal ${formatNumber(normal[0])} ${formatNumber(normal[1])} ${formatNumber(normal[2])}`);
471
+ lines.push(" outer loop");
472
+ for (const vertex of triangle.vertices) {
473
+ lines.push(` vertex ${formatNumber(vertex[0])} ${formatNumber(vertex[1])} ${formatNumber(vertex[2])}`);
474
+ }
475
+ lines.push(" endloop");
476
+ lines.push(" endfacet");
477
+ }
478
+ lines.push(`endsolid ${sanitizeSolidName(solidName)}`);
479
+ return `${lines.join("\n")}\n`;
480
+ }
481
+
482
+ /**
483
+ * Write triangle records as binary STL bytes.
484
+ * Output uses the standard 80-byte header, little-endian uint32 triangle
485
+ * count, 50-byte triangle records, and zero attribute words. The header keeps
486
+ * a `CarbonEngineJS` provenance prefix. Every numeric component is checked for
487
+ * finite float32 representation before storage.
488
+ *
489
+ * @param {object[]} triangles Triangle records.
490
+ * @param {string} solidName STL solid name.
491
+ * @returns {Uint8Array} Binary STL bytes.
492
+ * @throws {TypeError|RangeError} If count or numeric components exceed binary STL's representable domain.
493
+ */
494
+ function writeBinaryStl(triangles, solidName) {
495
+ if (triangles.length > 0xffffffff) {
496
+ throw new RangeError("CjsStlFormat: binary STL cannot contain more than 4294967295 triangles");
497
+ }
498
+ const bytes = new Uint8Array(BINARY_HEADER_BYTES + BINARY_COUNT_BYTES + triangles.length * BINARY_TRIANGLE_BYTES),
499
+ view = new DataView(bytes.buffer),
500
+ header = makeEncoder().encode(`CarbonEngineJS ${sanitizeSolidName(solidName)}`);
501
+ bytes.set(header.subarray(0, BINARY_HEADER_BYTES), 0);
502
+ view.setUint32(BINARY_HEADER_BYTES, triangles.length, true);
503
+ let offset = BINARY_HEADER_BYTES + BINARY_COUNT_BYTES;
504
+ for (const triangle of triangles) {
505
+ const normal = resolveTriangleNormal(triangle);
506
+ for (let c = 0; c < 3; c++) {
507
+ writeFloat32(view, offset + c * 4, normal[c], "facet normal");
508
+ }
509
+ for (let v = 0; v < 3; v++) {
510
+ const vertex = triangle.vertices[v];
511
+ for (let c = 0; c < 3; c++) {
512
+ writeFloat32(view, offset + 12 + v * 12 + c * 4, vertex[c], "vertex coordinate");
513
+ }
514
+ }
515
+ view.setUint16(offset + 48, 0, true);
516
+ offset += BINARY_TRIANGLE_BYTES;
517
+ }
518
+ return bytes;
519
+ }
520
+
521
+ /**
522
+ * Inspect triangle topology for common 3D-printing blockers.
523
+ *
524
+ * @param {object[]} triangles Triangle records.
525
+ * @param {object} values Normalized format values.
526
+ * @param {object} [source] Source metadata.
527
+ * @returns {object} Printability report.
528
+ */
529
+ function inspectTriangles(triangles, values, source = {}) {
530
+ const vertices = new Map(),
531
+ vertexKeys = [],
532
+ edges = new Map(),
533
+ dsu = new DisjointSet(triangles.length),
534
+ issues = [];
535
+ let degenerateTriangleCount = 0,
536
+ validTriangleCount = 0;
537
+ const vertexId = vertex => {
538
+ const key = quantizeVertex(vertex, values.weldTolerance);
539
+ const existing = vertices.get(key);
540
+ if (existing !== undefined) return existing;
541
+ const next = vertexKeys.length;
542
+ vertices.set(key, next);
543
+ vertexKeys.push(key);
544
+ return next;
545
+ };
546
+ const addEdge = (triangleIndex, a, b) => {
547
+ const ka = vertexKeys[a],
548
+ kb = vertexKeys[b],
549
+ key = ka < kb ? `${ka}|${kb}` : `${kb}|${ka}`,
550
+ sign = ka < kb ? 1 : -1,
551
+ entry = edges.get(key) || [];
552
+ entry.push({
553
+ triangleIndex,
554
+ sign
555
+ });
556
+ edges.set(key, entry);
557
+ };
558
+ for (let triangleIndex = 0; triangleIndex < triangles.length; triangleIndex++) {
559
+ const triangle = triangles[triangleIndex];
560
+ if (isDegenerateTriangle(triangle.vertices[0], triangle.vertices[1], triangle.vertices[2], values.weldTolerance)) {
561
+ degenerateTriangleCount++;
562
+ continue;
563
+ }
564
+ const ids = triangle.vertices.map(vertexId);
565
+ if (new Set(ids).size !== 3) {
566
+ degenerateTriangleCount++;
567
+ continue;
568
+ }
569
+ validTriangleCount++;
570
+ addEdge(triangleIndex, ids[0], ids[1]);
571
+ addEdge(triangleIndex, ids[1], ids[2]);
572
+ addEdge(triangleIndex, ids[2], ids[0]);
573
+ }
574
+ let openEdgeCount = 0,
575
+ nonManifoldEdgeCount = 0,
576
+ inconsistentWindingEdgeCount = 0;
577
+ for (const occurrences of edges.values()) {
578
+ if (occurrences.length === 1) {
579
+ openEdgeCount++;
580
+ continue;
581
+ }
582
+ if (occurrences.length > 2) {
583
+ nonManifoldEdgeCount++;
584
+ }
585
+ if (occurrences.length === 2 && occurrences[0].sign === occurrences[1].sign) {
586
+ inconsistentWindingEdgeCount++;
587
+ }
588
+ for (let i = 1; i < occurrences.length; i++) {
589
+ dsu.union(occurrences[0].triangleIndex, occurrences[i].triangleIndex);
590
+ }
591
+ }
592
+ const shells = new Set();
593
+ for (const occurrences of edges.values()) {
594
+ for (const occurrence of occurrences) {
595
+ shells.add(dsu.find(occurrence.triangleIndex));
596
+ }
597
+ }
598
+ addIssue(issues, "no_triangles", triangles.length === 0 ? 1 : 0);
599
+ addIssue(issues, "degenerate_triangles", degenerateTriangleCount);
600
+ addIssue(issues, "open_edges", openEdgeCount);
601
+ addIssue(issues, "non_manifold_edges", nonManifoldEdgeCount);
602
+ addIssue(issues, "inconsistent_winding_edges", inconsistentWindingEdgeCount);
603
+ const bounds = computeBoundsFromTriangles(triangles);
604
+ const printable = triangles.length > 0 && degenerateTriangleCount === 0 && openEdgeCount === 0 && nonManifoldEdgeCount === 0 && inconsistentWindingEdgeCount === 0;
605
+ return {
606
+ format: source.format || "stl",
607
+ name: source.name || "",
608
+ byteLength: source.byteLength || 0,
609
+ source: source.source || values.source,
610
+ triangleCount: triangles.length,
611
+ validTriangleCount,
612
+ vertexCount: vertices.size,
613
+ edgeCount: edges.size,
614
+ shellCount: validTriangleCount > 0 ? shells.size : 0,
615
+ openEdgeCount,
616
+ nonManifoldEdgeCount,
617
+ inconsistentWindingEdgeCount,
618
+ degenerateTriangleCount,
619
+ bounds: {
620
+ min: bounds.minBounds,
621
+ max: bounds.maxBounds
622
+ },
623
+ printable,
624
+ issues
625
+ };
626
+ }
627
+
628
+ export { inspectTriangles, isBinaryStl, isStl, jsonToTriangles, parseAsciiStl, parseBinaryStl, parseStl, toText, trianglesFromInput, trianglesToJson, writeAsciiStl, writeBinaryStl };
629
+ //# sourceMappingURL=stl.js.map