@carbonenginejs/runtime-resource 0.8.0 → 0.9.1

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