topotopo 0.3.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 (354) hide show
  1. package/NOTICE +40 -10
  2. package/README.md +475 -111
  3. package/dist/cli.js +328 -133
  4. package/dist/config.d.ts +48 -0
  5. package/dist/config.js +170 -0
  6. package/dist/core/analysis.d.ts +5 -1
  7. package/dist/core/analysis.js +8 -3
  8. package/dist/core/bake.d.ts +16 -8
  9. package/dist/core/bake.js +165 -29
  10. package/dist/core/bevel.d.ts +3 -1
  11. package/dist/core/bevel.js +238 -97
  12. package/dist/core/decimate.d.ts +65 -0
  13. package/dist/core/decimate.js +409 -3
  14. package/dist/core/erosion.d.ts +37 -0
  15. package/dist/core/erosion.js +41 -1
  16. package/dist/core/geometry.d.ts +5 -1
  17. package/dist/core/geometry.js +204 -4
  18. package/dist/core/heightfield.d.ts +27 -4
  19. package/dist/core/heightfield.js +54 -16
  20. package/dist/core/imageops.d.ts +6 -0
  21. package/dist/core/imageops.js +51 -0
  22. package/dist/core/intrinsics.d.ts +7 -0
  23. package/dist/core/intrinsics.js +94 -0
  24. package/dist/core/manifold.d.ts +12 -1
  25. package/dist/core/manifold.js +78 -6
  26. package/dist/core/materials.d.ts +11 -0
  27. package/dist/core/materials.js +56 -0
  28. package/dist/core/noise.d.ts +9 -0
  29. package/dist/core/noise.js +10 -1
  30. package/dist/core/packed.js +11 -0
  31. package/dist/core/particles.d.ts +1 -1
  32. package/dist/core/particles.js +1 -1
  33. package/dist/core/polymerge.d.ts +21 -0
  34. package/dist/core/polymerge.js +327 -0
  35. package/dist/core/rbd.js +13 -1
  36. package/dist/core/repair.d.ts +2 -0
  37. package/dist/core/repair.js +2 -0
  38. package/dist/core/report.d.ts +70 -0
  39. package/dist/core/report.js +275 -0
  40. package/dist/core/scatter.d.ts +1 -1
  41. package/dist/core/scatter.js +1 -1
  42. package/dist/core/scene.d.ts +20 -0
  43. package/dist/core/scene.js +72 -0
  44. package/dist/core/sha256.d.ts +4 -0
  45. package/dist/core/sha256.js +69 -0
  46. package/dist/core/shapes.d.ts +3 -0
  47. package/dist/core/shapes.js +34 -0
  48. package/dist/core/snippet-lib.d.ts +15 -2
  49. package/dist/core/snippet-lib.js +40 -14
  50. package/dist/core/solidify.d.ts +38 -0
  51. package/dist/core/solidify.js +356 -0
  52. package/dist/core/tangents.d.ts +54 -0
  53. package/dist/core/tangents.js +218 -0
  54. package/dist/core/texcoord.d.ts +4 -0
  55. package/dist/core/texcoord.js +14 -0
  56. package/dist/core/texnoise.d.ts +6 -1
  57. package/dist/core/texnoise.js +6 -2
  58. package/dist/core/texsdf.d.ts +131 -0
  59. package/dist/core/texsdf.js +637 -0
  60. package/dist/core/texture.d.ts +163 -9
  61. package/dist/core/texture.js +844 -20
  62. package/dist/core/topology.d.ts +32 -0
  63. package/dist/core/topology.js +238 -7
  64. package/dist/core/traceimage.d.ts +7 -0
  65. package/dist/core/traceimage.js +221 -0
  66. package/dist/core/tritri.d.ts +5 -0
  67. package/dist/core/tritri.js +120 -0
  68. package/dist/core/unwrap.d.ts +72 -0
  69. package/dist/core/unwrap.js +800 -0
  70. package/dist/core/usercode.d.ts +27 -0
  71. package/dist/core/usercode.js +87 -0
  72. package/dist/core/uv.d.ts +15 -16
  73. package/dist/core/uv.js +36 -189
  74. package/dist/core/uvislands.d.ts +62 -0
  75. package/dist/core/uvislands.js +574 -0
  76. package/dist/core/uvoverlap.d.ts +58 -0
  77. package/dist/core/uvoverlap.js +220 -0
  78. package/dist/core/uvpack.d.ts +64 -0
  79. package/dist/core/uvpack.js +628 -0
  80. package/dist/core/uvreport.d.ts +127 -0
  81. package/dist/core/uvreport.js +372 -0
  82. package/dist/core/wrangle.d.ts +6 -1
  83. package/dist/core/wrangle.js +27 -16
  84. package/dist/core/xatlas.d.ts +16 -1
  85. package/dist/core/xatlas.js +95 -61
  86. package/dist/engines.d.ts +63 -0
  87. package/dist/engines.js +180 -0
  88. package/dist/explain.d.ts +4 -3
  89. package/dist/explain.js +129 -12
  90. package/dist/graph/engine.d.ts +92 -29
  91. package/dist/graph/engine.js +298 -148
  92. package/dist/graph/expr.d.ts +6 -3
  93. package/dist/graph/expr.js +18 -8
  94. package/dist/graph/outputs.d.ts +23 -0
  95. package/dist/graph/outputs.js +41 -0
  96. package/dist/graph/packages.d.ts +72 -0
  97. package/dist/graph/packages.js +261 -0
  98. package/dist/graph/parallel.d.ts +3 -1
  99. package/dist/graph/parallel.js +4 -1
  100. package/dist/graph/params.d.ts +6 -0
  101. package/dist/graph/params.js +34 -7
  102. package/dist/graph/scope.d.ts +55 -0
  103. package/dist/graph/scope.js +14 -0
  104. package/dist/graph/types.d.ts +75 -12
  105. package/dist/graph/types.js +4 -2
  106. package/dist/graph/vars.d.ts +16 -0
  107. package/dist/graph/vars.js +80 -0
  108. package/dist/host/artifacts.d.ts +10 -1
  109. package/dist/host/artifacts.js +37 -6
  110. package/dist/host/cook.d.ts +241 -0
  111. package/dist/host/cook.js +844 -0
  112. package/dist/host/export-targets.d.ts +42 -5
  113. package/dist/host/export-targets.js +72 -13
  114. package/dist/host/godot-commands.d.ts +4 -0
  115. package/dist/host/godot-commands.js +21 -0
  116. package/dist/host/godot.d.ts +183 -0
  117. package/dist/host/godot.js +916 -0
  118. package/dist/host/node.d.ts +12 -7
  119. package/dist/host/node.js +27 -9
  120. package/dist/host/pool.js +51 -2
  121. package/dist/host/sidecars.d.ts +8 -0
  122. package/dist/host/sidecars.js +50 -0
  123. package/dist/host/types.d.ts +19 -6
  124. package/dist/host/version.d.ts +1 -0
  125. package/dist/host/version.js +3 -0
  126. package/dist/host/worker.js +5 -2
  127. package/dist/index.d.ts +5 -3
  128. package/dist/index.js +3 -2
  129. package/dist/inspect.d.ts +84 -1
  130. package/dist/inspect.js +271 -24
  131. package/dist/io/common.d.ts +33 -5
  132. package/dist/io/export.js +2 -1
  133. package/dist/io/files.d.ts +23 -4
  134. package/dist/io/files.js +60 -8
  135. package/dist/io/gltf.js +355 -51
  136. package/dist/io/heightmap.d.ts +3 -0
  137. package/dist/io/heightmap.js +1 -0
  138. package/dist/io/import.js +10 -0
  139. package/dist/io/inspect-scene.d.ts +55 -0
  140. package/dist/io/inspect-scene.js +155 -0
  141. package/dist/io/kinds.d.ts +81 -0
  142. package/dist/io/kinds.js +163 -0
  143. package/dist/io/points.d.ts +2 -1
  144. package/dist/io/points.js +3 -1
  145. package/dist/io/sidecars.d.ts +24 -0
  146. package/dist/io/sidecars.js +57 -0
  147. package/dist/io/source.d.ts +65 -0
  148. package/dist/io/source.js +112 -0
  149. package/dist/io/targets.d.ts +47 -3
  150. package/dist/io/targets.js +149 -14
  151. package/dist/io/textures.js +21 -1
  152. package/dist/io/unreal.js +5 -1
  153. package/dist/mcp/docs.d.ts +10 -1
  154. package/dist/mcp/docs.js +816 -119
  155. package/dist/mcp/inputs.d.ts +12 -5
  156. package/dist/mcp/inputs.js +50 -13
  157. package/dist/mcp/server.js +70 -24
  158. package/dist/mcp/tools.d.ts +14 -7
  159. package/dist/mcp/tools.js +207 -108
  160. package/dist/mcp/verify.d.ts +2 -2
  161. package/dist/mcp/verify.js +1 -1
  162. package/dist/mcp/workspace.d.ts +15 -0
  163. package/dist/mcp/workspace.js +349 -0
  164. package/dist/nodes/attributes.js +198 -1
  165. package/dist/nodes/bake.js +207 -83
  166. package/dist/nodes/beam.d.ts +1 -0
  167. package/dist/nodes/beam.js +201 -0
  168. package/dist/nodes/bevel.js +54 -5
  169. package/dist/nodes/cloth.js +2 -0
  170. package/dist/nodes/code.js +22 -10
  171. package/dist/nodes/curves.js +440 -93
  172. package/dist/nodes/flow.js +53 -33
  173. package/dist/nodes/generate.js +13 -39
  174. package/dist/nodes/heightfield.js +248 -77
  175. package/dist/nodes/imageops.d.ts +1 -0
  176. package/dist/nodes/imageops.js +203 -0
  177. package/dist/nodes/index.d.ts +4 -0
  178. package/dist/nodes/index.js +4 -0
  179. package/dist/nodes/material.js +91 -23
  180. package/dist/nodes/measure.js +45 -18
  181. package/dist/nodes/particles.js +2 -0
  182. package/dist/nodes/pcg.js +6 -5
  183. package/dist/nodes/procedural.js +4 -3
  184. package/dist/nodes/rbd.js +1 -1
  185. package/dist/nodes/remesh.js +71 -15
  186. package/dist/nodes/scene.d.ts +1 -0
  187. package/dist/nodes/scene.js +55 -0
  188. package/dist/nodes/sdf.js +10 -5
  189. package/dist/nodes/solid.js +20 -5
  190. package/dist/nodes/solidify.d.ts +1 -0
  191. package/dist/nodes/solidify.js +52 -0
  192. package/dist/nodes/splines.d.ts +15 -1
  193. package/dist/nodes/splines.js +112 -105
  194. package/dist/nodes/texture.d.ts +21 -6
  195. package/dist/nodes/texture.js +1318 -185
  196. package/dist/nodes/topology.d.ts +7 -0
  197. package/dist/nodes/topology.js +133 -6
  198. package/dist/nodes/transform.js +11 -3
  199. package/dist/nodes/util.d.ts +1 -1
  200. package/dist/nodes/uv.js +192 -174
  201. package/dist/nodes/wasmcall.js +6 -2
  202. package/dist/open.d.ts +19 -0
  203. package/dist/open.js +12 -0
  204. package/dist/package.d.ts +288 -0
  205. package/dist/package.js +772 -0
  206. package/dist/packages/check.d.ts +32 -0
  207. package/dist/packages/check.js +169 -0
  208. package/dist/packages/commands.d.ts +57 -0
  209. package/dist/packages/commands.js +537 -0
  210. package/dist/packages/registry.d.ts +796 -0
  211. package/dist/packages/registry.js +2998 -0
  212. package/dist/packages/update.d.ts +124 -0
  213. package/dist/packages/update.js +476 -0
  214. package/dist/render/options.d.ts +2 -0
  215. package/dist/render/options.js +44 -5
  216. package/dist/render/pbr.d.ts +28 -0
  217. package/dist/render/pbr.js +378 -0
  218. package/dist/render/preview.d.ts +69 -0
  219. package/dist/render/preview.js +26 -0
  220. package/dist/render/raster.d.ts +78 -7
  221. package/dist/render/raster.js +600 -145
  222. package/dist/render/texview.d.ts +7 -1
  223. package/dist/render/texview.js +34 -2
  224. package/dist/scan.d.ts +61 -0
  225. package/dist/scan.js +228 -0
  226. package/dist/session.d.ts +311 -0
  227. package/dist/session.js +849 -0
  228. package/dist/viewer/app/api.js +48 -6
  229. package/dist/viewer/app/camera.js +1 -1
  230. package/dist/viewer/app/cooking.js +78 -0
  231. package/dist/viewer/app/embed.js +100 -0
  232. package/dist/viewer/app/export-popover.js +118 -16
  233. package/dist/viewer/app/grid.js +6 -2
  234. package/dist/viewer/app/guides.js +123 -1
  235. package/dist/viewer/app/keymap.js +7 -4
  236. package/dist/viewer/app/layers.js +5 -5
  237. package/dist/viewer/app/main.js +186 -53
  238. package/dist/viewer/app/markers.js +61 -1
  239. package/dist/viewer/app/outliner.js +72 -27
  240. package/dist/viewer/app/output-info.js +45 -0
  241. package/dist/viewer/app/outputs.css +147 -8
  242. package/dist/viewer/app/outputs.js +168 -54
  243. package/dist/viewer/app/packages.js +614 -0
  244. package/dist/viewer/app/props.js +177 -53
  245. package/dist/viewer/app/scene.js +35 -6
  246. package/dist/viewer/app/select.js +5 -4
  247. package/dist/viewer/app/selection.js +1 -1
  248. package/dist/viewer/app/status.js +12 -15
  249. package/dist/viewer/app/style.css +66 -8
  250. package/dist/viewer/app/units.js +1 -1
  251. package/dist/viewer/app/vars.js +48 -1
  252. package/dist/viewer/app/welcome.js +72 -0
  253. package/dist/viewer/graph-file.d.ts +62 -0
  254. package/dist/viewer/graph-file.js +175 -0
  255. package/dist/viewer/index.html +24 -11
  256. package/dist/viewer/json-edit.d.ts +13 -0
  257. package/dist/viewer/json-edit.js +274 -0
  258. package/dist/viewer/outputs.d.ts +49 -5
  259. package/dist/viewer/outputs.js +264 -56
  260. package/dist/viewer/packages.d.ts +121 -0
  261. package/dist/viewer/packages.js +584 -0
  262. package/dist/viewer/server.d.ts +24 -7
  263. package/dist/viewer/server.js +289 -31
  264. package/dist/web/app/web.css +419 -0
  265. package/dist/web/app/web.js +188 -0
  266. package/dist/web/bake.d.ts +34 -0
  267. package/dist/web/bake.js +153 -0
  268. package/dist/web/folder-page.d.ts +101 -0
  269. package/dist/web/folder-page.js +146 -0
  270. package/dist/web/folders.d.ts +280 -0
  271. package/dist/web/folders.js +970 -0
  272. package/dist/web/library.d.ts +91 -0
  273. package/dist/web/library.js +228 -0
  274. package/dist/web/markdown.d.ts +45 -0
  275. package/dist/web/markdown.js +677 -0
  276. package/dist/web/pages.d.ts +258 -0
  277. package/dist/web/pages.js +301 -0
  278. package/dist/web/server.d.ts +24 -0
  279. package/dist/web/server.js +1068 -0
  280. package/dist/workspace.d.ts +88 -105
  281. package/dist/workspace.js +359 -375
  282. package/integrations/godot/addons/topotopo/LICENSE +202 -0
  283. package/integrations/godot/addons/topotopo/README.md +57 -0
  284. package/integrations/godot/addons/topotopo/context_menu.gd +43 -0
  285. package/integrations/godot/addons/topotopo/dock.gd +266 -0
  286. package/integrations/godot/addons/topotopo/dock.tscn +72 -0
  287. package/integrations/godot/addons/topotopo/export_filter.gd +72 -0
  288. package/integrations/godot/addons/topotopo/gltf_instancing.gd +131 -0
  289. package/integrations/godot/addons/topotopo/icons/topotopo.svg +1 -0
  290. package/integrations/godot/addons/topotopo/inspector.gd +38 -0
  291. package/integrations/godot/addons/topotopo/instances_post_import.gd +111 -0
  292. package/integrations/godot/addons/topotopo/package.gd +23 -0
  293. package/integrations/godot/addons/topotopo/package_importer.gd +187 -0
  294. package/integrations/godot/addons/topotopo/plugin.cfg +7 -0
  295. package/integrations/godot/addons/topotopo/plugin.gd +970 -0
  296. package/integrations/godot/addons/topotopo/record.gd +435 -0
  297. package/integrations/godot/addons/topotopo/runner.gd +458 -0
  298. package/integrations/godot/addons/topotopo/tools/check.gd +42 -0
  299. package/integrations/godot/addons/topotopo/watcher.gd +199 -0
  300. package/kernels/pkg/README.md +23 -29
  301. package/kernels/pkg-simd/README.md +23 -29
  302. package/library/architecture/versions/1.0/architecture.topo +12 -0
  303. package/{shelf → library/architecture/versions/1.0/graphs}/arch.json +3 -3
  304. package/{shelf → library/architecture/versions/1.0/graphs}/beam_truss.json +6 -6
  305. package/{shelf → library/architecture/versions/1.0/graphs}/brick_wall.json +8 -8
  306. package/{shelf → library/architecture/versions/1.0/graphs}/door_frame.json +3 -3
  307. package/{shelf → library/architecture/versions/1.0/graphs}/hex_grid_floor.json +3 -2
  308. package/{shelf → library/architecture/versions/1.0/graphs}/house.json +8 -8
  309. package/library/architecture/versions/1.0/graphs/lineup.json +42 -0
  310. package/{shelf → library/architecture/versions/1.0/graphs}/pillar.json +3 -2
  311. package/{shelf → library/architecture/versions/1.0/graphs}/railing.json +5 -5
  312. package/{shelf → library/architecture/versions/1.0/graphs}/roof_gable.json +2 -2
  313. package/{shelf → library/architecture/versions/1.0/graphs}/roof_hip.json +2 -2
  314. package/{shelf → library/architecture/versions/1.0/graphs}/roof_skeleton.json +2 -1
  315. package/{shelf → library/architecture/versions/1.0/graphs}/scaffold.json +4 -4
  316. package/{shelf → library/architecture/versions/1.0/graphs}/spiral_stairs.json +3 -2
  317. package/{shelf → library/architecture/versions/1.0/graphs}/stairs.json +6 -6
  318. package/{shelf → library/architecture/versions/1.0/graphs}/tile_floor.json +3 -2
  319. package/{shelf → library/architecture/versions/1.0/graphs}/wall_segment.json +10 -10
  320. package/{shelf → library/architecture/versions/1.0/graphs}/window_frame.json +2 -2
  321. package/library/architecture/versions/1.0/version.json +1119 -0
  322. package/{shelf → library/nature/versions/1.0/graphs}/bush.json +2 -2
  323. package/{shelf → library/nature/versions/1.0/graphs}/cliff_block.json +4 -3
  324. package/{shelf → library/nature/versions/1.0/graphs}/forest_patch.json +5 -5
  325. package/{shelf → library/nature/versions/1.0/graphs}/grass_clumps.json +2 -2
  326. package/library/nature/versions/1.0/graphs/lineup.json +24 -0
  327. package/{shelf → library/nature/versions/1.0/graphs}/log.json +6 -6
  328. package/{shelf → library/nature/versions/1.0/graphs}/rock.json +5 -4
  329. package/{shelf → library/nature/versions/1.0/graphs}/scatter_rocks.json +5 -5
  330. package/{shelf → library/nature/versions/1.0/graphs}/tree_lowpoly.json +3 -2
  331. package/library/nature/versions/1.0/nature.topo +12 -0
  332. package/library/nature/versions/1.0/version.json +534 -0
  333. package/{shelf → library/props/versions/1.0/graphs}/barrel.json +5 -4
  334. package/{shelf → library/props/versions/1.0/graphs}/crate.json +3 -3
  335. package/library/props/versions/1.0/graphs/lineup.json +18 -0
  336. package/{shelf → library/props/versions/1.0/graphs}/pallet.json +4 -3
  337. package/{shelf → library/props/versions/1.0/graphs}/pipe_run.json +3 -3
  338. package/{shelf → library/props/versions/1.0/graphs}/sandbag_wall.json +5 -5
  339. package/library/props/versions/1.0/props.topo +12 -0
  340. package/library/props/versions/1.0/version.json +336 -0
  341. package/{shelf → library/street/versions/1.0/graphs}/bench.json +5 -5
  342. package/{shelf → library/street/versions/1.0/graphs}/bollard.json +2 -1
  343. package/{shelf → library/street/versions/1.0/graphs}/cable.json +4 -4
  344. package/{shelf → library/street/versions/1.0/graphs}/fence.json +7 -7
  345. package/{shelf → library/street/versions/1.0/graphs}/lamp_post.json +2 -2
  346. package/library/street/versions/1.0/graphs/lineup.json +22 -0
  347. package/{shelf → library/street/versions/1.0/graphs}/road_strip.json +2 -2
  348. package/{shelf → library/street/versions/1.0/graphs}/sign_post.json +1 -1
  349. package/library/street/versions/1.0/street.topo +12 -0
  350. package/library/street/versions/1.0/version.json +421 -0
  351. package/package.json +23 -8
  352. package/dist/graph/migrate.d.ts +0 -23
  353. package/dist/graph/migrate.js +0 -58
  354. package/shelf/index.json +0 -190
package/dist/io/gltf.js CHANGED
@@ -12,28 +12,43 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
12
12
  // Export layout
13
13
  // one node + mesh per prim "name" (splitByName), one primitive per material within a mesh:
14
14
  // polygons → TRIANGLES, polylines → one LINE_STRIP per curve (or LINES), isolated points → POINTS.
15
- // POSITION · NORMAL (N, else computed) · TEXCOORD_0/1 from uv/uv2 (V flipped) · COLOR_0 from Cd (+Alpha → VEC4).
16
- // Custom attributes: every other numeric point/vertex attribute of size 1–4 becomes `_NAME` (upper-cased; float,
17
- // or the smallest integer type that holds an int attribute). The original names and types are kept in mesh
18
- // extras (topotopo.attributes), so imports restore them exactly. POINTS always carry pscale as `_PSCALE`.
15
+ // Scene empties (isolated points marked scene_empty, core/scene.ts; the scene_null node) → nodes without a mesh, under
16
+ // their parent (the scene, another empty or a uniquely named mesh node), with the local TRS that reproduces their
17
+ // geometry-space transform; other set point attributes → node extras. Missing, ambiguous or cyclic parents, and
18
+ // parents that are GPU-instanced meshes, are errors.
19
+ // POSITION · NORMAL (N, else computed) · TANGENT (see below) · TEXCOORD_0/1 from uv/uv2 (V flipped, core/texcoord.ts)
20
+ // · COLOR_0 from Cd (+Alpha → VEC4).
21
+ // TANGENT (option tangents, default 'auto'): MikkTSpace tangents (core/tangents.ts) computed per triangle corner from
22
+ // the exported positions, normals and uv BEFORE vertices are welded, so uv seams, hard normals and mirrored islands
23
+ // keep their own frames, for every primitive whose material has a normal map; a supplied point/vertex "tangent"
24
+ // float[4] attribute is written on the others ('preserve': everywhere it exists). Collapsed or missing uvs are
25
+ // reported, never written as invalid tangents.
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.
19
31
  // Materials: the prim "material" attribute names a material of the detail table "materials" (core/materials.ts).
20
32
  // Colour space: TopoTopo colours (Cd, material base/emissive colours) are display values; glTF defines
21
33
  // baseColorFactor, emissiveFactor and COLOR_0 as linear, so they are converted on export and back on import.
22
- // Vertex colours win: a primitive with Cd gets baseColorFactor white × COLOR_0, the material supplies the PBR
23
- // scalars; the original material is kept in material extras (topotopo.material) for lossless re-import.
24
- // A primitive whose Cd is one constant colour writes it as the baseColorFactor instead of COLOR_0 (the same
25
- // colour under glTF's factor × COLOR_0, and visible in engines whose default materials ignore vertex colours,
26
- // 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.
27
41
  // Options: quantize (KHR_mesh_quantization), compress 'meshopt' (EXT_meshopt_compression, implies quantize),
28
42
  // compress 'draco' (KHR_draco_mesh_compression, only when the optional draco3dgltf package is installed).
29
43
  // Packed instances (instancing 'packed', the default): one mesh + node per packed source with EXT_mesh_gpu_instancing
30
44
  // (TRANSLATION / ROTATION / SCALE per instance; a 3×3 with shear is written as its nearest rotation and the
31
45
  // scale of its columns, with a warning); the rest of the geometry as above. instancing 'expand' writes real copies.
32
- // 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
33
47
  // accessors with the extension's "_" prefix: Cd (+ Alpha) → _COLOR (VEC3/VEC4 float), every other numeric attribute
34
48
  // of size 1–4 → _NAME, single strings → _NAME indices into a table in the node's extras; all as 32-bit floats (exact
35
49
  // for integers below 2^24; 1- and 2-byte components break EXT_meshopt_compression's 4-byte instance strides); the
36
- // 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).
37
52
  // Node extras (topotopo.instanceAttributes) keep names, classes, types and string tables for re-import.
38
53
  // Node and mesh names are packedSourceNames() (the source's prim "name", else source_<i>), as in the instance stream.
39
54
  // Textures: the material table's texture paths (base colour, normal, roughness) are read with options.readFile and
@@ -41,13 +56,16 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
41
56
  // a map replaces its factor (baseColorFactor white, roughnessFactor 1). Without readFile the maps are skipped.
42
57
  // "image:<name>" paths are image volumes of the geometry (texture nodes), encoded to PNG in memory; an "orm" map is
43
58
  // both the metallicRoughness and the occlusion texture (metallicFactor 1).
59
+ // options.source (how the export was made, io/source.ts) → asset.extras.source.
44
60
  //
45
61
  // Import
46
- // node hierarchy flattened with world transforms, EXT_mesh_gpu_instancing as packed prims (one source per mesh;
62
+ // node hierarchy flattened with world transforms (nodes without a mesh → scene empties: points with scene_empty 1,
63
+ // name, parent = the nearest imported ancestor, P / orient / scale in world space, extras as attributes), EXT_mesh_gpu_instancing as packed prims (one source per mesh;
47
64
  // instancing 'expand' = real geometry), every primitive mode,
48
65
  // meshopt (meshoptimizer decoder) and Draco (when draco3dgltf is installed) decoded, external .bin files read
49
66
  // relative to the file. Mesh/node names → prim "name", materials → prim "material" + table, COLOR_0 → Cd/Alpha,
50
- // TEXCOORD_0/1 → uv/uv2, custom `_X` → attributes, instance `_X` accessors → anchor attributes. Texture images are
67
+ // TEXCOORD_0/1 → uv/uv2, TANGENT → point "tangent" (float[4]; node transforms applied, w flipped under mirrors),
68
+ // custom `_X` → attributes, instance `_X` accessors → anchor attributes. Texture images are
51
69
  // not decoded: their paths (URI resolved against the file, or "embedded:<name>" for images inside a GLB) go into the
52
70
  // material table's textures entries; files written by topotopo restore the original paths from material extras,
53
71
  // and their "image:<name>" textures are decoded back into image volumes (8-bit precision).
@@ -56,8 +74,12 @@ import { ALL_EXTENSIONS, EXTMeshGPUInstancing, EXTMeshoptCompression, KHRDracoMe
56
74
  import { MeshoptDecoder, MeshoptEncoder } from 'meshoptimizer';
57
75
  import { Attribute, AttribTable, Geometry, defaultValueFor } from '../core/geometry.js';
58
76
  import { resolveVertexNormals, triangulate } from '../core/topology.js';
59
- import { DEFAULT_MATERIAL, mergeMaterialTables, normalizeMaterial, primMaterials, texturePaths, writeMaterials } from '../core/materials.js';
60
- import { m4apply, m4applyDir, m4fromQuat, m4mul, m4normalMatrix, m4scale, m4translate } from '../core/math.js';
77
+ import { TANGENT_ATTRIB, cornerTangents, loadMikkTSpace, tangentProblem, transformTangents, vertexUV } from '../core/tangents.js';
78
+ import { gltfV } from '../core/texcoord.js';
79
+ import { posText, primWhere } from '../core/report.js';
80
+ import { DEFAULT_MATERIAL, materialAlphaMode, mergeMaterialTables, normalizeMaterial, primMaterials, texturePaths, writeMaterials } from '../core/materials.js';
81
+ import { m4apply, m4applyDir, m4fromQuat, m4invert, m4mul, m4normalMatrix, m4scale, m4translate } from '../core/math.js';
82
+ import { EMPTY_ATTRIB, PARENT_ATTRIB, sceneEmpties } from '../core/scene.js';
61
83
  import { INSTANCE_ATTRIB_SKIP, anchorAttribs, anchorValue, baseOf, decomposeXform, isolatedMask, packedSourceNames, pieces, xf, xfDir, xfLinear } from './common.js';
62
84
  import { DEFAULT_TRANSFER, expandPacked, flattenSource, packedFromMatrices, stripPacked, xform3 } from '../core/packed.js';
63
85
  import { hasSplinesDeep, splinesToPolylinesDeep } from '../core/splines.js';
@@ -67,7 +89,7 @@ import { imageRef } from '../core/image.js';
67
89
  /** Above this many polylines per material and mesh, curves go into one LINES primitive instead of LINE_STRIPs. */
68
90
  const MAX_LINE_STRIPS = 256;
69
91
  /** Attributes with a dedicated glTF semantic (never exported as `_NAME`). */
70
- const RESERVED = new Set(['P', 'N', 'uv', 'uv2', 'Cd', 'Alpha', 'material', 'name']);
92
+ const RESERVED = new Set(['P', 'N', 'uv', 'uv2', 'Cd', 'Alpha', 'material', 'name', TANGENT_ATTRIB]);
71
93
  const TYPES = ['SCALAR', 'VEC2', 'VEC3', 'VEC4'];
72
94
  const DRACO_MODULE = 'draco3dgltf';
73
95
  // ------------------------------------------------------------------ IO
@@ -171,14 +193,14 @@ function colorChannel(g) {
171
193
  const size = al ? 4 : 3;
172
194
  return {
173
195
  semantic: 'COLOR_0', size, int: false, perPoint: (!cd || cd.perPoint) && (!al || al.perPoint),
174
- read(v, pt, pr, out, o) {
196
+ read(v, pt, pr, out, o, k) {
175
197
  if (cd)
176
- cd.read(v, pt, pr, out, o);
198
+ cd.read(v, pt, pr, out, o, k);
177
199
  else {
178
200
  out[o] = out[o + 1] = out[o + 2] = 1;
179
201
  }
180
202
  if (al)
181
- al.read(v, pt, pr, out, o + 3);
203
+ al.read(v, pt, pr, out, o + 3, k);
182
204
  },
183
205
  };
184
206
  }
@@ -220,7 +242,7 @@ function emit(channels, corners, vprim, g, weld) {
220
242
  const v = corners[k];
221
243
  const pt = v >= 0 ? g.vertexPoint[v] : -1 - v;
222
244
  const pr = v >= 0 && vprim ? vprim[v] : -1;
223
- channels.forEach((c, ci) => c.read(v >= 0 ? v : -1, pt, pr, tmp[ci], 0));
245
+ channels.forEach((c, ci) => c.read(v >= 0 ? v : -1, pt, pr, tmp[ci], 0, k));
224
246
  let key = pt;
225
247
  if (weld && keyed.length) {
226
248
  let s = String(pt);
@@ -243,6 +265,16 @@ function emit(channels, corners, vprim, g, weld) {
243
265
  }
244
266
  return { data, count, idx };
245
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
+ };
246
278
  /** Image MIME type from the first bytes (PNG or JPEG), or null. */
247
279
  export function imageMime(b) {
248
280
  if (b.length >= 8 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47)
@@ -251,7 +283,10 @@ export function imageMime(b) {
251
283
  return 'image/jpeg';
252
284
  return null;
253
285
  }
254
- /** 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
+ */
255
290
  function textureFor(st, path) {
256
291
  if (!st.data)
257
292
  return null;
@@ -264,13 +299,23 @@ function textureFor(st, path) {
264
299
  if (bytes && !mime)
265
300
  st.warn?.(`glTF: texture "${path}" is not a PNG or JPEG image; material exported without it`);
266
301
  if (bytes && mime) {
267
- const base = (path.startsWith('image:') ? path.slice(6) : baseOf(path).replace(/\.[^.]*$/, '')).replace(/[^A-Za-z0-9_-]+/g, '_') || 'texture';
268
- const ext = mime === 'image/png' ? '.png' : '.jpg';
269
- let uri = base + ext, k = 1;
270
- while (st.uris.has(uri))
271
- uri = `${base}_${k++}${ext}`;
272
- st.uris.add(uri);
273
- 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
+ }
274
319
  }
275
320
  st.textures.set(path, t);
276
321
  return t;
@@ -314,8 +359,9 @@ function getMaterial(st, name, vertexColors, blend, tint) {
314
359
  }
315
360
  else
316
361
  m.setEmissiveFactor([toLinear(mat.emissive[0]), toLinear(mat.emissive[1]), toLinear(mat.emissive[2])]);
317
- if (mat.alpha < 1 || blend)
318
- m.setAlphaMode('BLEND');
362
+ m.setAlphaMode(materialAlphaMode(mat, blend));
363
+ if (mat.alphaMode === 'MASK')
364
+ m.setAlphaCutoff(mat.alphaCutoff ?? 0.5);
319
365
  if (mat.unlit)
320
366
  m.setExtension('KHR_materials_unlit', st.doc.createExtension(KHRMaterialsUnlit).createUnlit());
321
367
  m.setExtras({ topotopo: isDefault ? { default: true } : { material: mat } });
@@ -323,7 +369,7 @@ function getMaterial(st, name, vertexColors, blend, tint) {
323
369
  return m;
324
370
  }
325
371
  /** Display (sRGB-encoded) value to linear and back: glTF's factors and COLOR_0 are linear, TopoTopo colours are display
326
- * values (docs/DESIGN.md, colour). */
372
+ * values. */
327
373
  const toLinear = (c) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
328
374
  const toDisplay = (c) => (c <= 0.0031308 ? c * 12.92 : 1.055 * c ** (1 / 2.4) - 0.055);
329
375
  /** True when every element of a colour stream has the same rgb. */
@@ -341,12 +387,65 @@ const rgbAllOnes = (d, size) => {
341
387
  return true;
342
388
  };
343
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
+ }
344
431
  /** Build a gltf-transform Document for the geometry (no IO yet). */
345
432
  export function gltfDocument(g, o = {}) {
346
433
  if (hasSplinesDeep(g))
347
434
  g = splinesToPolylinesDeep(g).geo; // Bezier/NURBS prims (also in packed sources) as polylines
435
+ // scene empties become nodes, not POINTS
436
+ const empties = sceneEmpties(g);
437
+ if (empties.length) {
438
+ const keep = new Uint8Array(g.numPoints).fill(1);
439
+ for (const e of empties)
440
+ keep[e.point] = 0;
441
+ g = g.subsetPoints(keep);
442
+ dropEmptyAttributes(g, empties);
443
+ }
348
444
  const doc = new Document();
349
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 };
350
449
  const buffer = doc.createBuffer();
351
450
  const scene = doc.createScene('scene');
352
451
  doc.getRoot().setDefaultScene(scene);
@@ -354,10 +453,11 @@ export function gltfDocument(g, o = {}) {
354
453
  const useMaterials = o.materials !== false;
355
454
  const st = {
356
455
  doc, table: useMaterials ? mergeMaterialTables([g, ...g.packedSources]) : {}, cache: new Map(), defaultMat: DEFAULT_MATERIAL,
357
- 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,
358
457
  };
359
458
  let noUV = 0;
360
- const custom = o.custom !== false;
459
+ const custom = o.custom === true;
460
+ const tangentMode = o.tangents ?? 'auto';
361
461
  const lineMode = o.lineMode ?? 'strip';
362
462
  // what to write: the geometry, or (packed) its non-instanced part plus one instanced mesh per packed source
363
463
  const split = o.splitByName ?? true;
@@ -379,7 +479,7 @@ export function gltfDocument(g, o = {}) {
379
479
  semantic: 'POSITION', size: 3, int: false, perPoint: true,
380
480
  read(_v, pt, _pr, out, oo) { const P = geo.P; const p = xf(P[pt * 3], P[pt * 3 + 1], P[pt * 3 + 2], o); out[oo] = p[0]; out[oo + 1] = p[1]; out[oo + 2] = p[2]; },
381
481
  };
382
- const uvCh = (n, sem) => attribChannel(geo, n, sem, ['vertex', 'point', 'prim', 'detail'], (s, out, oo) => { out[oo] = s[0]; out[oo + 1] = 1 - (s[1] ?? 0); }, 2);
482
+ const uvCh = (n, sem) => attribChannel(geo, n, sem, ['vertex', 'point', 'prim', 'detail'], (s, out, oo) => { out[oo] = s[0]; out[oo + 1] = gltfV(s[1] ?? 0); }, 2);
383
483
  const color = colorChannel(geo);
384
484
  const customs = custom ? customChannels(geo, used, info) : [];
385
485
  // group prims by (closed, material)
@@ -396,6 +496,8 @@ export function gltfDocument(g, o = {}) {
396
496
  }
397
497
  const hasN = !!(geo.vertices.get('N') ?? geo.points.get('N'));
398
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);
399
501
  const finishColor = (out, mat) => {
400
502
  // vertex colours win where they are set; all-white Cd lets the material colour through
401
503
  const ci = color ? out.channels.indexOf(color) : -1;
@@ -425,6 +527,62 @@ export function gltfDocument(g, o = {}) {
425
527
  noUV++;
426
528
  }
427
529
  };
530
+ /**
531
+ * TANGENT of one triangle primitive (option tangents): the supplied tangent attribute where the mode takes it
532
+ * (validated), else MikkTSpace per corner for a normal-mapped material, else none.
533
+ */
534
+ const tangentChannel = (tris, nrm, mat, piece) => {
535
+ if (tangentMode === 'none')
536
+ return null;
537
+ const m = mat ? st.table[mat] : undefined;
538
+ const normalMapped = !!(m?.textures?.normal && textureFor(st, m.textures.normal));
539
+ const supplied = geo.findAttrib(TANGENT_ATTRIB, ['vertex', 'point']);
540
+ const where = `mesh "${piece}"${mat ? ` material "${mat}"` : ''}`;
541
+ if (supplied && (tangentMode === 'preserve' || !normalMapped)) {
542
+ const bad = tangentProblem(geo);
543
+ if (bad && tangentMode === 'preserve')
544
+ throw new Error(`glTF: tangents "preserve": ${where}: ${bad}`);
545
+ if (bad)
546
+ o.warn?.(`glTF: ${where}: supplied tangent attribute not written (${bad})`);
547
+ else if (!nrm)
548
+ o.warn?.(`glTF: ${where}: tangent attribute without NORMAL (normals: false): no TANGENT written`);
549
+ else {
550
+ const L = xfLinear([1, 0, 0, 0, 1, 0, 0, 0, 1], 0, o), tmp = new Float64Array(4);
551
+ return attribChannel(geo, TANGENT_ATTRIB, 'TANGENT', ['vertex', 'point'], (s, out, oo) => {
552
+ tmp[0] = s[0];
553
+ tmp[1] = s[1];
554
+ tmp[2] = s[2];
555
+ tmp[3] = s[3];
556
+ transformTangents(tmp, 1, L);
557
+ out[oo] = tmp[0];
558
+ out[oo + 1] = tmp[1];
559
+ out[oo + 2] = tmp[2];
560
+ out[oo + 3] = tmp[3];
561
+ }, 4);
562
+ }
563
+ }
564
+ if (!normalMapped)
565
+ return null;
566
+ if (!nrm) {
567
+ o.warn?.(`glTF: ${where}: normal map without NORMAL (normals: false): no TANGENT written`);
568
+ return null;
569
+ }
570
+ const uv = vertexUV(geo, 'uv');
571
+ if (!uv)
572
+ return null; // reported once, as a textured primitive without uv
573
+ const { tangents, diag } = cornerTangents(geo, tris, nrm, uv);
574
+ if (diag.uvNonFinite || diag.uvDegenerate) {
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`);
578
+ }
579
+ else if (diag.fallbackCorners)
580
+ o.warn?.(`glTF: ${where}: MikkTSpace left ${diag.fallbackCorners} corners without a tangent; a fallback was written`);
581
+ return {
582
+ semantic: 'TANGENT', size: 4, int: false, perPoint: false,
583
+ read(_v, _pt, _pr, out, oo, k) { const d = xfDir(tangents[k * 4], tangents[k * 4 + 1], tangents[k * 4 + 2], o); out[oo] = d[0]; out[oo + 1] = d[1]; out[oo + 2] = d[2]; out[oo + 3] = tangents[k * 4 + 3]; },
584
+ };
585
+ };
428
586
  for (const gr of groups.values()) {
429
587
  if (gr.closed) {
430
588
  const { tris } = triangulate(geo, gr.mask);
@@ -440,12 +598,16 @@ export function gltfDocument(g, o = {}) {
440
598
  chans.push({ semantic: 'NORMAL', size: 3, int: false, perPoint: pointN, read(v, _pt, _pr, out, oo) { const d = xfDir(nn[v * 3], nn[v * 3 + 1], nn[v * 3 + 2], o); out[oo] = d[0]; out[oo + 1] = d[1]; out[oo + 2] = d[2]; } });
441
599
  }
442
600
  const uv0 = uvCh('uv', 'TEXCOORD_0'), uv1 = uvCh('uv2', 'TEXCOORD_1');
601
+ const tan = tangentChannel(tris, normals, gr.mat, name);
602
+ if (tan)
603
+ chans.push(tan);
443
604
  if (uv0)
444
605
  chans.push(uv0);
445
606
  if (uv1)
446
607
  chans.push(uv1);
447
- if (color)
448
- chans.push(color);
608
+ const col = colorFor(gr.mat);
609
+ if (col)
610
+ chans.push(col);
449
611
  chans.push(...customs);
450
612
  const e = emit(chans, tris, vprim, geo, true);
451
613
  const out = { mode: Primitive.Mode.TRIANGLES, channels: chans, data: e.data, count: e.count, indices: e.idx, material: null };
@@ -468,8 +630,9 @@ export function gltfDocument(g, o = {}) {
468
630
  const uv0 = uvCh('uv', 'TEXCOORD_0');
469
631
  if (uv0)
470
632
  chans.push(uv0);
471
- if (color)
472
- chans.push(color);
633
+ const col = colorFor(gr.mat);
634
+ if (col)
635
+ chans.push(col);
473
636
  chans.push(...customs);
474
637
  const strips = lineMode === 'strip' && curves.length <= MAX_LINE_STRIPS;
475
638
  const batches = strips ? curves.map((c) => [c]) : [curves];
@@ -528,38 +691,151 @@ export function gltfDocument(g, o = {}) {
528
691
  const w = writeMesh(doc, buffer, scene, name, outs, info, quantize);
529
692
  job.onMesh?.(w);
530
693
  }
694
+ if (empties.length)
695
+ writeEmpties(doc, scene, empties, o);
531
696
  if (quantize)
532
697
  doc.createExtension(KHRMeshQuantization).setRequired(true);
533
698
  if (noUV)
534
699
  o.warn?.(`glTF: ${noUV} primitive(s) use a textured material but have no uv attribute (add uv_project or uv_unwrap)`);
535
700
  return doc;
536
701
  }
702
+ /**
703
+ * Scene empties as meshless nodes. Parents resolve by name among the empties and the mesh nodes written so far; each
704
+ * node gets the local TRS that places it at its geometry-space transform (in export space: axis conversion, scale).
705
+ */
706
+ function writeEmpties(doc, scene, empties, o) {
707
+ const meshNodes = new Map();
708
+ for (const n of doc.getRoot().listNodes()) {
709
+ const l = meshNodes.get(n.getName());
710
+ if (l)
711
+ l.push(n);
712
+ else
713
+ meshNodes.set(n.getName(), [n]);
714
+ }
715
+ const byName = new Map();
716
+ for (const e of empties) {
717
+ if (!e.name)
718
+ throw new Error(`glTF: the scene empty at ${posText(e.P)} (point ${e.point}) has no name: give scene_null a name`);
719
+ const l = byName.get(e.name);
720
+ if (l)
721
+ l.push(e);
722
+ else
723
+ byName.set(e.name, [e]);
724
+ }
725
+ const parentOf = new Map();
726
+ for (const e of empties) {
727
+ if (!e.parent) {
728
+ parentOf.set(e, null);
729
+ continue;
730
+ }
731
+ const es = byName.get(e.parent) ?? [], ms = meshNodes.get(e.parent) ?? [];
732
+ const where = `glTF: scene empty "${e.name}": parent "${e.parent}"`;
733
+ // without splitByName every mesh is merged into one node ("mesh"), so a named mesh parent no longer exists: the
734
+ // empty goes on the scene root, where its geometry-space transform places it the same (previews, viewers)
735
+ if (!es.length && !ms.length && o.splitByName === false) {
736
+ parentOf.set(e, null);
737
+ continue;
738
+ }
739
+ if (!es.length && !ms.length)
740
+ throw new Error(`${where} is neither an empty nor a mesh (meshes: ${[...meshNodes.keys()].slice(0, 12).join(', ') || 'none'}; empties: ${[...byName.keys()].slice(0, 12).join(', ')})`);
741
+ if (es.length + ms.length > 1)
742
+ throw new Error(`${where} is ambiguous: ${es.length} empt${es.length === 1 ? 'y' : 'ies'} and ${ms.length} mesh${ms.length === 1 ? '' : 'es'} have that name`);
743
+ if (ms.length && ms[0].getExtension('EXT_mesh_gpu_instancing'))
744
+ throw new Error(`${where} is a GPU-instanced mesh; parenting to an individual instance is not supported (parent to the scene or an empty instead)`);
745
+ parentOf.set(e, es.length ? { empty: es[0] } : { node: ms[0] });
746
+ }
747
+ for (const e of empties) {
748
+ const chain = [];
749
+ const seen = new Set();
750
+ for (let c = e; c;) {
751
+ if (seen.has(c))
752
+ throw new Error(`glTF: scene empties form a parent cycle: ${[...chain, c.name].join(' → ')}`);
753
+ seen.add(c);
754
+ chain.push(c.name);
755
+ const pr = parentOf.get(c);
756
+ c = pr && 'empty' in pr ? pr.empty : null;
757
+ }
758
+ }
759
+ // world matrix in export space: translation converted like positions, rotation conjugated by the axis change
760
+ const world = new Map();
761
+ for (const e of empties) {
762
+ const R = xfLinear(xform3(m4fromQuat(e.orient)), 0, o), t = xf(e.P[0], e.P[1], e.P[2], o);
763
+ const m = new Float64Array(16);
764
+ for (let c = 0; c < 3; c++)
765
+ for (let r = 0; r < 3; r++)
766
+ m[c * 4 + r] = R[c * 3 + r] * e.scale[c];
767
+ m[12] = t[0];
768
+ m[13] = t[1];
769
+ m[14] = t[2];
770
+ m[15] = 1;
771
+ world.set(e, m);
772
+ }
773
+ const made = new Map();
774
+ const make = (e) => {
775
+ const done = made.get(e);
776
+ if (done)
777
+ return done;
778
+ const pr = parentOf.get(e);
779
+ const parentNode = pr ? ('empty' in pr ? make(pr.empty) : pr.node) : null;
780
+ const pw = pr ? ('empty' in pr ? world.get(pr.empty) : Float64Array.from(pr.node.getWorldMatrix())) : null;
781
+ const local = pw ? m4mul(m4invert(pw), world.get(e)) : world.get(e);
782
+ const { q, s, shear } = decomposeXform(xform3(local));
783
+ if (shear)
784
+ o.warn?.(`glTF: scene empty "${e.name}": its transform relative to "${e.parent}" has shear (non-uniform parent scale with rotation); the nearest TRS was written`);
785
+ const node = doc.createNode(e.name).setTranslation([local[12], local[13], local[14]]).setRotation([q[0], q[1], q[2], q[3]]).setScale([s[0], s[1], s[2]]);
786
+ if (Object.keys(e.extras).length)
787
+ node.setExtras(e.extras);
788
+ if (parentNode)
789
+ parentNode.addChild(node);
790
+ else
791
+ scene.addChild(node);
792
+ made.set(e, node);
793
+ return node;
794
+ };
795
+ for (const e of empties)
796
+ make(e);
797
+ }
537
798
  /**
538
799
  * One job per packed source: its geometry (nested instances expanded) as a single mesh whose node gets
539
800
  * EXT_mesh_gpu_instancing with every instance's TRS in export space (axis conversion and scale applied).
540
801
  */
541
802
  function instanceJobs(doc, buffer, g, o, quantize) {
542
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;
543
813
  const bySrc = new Map();
544
814
  for (let p = 0; p < kind.length; p++) {
545
815
  if (kind[p] !== 1 || g.primStart[p + 1] - g.primStart[p] !== 1)
546
816
  continue;
547
- 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);
548
820
  if (!l) {
549
- l = [];
550
- bySrc.set(S[p], l);
821
+ l = { s, mat, prims: [] };
822
+ bySrc.set(key, l);
551
823
  }
552
- l.push(p);
824
+ l.prims.push(p);
553
825
  }
826
+ const perSource = new Map();
827
+ for (const { s } of bySrc.values())
828
+ perSource.set(s, (perSource.get(s) ?? 0) + 1);
554
829
  const ext = doc.createExtension(EXTMeshGPUInstancing).setRequired(true);
555
830
  const names = packedSourceNames(g);
556
- 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') : [];
557
833
  const info = {};
558
834
  for (const ia of iattrs)
559
835
  info[ia.sem] = { name: ia.a.name, cls: ia.a.cls, type: ia.type, size: ia.size, ...(ia.strings ? { strings: ia.strings } : {}) };
560
836
  let sheared = 0;
561
837
  const jobs = [];
562
- for (const [s, prims] of bySrc) {
838
+ for (const { s, mat, prims } of bySrc.values()) {
563
839
  const n = prims.length;
564
840
  const T = new Float64Array(n * 3), L = new Float64Array(n * 9), Q = new Float32Array(n * 4), SC = new Float64Array(n * 3);
565
841
  prims.forEach((p, i) => {
@@ -572,8 +848,12 @@ function instanceJobs(doc, buffer, g, o, quantize) {
572
848
  Q.set(d.q, i * 4);
573
849
  SC.set(d.s, i * 3);
574
850
  });
575
- const src = flattenSource(g.packedSources[s]);
576
- 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}` : '');
577
857
  jobs.push({
578
858
  src, split: false,
579
859
  onMesh: ({ node, center, extent }) => {
@@ -736,8 +1016,8 @@ function writeMesh(doc, buffer, scene, name, outs, info, quantize) {
736
1016
  q[i] = Math.round(Math.max(-1, Math.min(1, (d[i] - center[i % 3]) / extent)) * 32767);
737
1017
  a = acc(q, 3, true);
738
1018
  }
739
- else if (ch.semantic === 'NORMAL' && quantize) {
740
- a = acc(Int8Array.from(d, (x) => Math.round(Math.max(-1, Math.min(1, x)) * 127)), 3, true);
1019
+ else if ((ch.semantic === 'NORMAL' || ch.semantic === 'TANGENT') && quantize) {
1020
+ a = acc(Int8Array.from(d, (x) => Math.round(Math.max(-1, Math.min(1, x)) * 127)), ch.size, true);
741
1021
  }
742
1022
  else if (ch.semantic.startsWith('TEXCOORD_') && quantize && d.every((x) => x >= 0 && x <= 1)) {
743
1023
  a = acc(Uint16Array.from(d, (x) => Math.round(x * 65535)), 2, true);
@@ -823,6 +1103,8 @@ async function withTextures(g, o) {
823
1103
  /** GLB bytes. */
824
1104
  export async function exportGLB(g, o = {}) {
825
1105
  o = await withTextures(g, o);
1106
+ if (o.tangents !== 'none')
1107
+ await loadMikkTSpace();
826
1108
  const doc = gltfDocument(g, o);
827
1109
  const io = await exportIO(doc, o);
828
1110
  return io.writeBinary(doc);
@@ -830,6 +1112,8 @@ export async function exportGLB(g, o = {}) {
830
1112
  /** Self-contained .gltf JSON text (buffers embedded as data URIs). */
831
1113
  export async function exportGLTF(g, o = {}) {
832
1114
  o = await withTextures(g, o);
1115
+ if (o.tangents !== 'none')
1116
+ await loadMikkTSpace();
833
1117
  const doc = gltfDocument(g, o);
834
1118
  const io = await exportIO(doc, o);
835
1119
  const { json, resources } = await io.writeJSON(doc, { format: 'GLTF' });
@@ -916,6 +1200,7 @@ function materialEntry(m, base = '', index = () => 0) {
916
1200
  baseColor: [toDisplay(bc[0]), toDisplay(bc[1]), toDisplay(bc[2])], metallic: m.getMetallicFactor(), roughness: m.getRoughnessFactor(),
917
1201
  emissive: [toDisplay(em[0]) * strength, toDisplay(em[1]) * strength, toDisplay(em[2]) * strength], alpha: bc[3],
918
1202
  doubleSided: m.getDoubleSided(), unlit: !!m.getExtension('KHR_materials_unlit'),
1203
+ alphaMode: m.getAlphaMode(), alphaCutoff: m.getAlphaCutoff(),
919
1204
  textures: {
920
1205
  baseColor: texturePathOf(m.getBaseColorTexture(), base, index),
921
1206
  normal: texturePathOf(m.getNormalTexture(), base, index),
@@ -997,8 +1282,10 @@ function primitiveGeometry(prim, attrInfo, warn) {
997
1282
  continue;
998
1283
  if (sem === 'NORMAL')
999
1284
  setPt('N', a, 3, 'float');
1285
+ else if (sem === 'TANGENT' && es === 4)
1286
+ setPt(TANGENT_ATTRIB, a, 4, 'float');
1000
1287
  else if (sem === 'TEXCOORD_0' || sem === 'TEXCOORD_1')
1001
- setPt(sem === 'TEXCOORD_0' ? 'uv' : 'uv2', a, 3, 'float', (s, i, out) => { out[i * 3] = s[i * es]; out[i * 3 + 1] = 1 - s[i * es + 1]; out[i * 3 + 2] = 0; });
1288
+ setPt(sem === 'TEXCOORD_0' ? 'uv' : 'uv2', a, 3, 'float', (s, i, out) => { out[i * 3] = s[i * es]; out[i * 3 + 1] = gltfV(s[i * es + 1]); out[i * 3 + 2] = 0; });
1002
1289
  else if (sem === 'COLOR_0') {
1003
1290
  // COLOR_0 is linear; Cd holds display values
1004
1291
  setPt('Cd', a, 3, 'float', (s, i, out) => { out[i * 3] = toDisplay(s[i * es]); out[i * 3 + 1] = toDisplay(s[i * es + 1]); out[i * 3 + 2] = toDisplay(s[i * es + 2]); });
@@ -1010,7 +1297,7 @@ function primitiveGeometry(prim, attrInfo, warn) {
1010
1297
  const name = inf?.name ?? sem.slice(1).toLowerCase();
1011
1298
  setPt(name, a, es, inf?.type === 'int' ? 'int' : 'float');
1012
1299
  }
1013
- // TANGENT, JOINTS_n, WEIGHTS_n, TEXCOORD_2+, COLOR_1+ are not imported
1300
+ // JOINTS_n, WEIGHTS_n, TEXCOORD_2+, COLOR_1+ are not imported
1014
1301
  }
1015
1302
  // a constant Cd that the exporter folded into the material factor comes back as the point colour it was
1016
1303
  const folded = prim.getExtras()?.topotopo?.Cd;
@@ -1042,6 +1329,9 @@ function transformGeo(local, m) {
1042
1329
  d[i + 2] /= l;
1043
1330
  }
1044
1331
  }
1332
+ const T = g.points.get(TANGENT_ATTRIB);
1333
+ if (T && T.size === 4)
1334
+ transformTangents(T.data, g.numPoints, xform3(m));
1045
1335
  return g;
1046
1336
  }
1047
1337
  /** EXT_mesh_gpu_instancing: one matrix per instance (TRANSLATION · ROTATION · SCALE). */
@@ -1058,7 +1348,19 @@ function instanceMatrices(inst) {
1058
1348
  }
1059
1349
  return out;
1060
1350
  }
1061
- const RESERVED_EXTRAS = new Set('P N uv uv2 Cd Alpha material name path orient scale pscale'.split(' '));
1351
+ const RESERVED_EXTRAS = new Set(`P N uv uv2 Cd Alpha material name path orient scale pscale ${EMPTY_ATTRIB} ${PARENT_ATTRIB}`.split(' '));
1352
+ /**
1353
+ * The parent an imported empty refers to: the name (node name, else its mesh's) of the nearest ancestor that is imported
1354
+ * as an empty or a mesh; cameras, lights and GPU-instanced meshes are skipped (the world transform is kept either way).
1355
+ */
1356
+ function importedParent(node) {
1357
+ for (let p = node.getParentNode(); p; p = p.getParentNode()) {
1358
+ if (p.getCamera() || p.getExtension('KHR_lights_punctual') || p.getExtension('EXT_mesh_gpu_instancing'))
1359
+ continue;
1360
+ return p.getName() || p.getMesh()?.getName() || '';
1361
+ }
1362
+ return '';
1363
+ }
1062
1364
  function constantAttribute(table, name, type, size, value) {
1063
1365
  const a = table.add(name, type, size);
1064
1366
  for (let i = 0; i < table.count; i++)
@@ -1144,7 +1446,9 @@ export function documentToGeometry(doc, warn = () => { }, instancing = 'packed',
1144
1446
  if (!mesh) {
1145
1447
  const g = new Geometry({ positions: [world[12], world[13], world[14]] });
1146
1448
  const { q, s } = decomposeXform(xform3(world));
1449
+ constantAttribute(g.points, EMPTY_ATTRIB, 'int', 1, 1);
1147
1450
  constantAttribute(g.points, 'name', 'string', 1, node.getName());
1451
+ constantAttribute(g.points, PARENT_ATTRIB, 'string', 1, importedParent(node));
1148
1452
  constantAttribute(g.points, 'path', 'string', 1, path);
1149
1453
  constantAttribute(g.points, 'orient', 'float', 4, q);
1150
1454
  constantAttribute(g.points, 'scale', 'float', 3, s);