topotopo 0.4.0 → 0.5.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 (336) hide show
  1. package/NOTICE +10 -10
  2. package/README.md +460 -117
  3. package/dist/cli.js +323 -146
  4. package/dist/config.d.ts +48 -0
  5. package/dist/config.js +170 -0
  6. package/dist/core/bake.d.ts +14 -3
  7. package/dist/core/bake.js +153 -4
  8. package/dist/core/bevel.d.ts +3 -1
  9. package/dist/core/bevel.js +76 -3
  10. package/dist/core/decimate.d.ts +65 -0
  11. package/dist/core/decimate.js +409 -3
  12. package/dist/core/erosion.d.ts +37 -0
  13. package/dist/core/erosion.js +41 -1
  14. package/dist/core/geometry.d.ts +5 -1
  15. package/dist/core/geometry.js +203 -3
  16. package/dist/core/heightfield.d.ts +27 -4
  17. package/dist/core/heightfield.js +54 -16
  18. package/dist/core/intrinsics.d.ts +7 -0
  19. package/dist/core/intrinsics.js +94 -0
  20. package/dist/core/manifold.d.ts +12 -1
  21. package/dist/core/manifold.js +78 -6
  22. package/dist/core/materials.d.ts +7 -0
  23. package/dist/core/materials.js +45 -0
  24. package/dist/core/noise.d.ts +9 -0
  25. package/dist/core/noise.js +10 -1
  26. package/dist/core/polymerge.d.ts +21 -0
  27. package/dist/core/polymerge.js +327 -0
  28. package/dist/core/repair.d.ts +2 -0
  29. package/dist/core/repair.js +2 -0
  30. package/dist/core/report.d.ts +70 -0
  31. package/dist/core/report.js +275 -0
  32. package/dist/core/scene.js +2 -1
  33. package/dist/core/sha256.d.ts +4 -0
  34. package/dist/core/sha256.js +69 -0
  35. package/dist/core/shapes.d.ts +3 -0
  36. package/dist/core/shapes.js +34 -0
  37. package/dist/core/snippet-lib.d.ts +14 -1
  38. package/dist/core/snippet-lib.js +39 -13
  39. package/dist/core/tangents.d.ts +2 -0
  40. package/dist/core/tangents.js +5 -1
  41. package/dist/core/texnoise.d.ts +6 -1
  42. package/dist/core/texnoise.js +6 -2
  43. package/dist/core/texsdf.d.ts +131 -0
  44. package/dist/core/texsdf.js +637 -0
  45. package/dist/core/texture.d.ts +163 -9
  46. package/dist/core/texture.js +844 -20
  47. package/dist/core/topology.d.ts +10 -0
  48. package/dist/core/topology.js +168 -0
  49. package/dist/core/unwrap.d.ts +72 -0
  50. package/dist/core/unwrap.js +800 -0
  51. package/dist/core/usercode.d.ts +27 -0
  52. package/dist/core/usercode.js +87 -0
  53. package/dist/core/uv.d.ts +4 -18
  54. package/dist/core/uv.js +35 -188
  55. package/dist/core/uvislands.d.ts +62 -0
  56. package/dist/core/uvislands.js +574 -0
  57. package/dist/core/uvoverlap.d.ts +58 -0
  58. package/dist/core/uvoverlap.js +220 -0
  59. package/dist/core/uvpack.d.ts +64 -0
  60. package/dist/core/uvpack.js +628 -0
  61. package/dist/core/uvreport.d.ts +61 -0
  62. package/dist/core/uvreport.js +207 -143
  63. package/dist/core/wrangle.d.ts +6 -1
  64. package/dist/core/wrangle.js +27 -16
  65. package/dist/core/xatlas.d.ts +16 -1
  66. package/dist/core/xatlas.js +66 -62
  67. package/dist/engines.d.ts +63 -0
  68. package/dist/engines.js +180 -0
  69. package/dist/explain.d.ts +4 -3
  70. package/dist/explain.js +129 -12
  71. package/dist/graph/engine.d.ts +92 -29
  72. package/dist/graph/engine.js +298 -148
  73. package/dist/graph/expr.d.ts +6 -3
  74. package/dist/graph/expr.js +18 -8
  75. package/dist/graph/outputs.d.ts +23 -0
  76. package/dist/graph/outputs.js +41 -0
  77. package/dist/graph/packages.d.ts +72 -0
  78. package/dist/graph/packages.js +261 -0
  79. package/dist/graph/parallel.d.ts +3 -1
  80. package/dist/graph/parallel.js +4 -1
  81. package/dist/graph/params.d.ts +6 -0
  82. package/dist/graph/params.js +34 -7
  83. package/dist/graph/scope.d.ts +55 -0
  84. package/dist/graph/scope.js +14 -0
  85. package/dist/graph/types.d.ts +75 -12
  86. package/dist/graph/types.js +4 -2
  87. package/dist/graph/vars.d.ts +16 -0
  88. package/dist/graph/vars.js +80 -0
  89. package/dist/host/artifacts.d.ts +10 -1
  90. package/dist/host/artifacts.js +37 -6
  91. package/dist/host/cook.d.ts +241 -0
  92. package/dist/host/cook.js +844 -0
  93. package/dist/host/export-targets.d.ts +42 -5
  94. package/dist/host/export-targets.js +72 -13
  95. package/dist/host/godot-commands.d.ts +4 -0
  96. package/dist/host/godot-commands.js +21 -0
  97. package/dist/host/godot.d.ts +183 -0
  98. package/dist/host/godot.js +916 -0
  99. package/dist/host/node.d.ts +12 -7
  100. package/dist/host/node.js +27 -9
  101. package/dist/host/pool.js +51 -2
  102. package/dist/host/sidecars.d.ts +8 -0
  103. package/dist/host/sidecars.js +50 -0
  104. package/dist/host/types.d.ts +19 -6
  105. package/dist/host/version.d.ts +1 -0
  106. package/dist/host/version.js +3 -0
  107. package/dist/host/worker.js +5 -2
  108. package/dist/index.d.ts +2 -2
  109. package/dist/index.js +1 -1
  110. package/dist/inspect.d.ts +80 -2
  111. package/dist/inspect.js +265 -30
  112. package/dist/io/common.d.ts +25 -5
  113. package/dist/io/export.js +2 -1
  114. package/dist/io/files.d.ts +23 -4
  115. package/dist/io/files.js +60 -8
  116. package/dist/io/gltf.js +134 -47
  117. package/dist/io/heightmap.d.ts +3 -0
  118. package/dist/io/heightmap.js +1 -0
  119. package/dist/io/import.js +10 -0
  120. package/dist/io/inspect-scene.d.ts +55 -0
  121. package/dist/io/inspect-scene.js +155 -0
  122. package/dist/io/kinds.d.ts +81 -0
  123. package/dist/io/kinds.js +163 -0
  124. package/dist/io/points.d.ts +2 -1
  125. package/dist/io/points.js +3 -1
  126. package/dist/io/sidecars.d.ts +24 -0
  127. package/dist/io/sidecars.js +57 -0
  128. package/dist/io/source.d.ts +65 -0
  129. package/dist/io/source.js +112 -0
  130. package/dist/io/targets.d.ts +47 -3
  131. package/dist/io/targets.js +148 -13
  132. package/dist/io/textures.js +21 -1
  133. package/dist/io/unreal.js +5 -1
  134. package/dist/mcp/docs.d.ts +10 -1
  135. package/dist/mcp/docs.js +786 -143
  136. package/dist/mcp/inputs.d.ts +12 -5
  137. package/dist/mcp/inputs.js +50 -13
  138. package/dist/mcp/server.js +56 -27
  139. package/dist/mcp/tools.d.ts +14 -7
  140. package/dist/mcp/tools.js +196 -103
  141. package/dist/mcp/verify.d.ts +2 -2
  142. package/dist/mcp/verify.js +1 -1
  143. package/dist/mcp/workspace.d.ts +15 -0
  144. package/dist/mcp/workspace.js +349 -0
  145. package/dist/nodes/attributes.js +198 -1
  146. package/dist/nodes/bake.js +151 -47
  147. package/dist/nodes/beam.d.ts +1 -0
  148. package/dist/nodes/beam.js +201 -0
  149. package/dist/nodes/bevel.js +51 -3
  150. package/dist/nodes/cloth.js +2 -0
  151. package/dist/nodes/code.js +21 -9
  152. package/dist/nodes/curves.js +433 -93
  153. package/dist/nodes/flow.js +53 -33
  154. package/dist/nodes/generate.js +12 -38
  155. package/dist/nodes/heightfield.js +248 -77
  156. package/dist/nodes/imageops.js +16 -19
  157. package/dist/nodes/index.d.ts +1 -0
  158. package/dist/nodes/index.js +1 -0
  159. package/dist/nodes/material.js +89 -24
  160. package/dist/nodes/measure.js +43 -17
  161. package/dist/nodes/particles.js +2 -0
  162. package/dist/nodes/pcg.js +6 -5
  163. package/dist/nodes/procedural.js +4 -3
  164. package/dist/nodes/remesh.js +71 -15
  165. package/dist/nodes/scene.js +4 -2
  166. package/dist/nodes/sdf.js +10 -5
  167. package/dist/nodes/solid.js +20 -5
  168. package/dist/nodes/splines.d.ts +15 -1
  169. package/dist/nodes/splines.js +112 -105
  170. package/dist/nodes/texture.d.ts +21 -6
  171. package/dist/nodes/texture.js +1318 -185
  172. package/dist/nodes/topology.d.ts +7 -0
  173. package/dist/nodes/topology.js +133 -6
  174. package/dist/nodes/transform.js +6 -2
  175. package/dist/nodes/uv.js +192 -174
  176. package/dist/nodes/wasmcall.js +5 -1
  177. package/dist/open.d.ts +19 -0
  178. package/dist/open.js +12 -0
  179. package/dist/package.d.ts +288 -0
  180. package/dist/package.js +772 -0
  181. package/dist/packages/check.d.ts +32 -0
  182. package/dist/packages/check.js +169 -0
  183. package/dist/packages/commands.d.ts +57 -0
  184. package/dist/packages/commands.js +537 -0
  185. package/dist/packages/registry.d.ts +796 -0
  186. package/dist/packages/registry.js +2998 -0
  187. package/dist/packages/update.d.ts +124 -0
  188. package/dist/packages/update.js +476 -0
  189. package/dist/render/options.d.ts +2 -0
  190. package/dist/render/options.js +44 -5
  191. package/dist/render/preview.d.ts +15 -4
  192. package/dist/render/preview.js +6 -4
  193. package/dist/render/raster.d.ts +66 -5
  194. package/dist/render/raster.js +506 -138
  195. package/dist/render/texview.d.ts +6 -0
  196. package/dist/render/texview.js +27 -0
  197. package/dist/scan.d.ts +61 -0
  198. package/dist/scan.js +228 -0
  199. package/dist/session.d.ts +311 -0
  200. package/dist/session.js +849 -0
  201. package/dist/viewer/app/api.js +48 -6
  202. package/dist/viewer/app/cooking.js +78 -0
  203. package/dist/viewer/app/embed.js +27 -7
  204. package/dist/viewer/app/export-popover.js +118 -16
  205. package/dist/viewer/app/grid.js +5 -1
  206. package/dist/viewer/app/guides.js +122 -0
  207. package/dist/viewer/app/keymap.js +6 -3
  208. package/dist/viewer/app/layers.js +4 -4
  209. package/dist/viewer/app/main.js +185 -52
  210. package/dist/viewer/app/markers.js +60 -0
  211. package/dist/viewer/app/outliner.js +72 -27
  212. package/dist/viewer/app/output-info.js +45 -0
  213. package/dist/viewer/app/outputs.css +147 -8
  214. package/dist/viewer/app/outputs.js +168 -54
  215. package/dist/viewer/app/packages.js +614 -0
  216. package/dist/viewer/app/props.js +176 -52
  217. package/dist/viewer/app/scene.js +30 -5
  218. package/dist/viewer/app/select.js +4 -3
  219. package/dist/viewer/app/status.js +12 -15
  220. package/dist/viewer/app/style.css +65 -7
  221. package/dist/viewer/app/vars.js +47 -0
  222. package/dist/viewer/app/welcome.js +72 -0
  223. package/dist/viewer/graph-file.d.ts +62 -0
  224. package/dist/viewer/graph-file.js +175 -0
  225. package/dist/viewer/index.html +23 -10
  226. package/dist/viewer/json-edit.d.ts +13 -0
  227. package/dist/viewer/json-edit.js +274 -0
  228. package/dist/viewer/outputs.d.ts +49 -5
  229. package/dist/viewer/outputs.js +264 -56
  230. package/dist/viewer/packages.d.ts +121 -0
  231. package/dist/viewer/packages.js +584 -0
  232. package/dist/viewer/server.d.ts +14 -9
  233. package/dist/viewer/server.js +266 -28
  234. package/dist/web/app/web.css +419 -0
  235. package/dist/web/app/web.js +188 -0
  236. package/dist/{gallery → web}/bake.d.ts +4 -4
  237. package/dist/{gallery → web}/bake.js +24 -15
  238. package/dist/web/folder-page.d.ts +101 -0
  239. package/dist/web/folder-page.js +146 -0
  240. package/dist/web/folders.d.ts +280 -0
  241. package/dist/web/folders.js +970 -0
  242. package/dist/web/library.d.ts +91 -0
  243. package/dist/web/library.js +228 -0
  244. package/dist/web/markdown.d.ts +45 -0
  245. package/dist/web/markdown.js +677 -0
  246. package/dist/web/pages.d.ts +258 -0
  247. package/dist/web/pages.js +301 -0
  248. package/dist/web/server.d.ts +24 -0
  249. package/dist/web/server.js +1068 -0
  250. package/dist/workspace.d.ts +88 -118
  251. package/dist/workspace.js +358 -460
  252. package/integrations/godot/addons/topotopo/LICENSE +202 -0
  253. package/integrations/godot/addons/topotopo/README.md +57 -0
  254. package/integrations/godot/addons/topotopo/context_menu.gd +43 -0
  255. package/integrations/godot/addons/topotopo/dock.gd +266 -0
  256. package/integrations/godot/addons/topotopo/dock.tscn +72 -0
  257. package/integrations/godot/addons/topotopo/export_filter.gd +72 -0
  258. package/integrations/godot/addons/topotopo/gltf_instancing.gd +131 -0
  259. package/integrations/godot/addons/topotopo/icons/topotopo.svg +1 -0
  260. package/integrations/godot/addons/topotopo/inspector.gd +38 -0
  261. package/integrations/godot/addons/topotopo/instances_post_import.gd +111 -0
  262. package/integrations/godot/addons/topotopo/package.gd +23 -0
  263. package/integrations/godot/addons/topotopo/package_importer.gd +187 -0
  264. package/integrations/godot/addons/topotopo/plugin.cfg +7 -0
  265. package/integrations/godot/addons/topotopo/plugin.gd +970 -0
  266. package/integrations/godot/addons/topotopo/record.gd +435 -0
  267. package/integrations/godot/addons/topotopo/runner.gd +458 -0
  268. package/integrations/godot/addons/topotopo/tools/check.gd +42 -0
  269. package/integrations/godot/addons/topotopo/watcher.gd +199 -0
  270. package/kernels/pkg/README.md +2 -1
  271. package/kernels/pkg-simd/README.md +2 -1
  272. package/library/architecture/versions/1.0/architecture.topo +12 -0
  273. package/{shelf → library/architecture/versions/1.0/graphs}/arch.json +3 -3
  274. package/{shelf → library/architecture/versions/1.0/graphs}/beam_truss.json +6 -6
  275. package/{shelf → library/architecture/versions/1.0/graphs}/brick_wall.json +8 -8
  276. package/{shelf → library/architecture/versions/1.0/graphs}/door_frame.json +3 -3
  277. package/{shelf → library/architecture/versions/1.0/graphs}/hex_grid_floor.json +3 -2
  278. package/{shelf → library/architecture/versions/1.0/graphs}/house.json +8 -8
  279. package/library/architecture/versions/1.0/graphs/lineup.json +42 -0
  280. package/{shelf → library/architecture/versions/1.0/graphs}/pillar.json +3 -2
  281. package/{shelf → library/architecture/versions/1.0/graphs}/railing.json +5 -5
  282. package/{shelf → library/architecture/versions/1.0/graphs}/roof_gable.json +2 -2
  283. package/{shelf → library/architecture/versions/1.0/graphs}/roof_hip.json +2 -2
  284. package/{shelf → library/architecture/versions/1.0/graphs}/roof_skeleton.json +2 -1
  285. package/{shelf → library/architecture/versions/1.0/graphs}/scaffold.json +4 -4
  286. package/{shelf → library/architecture/versions/1.0/graphs}/spiral_stairs.json +3 -2
  287. package/{shelf → library/architecture/versions/1.0/graphs}/stairs.json +6 -6
  288. package/{shelf → library/architecture/versions/1.0/graphs}/tile_floor.json +3 -2
  289. package/{shelf → library/architecture/versions/1.0/graphs}/wall_segment.json +10 -10
  290. package/{shelf → library/architecture/versions/1.0/graphs}/window_frame.json +2 -2
  291. package/library/architecture/versions/1.0/version.json +1119 -0
  292. package/{shelf → library/nature/versions/1.0/graphs}/bush.json +2 -2
  293. package/{shelf → library/nature/versions/1.0/graphs}/cliff_block.json +4 -3
  294. package/{shelf → library/nature/versions/1.0/graphs}/forest_patch.json +5 -5
  295. package/{shelf → library/nature/versions/1.0/graphs}/grass_clumps.json +2 -2
  296. package/library/nature/versions/1.0/graphs/lineup.json +24 -0
  297. package/{shelf → library/nature/versions/1.0/graphs}/log.json +6 -6
  298. package/{shelf → library/nature/versions/1.0/graphs}/rock.json +5 -4
  299. package/{shelf → library/nature/versions/1.0/graphs}/scatter_rocks.json +5 -5
  300. package/{shelf → library/nature/versions/1.0/graphs}/tree_lowpoly.json +3 -2
  301. package/library/nature/versions/1.0/nature.topo +12 -0
  302. package/library/nature/versions/1.0/version.json +534 -0
  303. package/{shelf → library/props/versions/1.0/graphs}/barrel.json +5 -4
  304. package/{shelf → library/props/versions/1.0/graphs}/crate.json +3 -3
  305. package/library/props/versions/1.0/graphs/lineup.json +18 -0
  306. package/{shelf → library/props/versions/1.0/graphs}/pallet.json +4 -3
  307. package/{shelf → library/props/versions/1.0/graphs}/pipe_run.json +3 -3
  308. package/{shelf → library/props/versions/1.0/graphs}/sandbag_wall.json +5 -5
  309. package/library/props/versions/1.0/props.topo +12 -0
  310. package/library/props/versions/1.0/version.json +336 -0
  311. package/{shelf → library/street/versions/1.0/graphs}/bench.json +5 -5
  312. package/{shelf → library/street/versions/1.0/graphs}/bollard.json +2 -1
  313. package/{shelf → library/street/versions/1.0/graphs}/cable.json +4 -4
  314. package/{shelf → library/street/versions/1.0/graphs}/fence.json +7 -7
  315. package/{shelf → library/street/versions/1.0/graphs}/lamp_post.json +2 -2
  316. package/library/street/versions/1.0/graphs/lineup.json +22 -0
  317. package/{shelf → library/street/versions/1.0/graphs}/road_strip.json +2 -2
  318. package/{shelf → library/street/versions/1.0/graphs}/sign_post.json +1 -1
  319. package/library/street/versions/1.0/street.topo +12 -0
  320. package/library/street/versions/1.0/version.json +421 -0
  321. package/package.json +17 -8
  322. package/dist/gallery/app/gallery.css +0 -100
  323. package/dist/gallery/app/gallery.js +0 -80
  324. package/dist/gallery/cli.d.ts +0 -4
  325. package/dist/gallery/cli.js +0 -157
  326. package/dist/gallery/library.d.ts +0 -124
  327. package/dist/gallery/library.js +0 -366
  328. package/dist/gallery/pages.d.ts +0 -94
  329. package/dist/gallery/pages.js +0 -148
  330. package/dist/gallery/server.d.ts +0 -21
  331. package/dist/gallery/server.js +0 -391
  332. package/dist/graph/migrate.d.ts +0 -23
  333. package/dist/graph/migrate.js +0 -58
  334. package/dist/mcp/library.d.ts +0 -12
  335. package/dist/mcp/library.js +0 -159
  336. package/shelf/index.json +0 -190
package/dist/io/gltf.js CHANGED
@@ -23,27 +23,32 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
23
23
  // keep their own frames, for every primitive whose material has a normal map; a supplied point/vertex "tangent"
24
24
  // float[4] attribute is written on the others ('preserve': everywhere it exists). Collapsed or missing uvs are
25
25
  // reported, never written as invalid tangents.
26
- // Custom attributes: every other numeric point/vertex attribute of size 1–4 becomes `_NAME` (upper-cased; float,
27
- // or the smallest integer type that holds an int attribute). The original names and types are kept in mesh
28
- // extras (topotopo.attributes), so imports restore them exactly. POINTS always carry pscale as `_PSCALE`.
26
+ // Custom attributes (option custom, default off): every other numeric point/vertex attribute of size 1–4 becomes
27
+ // `_NAME` (upper-cased; float, or the smallest integer type that holds an int attribute). The original names and
28
+ // types are kept in mesh extras (topotopo.attributes), so imports restore them exactly. POINTS always carry pscale
29
+ // as `_PSCALE`. Attributes only scene empties use (scene_empty, parent, orient, scale and their extras, at their
30
+ // defaults on every mesh point) are never written as mesh channels.
29
31
  // Materials: the prim "material" attribute names a material of the detail table "materials" (core/materials.ts).
30
32
  // Colour space: TopoTopo colours (Cd, material base/emissive colours) are display values; glTF defines
31
33
  // baseColorFactor, emissiveFactor and COLOR_0 as linear, so they are converted on export and back on import.
32
- // Vertex colours win: a primitive with Cd gets baseColorFactor white × COLOR_0, the material supplies the PBR
33
- // scalars; the original material is kept in material extras (topotopo.material) for lossless re-import.
34
- // A primitive whose Cd is one constant colour writes it as the baseColorFactor instead of COLOR_0 (the same
35
- // colour under glTF's factor × COLOR_0, and visible in engines whose default materials ignore vertex colours,
36
- // such as Unreal's Interchange); primitive extras (topotopo.Cd) restore it as point Cd on import.
34
+ // A named material wins over Cd: a primitive whose prim "material" names a material of the table is written with
35
+ // that material as it is, and its Cd / Alpha are not exported (option vertexColors writes them there too).
36
+ // Elsewhere, and with vertexColors, vertex colours win: a primitive with Cd gets baseColorFactor white × COLOR_0,
37
+ // the material supplies the PBR scalars; the original material is kept in material extras (topotopo.material) for
38
+ // lossless re-import. A primitive whose Cd is one constant colour writes it as the baseColorFactor instead of
39
+ // COLOR_0 (the same colour under glTF's factor × COLOR_0, and visible in engines whose default materials ignore
40
+ // vertex colours, such as Unreal's Interchange); primitive extras (topotopo.Cd) restore it as point Cd on import.
37
41
  // Options: quantize (KHR_mesh_quantization), compress 'meshopt' (EXT_meshopt_compression, implies quantize),
38
42
  // compress 'draco' (KHR_draco_mesh_compression, only when the optional draco3dgltf package is installed).
39
43
  // Packed instances (instancing 'packed', the default): one mesh + node per packed source with EXT_mesh_gpu_instancing
40
44
  // (TRANSLATION / ROTATION / SCALE per instance; a 3×3 with shear is written as its nearest rotation and the
41
45
  // scale of its columns, with a warning); the rest of the geometry as above. instancing 'expand' writes real copies.
42
- // Per-instance attributes (custom, default on): the anchor point / packed prim attributes become extra instance
46
+ // Per-instance attributes (custom, default off): the anchor point / packed prim attributes become extra instance
43
47
  // accessors with the extension's "_" prefix: Cd (+ Alpha) → _COLOR (VEC3/VEC4 float), every other numeric attribute
44
48
  // of size 1–4 → _NAME, single strings → _NAME indices into a table in the node's extras; all as 32-bit floats (exact
45
49
  // for integers below 2^24; 1- and 2-byte components break EXT_meshopt_compression's 4-byte instance strides); the
46
- // transform inputs (N, up, orient, rot, scale, trans, pivot) are folded into TRS and skipped.
50
+ // transform inputs (N, up, orient, rot, scale, trans, pivot) are folded into TRS and skipped. Option instanceColors
51
+ // writes _COLOR alone, without custom (Godot's MultiMesh reads instance colours and nothing else).
47
52
  // Node extras (topotopo.instanceAttributes) keep names, classes, types and string tables for re-import.
48
53
  // Node and mesh names are packedSourceNames() (the source's prim "name", else source_<i>), as in the instance stream.
49
54
  // Textures: the material table's texture paths (base colour, normal, roughness) are read with options.readFile and
@@ -51,6 +56,7 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
51
56
  // a map replaces its factor (baseColorFactor white, roughnessFactor 1). Without readFile the maps are skipped.
52
57
  // "image:<name>" paths are image volumes of the geometry (texture nodes), encoded to PNG in memory; an "orm" map is
53
58
  // both the metallicRoughness and the occlusion texture (metallicFactor 1).
59
+ // options.source (how the export was made, io/source.ts) → asset.extras.source.
54
60
  //
55
61
  // Import
56
62
  // node hierarchy flattened with world transforms (nodes without a mesh → scene empties: points with scene_empty 1,
@@ -70,6 +76,7 @@ import { Attribute, AttribTable, Geometry, defaultValueFor } from '../core/geome
70
76
  import { resolveVertexNormals, triangulate } from '../core/topology.js';
71
77
  import { TANGENT_ATTRIB, cornerTangents, loadMikkTSpace, tangentProblem, transformTangents, vertexUV } from '../core/tangents.js';
72
78
  import { gltfV } from '../core/texcoord.js';
79
+ import { posText, primWhere } from '../core/report.js';
73
80
  import { DEFAULT_MATERIAL, materialAlphaMode, mergeMaterialTables, normalizeMaterial, primMaterials, texturePaths, writeMaterials } from '../core/materials.js';
74
81
  import { m4apply, m4applyDir, m4fromQuat, m4invert, m4mul, m4normalMatrix, m4scale, m4translate } from '../core/math.js';
75
82
  import { EMPTY_ATTRIB, PARENT_ATTRIB, sceneEmpties } from '../core/scene.js';
@@ -258,6 +265,16 @@ function emit(channels, corners, vprim, g, weld) {
258
265
  }
259
266
  return { data, count, idx };
260
267
  }
268
+ const sameBytes = (a, b) => {
269
+ if (a === b)
270
+ return true;
271
+ if (a.length !== b.length)
272
+ return false;
273
+ for (let i = 0; i < a.length; i++)
274
+ if (a[i] !== b[i])
275
+ return false;
276
+ return true;
277
+ };
261
278
  /** Image MIME type from the first bytes (PNG or JPEG), or null. */
262
279
  export function imageMime(b) {
263
280
  if (b.length >= 8 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47)
@@ -266,7 +283,10 @@ export function imageMime(b) {
266
283
  return 'image/jpeg';
267
284
  return null;
268
285
  }
269
- /** The glTF texture for an image path (created once per path), or null when its bytes are missing or not PNG/JPEG. */
286
+ /**
287
+ * The glTF texture for an image path (created once per path, and once per distinct image: a path whose bytes equal an
288
+ * earlier one's, e.g. each LOD's copy of a map, shares its texture), or null when its bytes are missing or not PNG/JPEG.
289
+ */
270
290
  function textureFor(st, path) {
271
291
  if (!st.data)
272
292
  return null;
@@ -279,13 +299,23 @@ function textureFor(st, path) {
279
299
  if (bytes && !mime)
280
300
  st.warn?.(`glTF: texture "${path}" is not a PNG or JPEG image; material exported without it`);
281
301
  if (bytes && mime) {
282
- const base = (path.startsWith('image:') ? path.slice(6) : baseOf(path).replace(/\.[^.]*$/, '')).replace(/[^A-Za-z0-9_-]+/g, '_') || 'texture';
283
- const ext = mime === 'image/png' ? '.png' : '.jpg';
284
- let uri = base + ext, k = 1;
285
- while (st.uris.has(uri))
286
- uri = `${base}_${k++}${ext}`;
287
- st.uris.add(uri);
288
- t = st.doc.createTexture(base).setImage(bytes).setMimeType(mime).setURI(uri);
302
+ const same = st.byLength.get(bytes.length)?.find((c) => sameBytes(c.bytes, bytes));
303
+ if (same)
304
+ t = same.tex;
305
+ else {
306
+ const base = (path.startsWith('image:') ? path.slice(6) : baseOf(path).replace(/\.[^.]*$/, '')).replace(/[^A-Za-z0-9_-]+/g, '_') || 'texture';
307
+ const ext = mime === 'image/png' ? '.png' : '.jpg';
308
+ let uri = base + ext, k = 1;
309
+ while (st.uris.has(uri))
310
+ uri = `${base}_${k++}${ext}`;
311
+ st.uris.add(uri);
312
+ t = st.doc.createTexture(base).setImage(bytes).setMimeType(mime).setURI(uri);
313
+ const list = st.byLength.get(bytes.length);
314
+ if (list)
315
+ list.push({ bytes, tex: t });
316
+ else
317
+ st.byLength.set(bytes.length, [{ bytes, tex: t }]);
318
+ }
289
319
  }
290
320
  st.textures.set(path, t);
291
321
  return t;
@@ -357,6 +387,47 @@ const rgbAllOnes = (d, size) => {
357
387
  return true;
358
388
  };
359
389
  // ------------------------------------------------------------------ export: document
390
+ /**
391
+ * The empties' own point attributes are no mesh data: once the empties are split out (`g` holds only the other points,
392
+ * a copy the caller owns), their marker, parent, orient, scale and extras hold nothing but the default fill a merge
393
+ * gave the mesh points. Those are deleted so no mesh carries a channel for them; one a mesh point really sets stays.
394
+ */
395
+ function dropEmptyAttributes(g, empties) {
396
+ const names = new Set([EMPTY_ATTRIB, PARENT_ATTRIB, 'orient', 'scale']);
397
+ for (const e of empties)
398
+ for (const k of Object.keys(e.extras))
399
+ names.add(k);
400
+ for (const n of names) {
401
+ const a = g.points.get(n);
402
+ if (!a)
403
+ continue;
404
+ if (n === EMPTY_ATTRIB || onlyDefaults(a))
405
+ g.points.delete(n);
406
+ }
407
+ }
408
+ /** Every element of a fixed-size attribute holds its default (or, for numbers, all zeros: an unset fill). */
409
+ function onlyDefaults(a) {
410
+ if (a.isArray)
411
+ return false;
412
+ if (a.type === 'string') {
413
+ const d = a.def;
414
+ return a.data.every((s) => s === '' || s === d);
415
+ }
416
+ const d = a.def, sz = a.size, data = a.data;
417
+ for (let i = 0; i < data.length; i += sz) {
418
+ let def = true, zero = true;
419
+ for (let c = 0; c < sz; c++) {
420
+ const x = data[i + c];
421
+ if (x !== (d[c] ?? 0))
422
+ def = false;
423
+ if (x !== 0)
424
+ zero = false;
425
+ }
426
+ if (!def && !zero)
427
+ return false;
428
+ }
429
+ return true;
430
+ }
360
431
  /** Build a gltf-transform Document for the geometry (no IO yet). */
361
432
  export function gltfDocument(g, o = {}) {
362
433
  if (hasSplinesDeep(g))
@@ -368,22 +439,13 @@ export function gltfDocument(g, o = {}) {
368
439
  for (const e of empties)
369
440
  keep[e.point] = 0;
370
441
  g = g.subsetPoints(keep);
371
- // the empties' own attributes are no mesh data: merged meshes only hold their default fill
372
- g.points.delete(EMPTY_ATTRIB);
373
- for (const n of ['orient', 'scale']) {
374
- const a = g.points.get(n);
375
- if (!a || a.type !== 'float' || typeof a.def === 'string')
376
- continue;
377
- const d = a.def, sz = a.size, data = a.data;
378
- let fill = true;
379
- for (let i = 0; i < data.length && fill; i++)
380
- fill = data[i] === d[i % sz] || data[i] === 0;
381
- if (fill)
382
- g.points.delete(n);
383
- }
442
+ dropEmptyAttributes(g, empties);
384
443
  }
385
444
  const doc = new Document();
386
445
  doc.getRoot().getAsset().generator = 'topotopo';
446
+ // how the export was made (io/source.ts): the graph, its vars and seeds, the frame, the version
447
+ if (o.source)
448
+ doc.getRoot().getAsset().extras = { source: o.source };
387
449
  const buffer = doc.createBuffer();
388
450
  const scene = doc.createScene('scene');
389
451
  doc.getRoot().setDefaultScene(scene);
@@ -391,10 +453,10 @@ export function gltfDocument(g, o = {}) {
391
453
  const useMaterials = o.materials !== false;
392
454
  const st = {
393
455
  doc, table: useMaterials ? mergeMaterialTables([g, ...g.packedSources]) : {}, cache: new Map(), defaultMat: DEFAULT_MATERIAL,
394
- data: o.textureData, textures: new Map(), uris: new Set(), warn: o.warn,
456
+ data: o.textureData, textures: new Map(), byLength: new Map(), uris: new Set(), warn: o.warn,
395
457
  };
396
458
  let noUV = 0;
397
- const custom = o.custom !== false;
459
+ const custom = o.custom === true;
398
460
  const tangentMode = o.tangents ?? 'auto';
399
461
  const lineMode = o.lineMode ?? 'strip';
400
462
  // what to write: the geometry, or (packed) its non-instanced part plus one instanced mesh per packed source
@@ -434,6 +496,8 @@ export function gltfDocument(g, o = {}) {
434
496
  }
435
497
  const hasN = !!(geo.vertices.get('N') ?? geo.points.get('N'));
436
498
  let normals = null;
499
+ // a named material decides the colour of its primitives: their Cd / Alpha are written only with vertexColors
500
+ const colorFor = (mat) => (color && (o.vertexColors === true || !(mat && st.table[mat])) ? color : null);
437
501
  const finishColor = (out, mat) => {
438
502
  // vertex colours win where they are set; all-white Cd lets the material colour through
439
503
  const ci = color ? out.channels.indexOf(color) : -1;
@@ -508,7 +572,9 @@ export function gltfDocument(g, o = {}) {
508
572
  return null; // reported once, as a textured primitive without uv
509
573
  const { tangents, diag } = cornerTangents(geo, tris, nrm, uv);
510
574
  if (diag.uvNonFinite || diag.uvDegenerate) {
511
- o.warn?.(`glTF: ${where}: ${diag.uvDegenerate} of ${diag.triangles} triangles have collapsed uvs${diag.uvNonFinite ? ` and ${diag.uvNonFinite} non-finite uvs` : ''}; their ${diag.fallbackCorners} corners get a fallback tangent (the normal map has no orientation there)`);
575
+ // where the first one is: its prim's part and position (core/report.ts)
576
+ const first = diag.firstBad >= 0 ? `, first ${primWhere(geo, geo.vertexPrims()[tris[diag.firstBad * 3]])}` : '';
577
+ o.warn?.(`glTF: ${where}: ${diag.uvDegenerate} of ${diag.triangles} triangles have collapsed uvs${diag.uvNonFinite ? ` and ${diag.uvNonFinite} non-finite uvs` : ''}${first}; their ${diag.fallbackCorners} corners get a fallback tangent (the normal map has no orientation there): unwrap them (uv_unwrap) or give them uv area`);
512
578
  }
513
579
  else if (diag.fallbackCorners)
514
580
  o.warn?.(`glTF: ${where}: MikkTSpace left ${diag.fallbackCorners} corners without a tangent; a fallback was written`);
@@ -539,8 +605,9 @@ export function gltfDocument(g, o = {}) {
539
605
  chans.push(uv0);
540
606
  if (uv1)
541
607
  chans.push(uv1);
542
- if (color)
543
- chans.push(color);
608
+ const col = colorFor(gr.mat);
609
+ if (col)
610
+ chans.push(col);
544
611
  chans.push(...customs);
545
612
  const e = emit(chans, tris, vprim, geo, true);
546
613
  const out = { mode: Primitive.Mode.TRIANGLES, channels: chans, data: e.data, count: e.count, indices: e.idx, material: null };
@@ -563,8 +630,9 @@ export function gltfDocument(g, o = {}) {
563
630
  const uv0 = uvCh('uv', 'TEXCOORD_0');
564
631
  if (uv0)
565
632
  chans.push(uv0);
566
- if (color)
567
- chans.push(color);
633
+ const col = colorFor(gr.mat);
634
+ if (col)
635
+ chans.push(col);
568
636
  chans.push(...customs);
569
637
  const strips = lineMode === 'strip' && curves.length <= MAX_LINE_STRIPS;
570
638
  const batches = strips ? curves.map((c) => [c]) : [curves];
@@ -647,7 +715,7 @@ function writeEmpties(doc, scene, empties, o) {
647
715
  const byName = new Map();
648
716
  for (const e of empties) {
649
717
  if (!e.name)
650
- throw new Error(`glTF: scene empty at point ${e.point} has no name`);
718
+ throw new Error(`glTF: the scene empty at ${posText(e.P)} (point ${e.point}) has no name: give scene_null a name`);
651
719
  const l = byName.get(e.name);
652
720
  if (l)
653
721
  l.push(e);
@@ -733,26 +801,41 @@ function writeEmpties(doc, scene, empties, o) {
733
801
  */
734
802
  function instanceJobs(doc, buffer, g, o, quantize) {
735
803
  const kind = g.primKind, S = g.packedSource, X = g.packedXform, P = g.P;
804
+ // a packed prim's "material" (pack carries it onto the instance) applies where its source has none of its own, as
805
+ // unpacking does: one instanced mesh per source and material
806
+ const flat = new Map();
807
+ const flatOf = (s) => { let f = flat.get(s); if (!f) {
808
+ f = flattenSource(g.packedSources[s]);
809
+ flat.set(s, f);
810
+ } return f; };
811
+ const ownMat = (s) => { const a = flatOf(s).prims.get('material'); return !!a && a.type === 'string' && a.data.some((x) => !!x); };
812
+ const pm = g.prims.get('material'), pmat = pm && pm.type === 'string' ? pm.data : null;
736
813
  const bySrc = new Map();
737
814
  for (let p = 0; p < kind.length; p++) {
738
815
  if (kind[p] !== 1 || g.primStart[p + 1] - g.primStart[p] !== 1)
739
816
  continue;
740
- let l = bySrc.get(S[p]);
817
+ const s = S[p], mat = pmat?.[p] && o.materials !== false && !ownMat(s) ? pmat[p] : '';
818
+ const key = `${s}\u0000${mat}`;
819
+ let l = bySrc.get(key);
741
820
  if (!l) {
742
- l = [];
743
- bySrc.set(S[p], l);
821
+ l = { s, mat, prims: [] };
822
+ bySrc.set(key, l);
744
823
  }
745
- l.push(p);
824
+ l.prims.push(p);
746
825
  }
826
+ const perSource = new Map();
827
+ for (const { s } of bySrc.values())
828
+ perSource.set(s, (perSource.get(s) ?? 0) + 1);
747
829
  const ext = doc.createExtension(EXTMeshGPUInstancing).setRequired(true);
748
830
  const names = packedSourceNames(g);
749
- const iattrs = o.custom === false ? [] : instanceAttribSpecs(g);
831
+ // custom: every per-instance attribute; instanceColors: Cd (+ Alpha) alone, as _COLOR
832
+ const iattrs = o.custom === true ? instanceAttribSpecs(g) : o.instanceColors === true ? instanceAttribSpecs(g).filter((ia) => ia.sem === '_COLOR') : [];
750
833
  const info = {};
751
834
  for (const ia of iattrs)
752
835
  info[ia.sem] = { name: ia.a.name, cls: ia.a.cls, type: ia.type, size: ia.size, ...(ia.strings ? { strings: ia.strings } : {}) };
753
836
  let sheared = 0;
754
837
  const jobs = [];
755
- for (const [s, prims] of bySrc) {
838
+ for (const { s, mat, prims } of bySrc.values()) {
756
839
  const n = prims.length;
757
840
  const T = new Float64Array(n * 3), L = new Float64Array(n * 9), Q = new Float32Array(n * 4), SC = new Float64Array(n * 3);
758
841
  prims.forEach((p, i) => {
@@ -765,8 +848,12 @@ function instanceJobs(doc, buffer, g, o, quantize) {
765
848
  Q.set(d.q, i * 4);
766
849
  SC.set(d.s, i * 3);
767
850
  });
768
- const src = flattenSource(g.packedSources[s]);
769
- const label = names[s] ?? `source_${s}`;
851
+ let src = flatOf(s);
852
+ if (mat) {
853
+ src = src.clone();
854
+ src.prims.set('material', new Attribute('string', 1, new Array(src.numPrims).fill(mat), ''));
855
+ }
856
+ const label = (names[s] ?? `source_${s}`) + (mat && (perSource.get(s) ?? 0) > 1 ? `_${mat}` : '');
770
857
  jobs.push({
771
858
  src, split: false,
772
859
  onMesh: ({ node, center, extent }) => {
@@ -1,5 +1,6 @@
1
1
  import type { Geometry } from '../core/geometry.ts';
2
2
  import type { Heightfield } from '../core/heightfield.ts';
3
+ import type { ExportSource } from './source.ts';
3
4
  export type HeightmapFormat = 'png16' | 'r16' | 'mask_png';
4
5
  export declare const HEIGHTMAP_FORMATS: HeightmapFormat[];
5
6
  export interface HeightmapOptions {
@@ -14,6 +15,8 @@ export interface HeightmapOptions {
14
15
  heightfield?: number;
15
16
  /** zlib compressor for PNG data (default: stored, uncompressed blocks) */
16
17
  deflate?: (data: Uint8Array) => Uint8Array;
18
+ /** png16 / r16: how the export was made (io/source.ts), written into the sidecar as "source" */
19
+ source?: ExportSource;
17
20
  }
18
21
  export interface HeightmapFile {
19
22
  kind: 'main' | 'sidecar' | 'layer';
@@ -184,6 +184,7 @@ export function heightmapExport(g, format, o = {}) {
184
184
  : 'RAW little-endian uint16, row-major, no header; h = height_min + value / 65535 * (height_max - height_min)',
185
185
  clipped: min > st.min || max < st.max,
186
186
  unreal,
187
+ ...(o.source ? { source: o.source } : {}),
187
188
  };
188
189
  const sidecar = new TextEncoder().encode(JSON.stringify(info, null, 2) + '\n');
189
190
  return {
package/dist/io/import.js CHANGED
@@ -9,6 +9,7 @@ import { importGLTFAsync } from './gltf.js';
9
9
  import { importHoudiniBgeo, importHoudiniGeo, isBinaryJSON } from './hgeo.js';
10
10
  import { importCSV, importPointsJSON, isPointsJSON } from './points.js';
11
11
  import { imageFromPNGFile } from './textures.js';
12
+ import { SIDECAR_FORMATS, SIDECAR_NAMES, SIDECAR_TEXT } from './sidecars.js';
12
13
  export { importGLTFAsync } from './gltf.js';
13
14
  export { importHoudiniBgeo, importHoudiniGeo } from './hgeo.js';
14
15
  export { importCSV, importPointsJSON } from './points.js';
@@ -29,6 +30,15 @@ function importAnyJSON(j, warn) {
29
30
  return importHoudiniGeo(j, warn);
30
31
  if (isPointsJSON(j))
31
32
  return importPointsJSON(j);
33
+ // an export's sidecar (io/sidecars.ts) is metadata of the file beside it: say so instead of "not a topotopo-geo file"
34
+ const role = typeof j?.format === 'string' ? SIDECAR_FORMATS[j.format] : undefined;
35
+ if (role)
36
+ throw new Error(`this JSON is an export's ${SIDECAR_NAMES[role]} (${SIDECAR_TEXT[role]}), not geometry: ${{
37
+ source: 'read the exported file it sits beside',
38
+ heightmap: j.format === 'png16' ? 'read the heightmap PNG beside it with heightfield_from_image (height_min / height_max from this sidecar)' : 'the RAW heightmap beside it is for Unreal; export png16 to read it back',
39
+ meshes: 'read the instance stream (.csv / .points.json) beside it',
40
+ landscape: 'read the files of its folder (heightmap.png, objects.glb)',
41
+ }[role]}`);
32
42
  return geoFromJSON(j);
33
43
  }
34
44
  /** Synchronous import for every format except glb/gltf (see importGeometryAsync). */
@@ -0,0 +1,55 @@
1
+ /** A node of the exported scene. */
2
+ export interface SceneNode {
3
+ name: string;
4
+ /** the parent node's name, or null at the scene root */
5
+ parent: string | null;
6
+ /** "mesh" (with its mesh), "instances" (EXT_mesh_gpu_instancing), "empty" (a socket / scene empty) */
7
+ kind: 'mesh' | 'instances' | 'empty';
8
+ mesh: string | null;
9
+ /** local translation, and the world position of the node's origin (metres, Y up) */
10
+ translation: [number, number, number];
11
+ world: [number, number, number];
12
+ instances: number;
13
+ extras: string[];
14
+ }
15
+ export interface SceneMesh {
16
+ name: string;
17
+ primitives: {
18
+ material: string | null;
19
+ mode: string;
20
+ triangles: number;
21
+ vertices: number;
22
+ attributes: string[];
23
+ }[];
24
+ triangles: number;
25
+ }
26
+ export interface SceneMaterial {
27
+ name: string;
28
+ baseColor: number[];
29
+ metallic: number;
30
+ roughness: number;
31
+ maps: Record<string, string>;
32
+ alphaMode: string;
33
+ doubleSided: boolean;
34
+ unlit: boolean;
35
+ }
36
+ export interface SceneImage {
37
+ name: string;
38
+ mimeType: string;
39
+ bytes: number;
40
+ width: number;
41
+ height: number;
42
+ }
43
+ export interface SceneReport {
44
+ nodes: SceneNode[];
45
+ meshes: SceneMesh[];
46
+ materials: SceneMaterial[];
47
+ images: SceneImage[];
48
+ extensions: string[];
49
+ bytes: number;
50
+ triangles: number;
51
+ }
52
+ /** The scene a GLB holds (see the file comment). */
53
+ export declare function glbSceneReport(bytes: Uint8Array): SceneReport;
54
+ /** The scene report as text. */
55
+ export declare function sceneReportText(r: SceneReport): string[];
@@ -0,0 +1,155 @@
1
+ // inspect detail "scene": what a glb export of the geometry holds, read back from the exported bytes themselves (the
2
+ // GLB's JSON chunk), so it is the export and not a guess at it: the node tree (meshes, scene empties and their
3
+ // parents, local and world positions, extras), each mesh's primitives (triangles, vertex attributes, material), the
4
+ // materials with their factors and maps, and the images (size, format, bytes). Pure: no file system.
5
+ const MODES = ['POINTS', 'LINES', 'LINE_LOOP', 'LINE_STRIP', 'TRIANGLES', 'TRIANGLE_STRIP', 'TRIANGLE_FAN'];
6
+ /** The JSON chunk and binary chunk of a GLB. */
7
+ function glbChunks(bytes) {
8
+ const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
9
+ if (bytes.length < 20 || dv.getUint32(0, true) !== 0x46546c67)
10
+ throw new Error('not a GLB file');
11
+ let o = 12, json = null, bin = null;
12
+ while (o + 8 <= bytes.length) {
13
+ const len = dv.getUint32(o, true), type = dv.getUint32(o + 4, true);
14
+ const data = bytes.subarray(o + 8, o + 8 + len);
15
+ if (type === 0x4e4f534a)
16
+ json = JSON.parse(new TextDecoder().decode(data));
17
+ else if (type === 0x004e4942)
18
+ bin = data;
19
+ o += 8 + len;
20
+ }
21
+ if (!json)
22
+ throw new Error('GLB without a JSON chunk');
23
+ return { json, bin };
24
+ }
25
+ /** Width and height of a PNG or JPEG from its header (0 × 0 when unknown). */
26
+ function imageSize(b) {
27
+ if (!b || b.length < 24)
28
+ return [0, 0];
29
+ const dv = new DataView(b.buffer, b.byteOffset, b.byteLength);
30
+ if (b[0] === 0x89 && b[1] === 0x50)
31
+ return [dv.getUint32(16), dv.getUint32(20)];
32
+ if (b[0] === 0xff && b[1] === 0xd8) {
33
+ let o = 2;
34
+ while (o + 9 < b.length) {
35
+ if (b[o] !== 0xff)
36
+ break;
37
+ const m = b[o + 1], len = dv.getUint16(o + 2);
38
+ if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc)
39
+ return [dv.getUint16(o + 7), dv.getUint16(o + 5)];
40
+ o += 2 + len;
41
+ }
42
+ }
43
+ return [0, 0];
44
+ }
45
+ /** Quaternion (x, y, z, w) applied to v. */
46
+ function qrot(q, v) {
47
+ const [x, y, z, w] = q, ix = w * v[0] + y * v[2] - z * v[1], iy = w * v[1] + z * v[0] - x * v[2], iz = w * v[2] + x * v[1] - y * v[0], iw = -x * v[0] - y * v[1] - z * v[2];
48
+ return [ix * w + iw * -x + iy * -z - iz * -y, iy * w + iw * -y + iz * -x - ix * -z, iz * w + iw * -z + ix * -y - iy * -x];
49
+ }
50
+ /** The scene a GLB holds (see the file comment). */
51
+ export function glbSceneReport(bytes) {
52
+ const { json, bin } = glbChunks(bytes);
53
+ const acc = (i) => (i === undefined ? null : json.accessors?.[i] ?? null);
54
+ const images = (json.images ?? []).map((im, i) => {
55
+ const bv = im.bufferView !== undefined ? json.bufferViews?.[im.bufferView] : null;
56
+ const data = bv && bin ? bin.subarray(bv.byteOffset ?? 0, (bv.byteOffset ?? 0) + bv.byteLength) : null;
57
+ const [w, h] = imageSize(data);
58
+ return { name: im.name ?? `image_${i}`, mimeType: im.mimeType ?? (im.uri ? 'uri' : '?'), bytes: bv?.byteLength ?? 0, width: w, height: h };
59
+ });
60
+ const texName = (t) => {
61
+ if (!t || t.index === undefined)
62
+ return null;
63
+ const tex = json.textures?.[t.index];
64
+ const src = tex?.source ?? tex?.extensions?.EXT_texture_webp?.source;
65
+ const im = src !== undefined ? images[src] : undefined;
66
+ return im ? `${im.name}${im.width ? ` ${im.width}×${im.height}` : ''}` : `texture ${t.index}`;
67
+ };
68
+ const materials = (json.materials ?? []).map((m, i) => {
69
+ const pbr = m.pbrMetallicRoughness ?? {}, maps = {};
70
+ const put = (k, t) => { const nm = texName(t); if (nm)
71
+ maps[k] = nm; };
72
+ put('baseColor', pbr.baseColorTexture);
73
+ put('metallicRoughness', pbr.metallicRoughnessTexture);
74
+ put('normal', m.normalTexture);
75
+ put('occlusion', m.occlusionTexture);
76
+ put('emissive', m.emissiveTexture);
77
+ return {
78
+ name: m.name ?? `material_${i}`, baseColor: pbr.baseColorFactor ?? [1, 1, 1, 1], metallic: pbr.metallicFactor ?? 1, roughness: pbr.roughnessFactor ?? 1,
79
+ maps, alphaMode: m.alphaMode ?? 'OPAQUE', doubleSided: !!m.doubleSided, unlit: !!m.extensions?.KHR_materials_unlit,
80
+ };
81
+ });
82
+ const meshes = (json.meshes ?? []).map((m, i) => {
83
+ const prims = (m.primitives ?? []).map((p) => {
84
+ const mode = MODES[p.mode ?? 4] ?? String(p.mode);
85
+ const pos = acc(p.attributes?.POSITION), idx = acc(p.indices);
86
+ const count = idx ? idx.count : pos ? pos.count : 0;
87
+ const triangles = mode === 'TRIANGLES' ? Math.floor(count / 3) : mode === 'TRIANGLE_STRIP' || mode === 'TRIANGLE_FAN' ? Math.max(0, count - 2) : 0;
88
+ return { material: p.material !== undefined ? materials[p.material]?.name ?? `material ${p.material}` : null, mode, triangles, vertices: pos?.count ?? 0, attributes: Object.keys(p.attributes ?? {}) };
89
+ });
90
+ return { name: m.name ?? `mesh_${i}`, primitives: prims, triangles: prims.reduce((s, p) => s + p.triangles, 0) };
91
+ });
92
+ // the node tree, depth first from the scene roots
93
+ const nodes = [];
94
+ let triangles = 0;
95
+ const scene = json.scenes?.[json.scene ?? 0];
96
+ const walk = (i, parent, world, depth) => {
97
+ const nd = json.nodes?.[i];
98
+ if (!nd || depth > 64)
99
+ return;
100
+ const t = nd.translation ?? [0, 0, 0], r = nd.rotation ?? [0, 0, 0, 1], sc = nd.scale ?? [1, 1, 1];
101
+ // the world origin: parent's transform applied to the local translation (matrices: none are written by the exporter)
102
+ const rt = qrot(world.r, [t[0] * world.s[0], t[1] * world.s[1], t[2] * world.s[2]]);
103
+ const wt = [world.t[0] + rt[0], world.t[1] + rt[1], world.t[2] + rt[2]];
104
+ const qr = world.r, wr = [
105
+ qr[3] * r[0] + qr[0] * r[3] + qr[1] * r[2] - qr[2] * r[1], qr[3] * r[1] - qr[0] * r[2] + qr[1] * r[3] + qr[2] * r[0],
106
+ qr[3] * r[2] + qr[0] * r[1] - qr[1] * r[0] + qr[2] * r[3], qr[3] * r[3] - qr[0] * r[0] - qr[1] * r[1] - qr[2] * r[2]
107
+ ];
108
+ const inst = nd.extensions?.EXT_mesh_gpu_instancing;
109
+ const ic = inst ? acc(inst.attributes?.TRANSLATION ?? inst.attributes?.ROTATION ?? inst.attributes?.SCALE)?.count ?? 0 : 0;
110
+ const mesh = nd.mesh !== undefined ? meshes[nd.mesh] : null;
111
+ if (mesh)
112
+ triangles += mesh.triangles * (inst ? ic : 1);
113
+ const name = nd.name ?? `node_${i}`;
114
+ nodes.push({
115
+ name, parent, kind: mesh ? (inst ? 'instances' : 'mesh') : 'empty', mesh: mesh?.name ?? null,
116
+ translation: [t[0], t[1], t[2]], world: [wt[0], wt[1], wt[2]], instances: ic,
117
+ extras: nd.extras && typeof nd.extras === 'object' ? Object.keys(nd.extras).filter((k) => k !== 'topotopo') : [],
118
+ });
119
+ for (const c of nd.children ?? [])
120
+ walk(c, name, { t: wt, r: wr, s: [world.s[0] * sc[0], world.s[1] * sc[1], world.s[2] * sc[2]] }, depth + 1);
121
+ };
122
+ for (const i of scene?.nodes ?? [])
123
+ walk(i, null, { t: [0, 0, 0], r: [0, 0, 0, 1], s: [1, 1, 1] }, 0);
124
+ return { nodes, meshes, materials, images, extensions: json.extensionsUsed ?? [], bytes: bytes.length, triangles };
125
+ }
126
+ /** The scene report as text. */
127
+ export function sceneReportText(r) {
128
+ const n = (x) => x.toLocaleString('en-US');
129
+ const f = (x) => (Math.abs(x) < 5e-4 ? 0 : x).toFixed(3);
130
+ const p3 = (v) => `(${v.map(f).join(', ')})`;
131
+ const kb = (b) => (b >= 1 << 20 ? `${(b / (1 << 20)).toFixed(2)} MB` : `${(b / 1024).toFixed(1)} KB`);
132
+ const out = [`scene (the glb export, read back): ${r.nodes.length} nodes, ${r.meshes.length} meshes, ${n(r.triangles)} triangles, ${r.materials.length} materials, ${r.images.length} images; ${kb(r.bytes)}${r.extensions.length ? `; extensions ${r.extensions.join(', ')}` : ''}`];
133
+ out.push('nodes (parent → child; positions in metres, Y up):');
134
+ const depth = new Map();
135
+ for (const nd of r.nodes) {
136
+ const d = nd.parent === null ? 0 : (depth.get(nd.parent) ?? 0) + 1;
137
+ depth.set(nd.name, d);
138
+ const mesh = nd.mesh ? r.meshes.find((m) => m.name === nd.mesh) : null;
139
+ const what = nd.kind === 'empty' ? 'empty (socket)' : `${nd.kind === 'instances' ? `${n(nd.instances)} instances of ` : ''}mesh "${nd.mesh}": ${n(mesh?.triangles ?? 0)} tris, ${mesh?.primitives.length ?? 0} primitive(s)${mesh && mesh.primitives.some((p) => p.material) ? ` [${[...new Set(mesh.primitives.map((p) => p.material ?? 'no material'))].join(', ')}]` : ''}`;
140
+ out.push(` ${' '.repeat(d)}${nd.name}: ${what}; at ${p3(nd.world)}${nd.parent !== null ? `, local ${p3(nd.translation)}` : ''}${nd.extras.length ? `; extras ${nd.extras.join(', ')}` : ''}`);
141
+ }
142
+ const attrs = [...new Set(r.meshes.flatMap((m) => m.primitives.flatMap((p) => p.attributes)))].sort();
143
+ if (attrs.length)
144
+ out.push(`vertex attributes: ${attrs.join(', ')}`);
145
+ if (r.materials.length) {
146
+ out.push('materials:');
147
+ for (const m of r.materials) {
148
+ const maps = Object.entries(m.maps).map(([k, v]) => `${k} ${v}`);
149
+ out.push(` ${m.name}: base colour factor (linear) (${m.baseColor.slice(0, 3).map((x) => x.toFixed(2)).join(', ')}${m.baseColor[3] !== undefined && m.baseColor[3] !== 1 ? `, alpha ${m.baseColor[3].toFixed(2)}` : ''}), metallic ${m.metallic.toFixed(2)}, roughness ${m.roughness.toFixed(2)}${m.alphaMode !== 'OPAQUE' ? `, ${m.alphaMode}` : ''}${m.doubleSided ? ', double-sided' : ''}${m.unlit ? ', unlit' : ''}${maps.length ? `; maps: ${maps.join(', ')}` : '; no maps'}`);
150
+ }
151
+ }
152
+ if (r.images.length)
153
+ out.push(`images: ${r.images.map((im) => `${im.name} ${im.width ? `${im.width}×${im.height} ` : ''}${im.mimeType.replace('image/', '')} ${kb(im.bytes)}`).join(', ')}`);
154
+ return out;
155
+ }