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
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,203 @@
1
+ // General-purpose image extraction, contour tracing, padding and atlas assembly.
2
+ import { Geometry, GeoBuilder } from '../core/geometry.js';
3
+ import { Image, imagesOf, toGrey, MAX_PIXELS } from '../core/image.js';
4
+ import { cropImage, dilateImage } from '../core/imageops.js';
5
+ import { traceMask } from '../core/traceimage.js';
6
+ import { skylinePack } from '../core/uv.js';
7
+ import { defineNode } from '../graph/registry.js';
8
+ import { NodeError } from '../graph/types.js';
9
+ import { NAMED_BY_NODE, imageParam, outName, renameParam, source, withLayer, checkSize, resolutionParam } from './texture.js';
10
+ const layerParam = () => ({ type: 'string', default: '', desc: 'layer name (empty selects the main layer)' });
11
+ const channelParam = (def = 'alpha') => ({ type: 'enum', options: ['alpha', 'luminance', 'r', 'g', 'b'], default: def, desc: 'channel to read; alpha requires RGBA, luminance/R/G/B accept grey' });
12
+ function channel(data, ch, which) {
13
+ if (which === 'luminance')
14
+ return toGrey(data, ch);
15
+ if (ch === 1) {
16
+ if (which === 'alpha')
17
+ throw new NodeError('alpha channel requires RGBA; select luminance for a grey mask');
18
+ return data;
19
+ }
20
+ const c = which === 'alpha' ? 3 : 'rgb'.indexOf(which);
21
+ return Float32Array.from({ length: data.length / 4 }, (_, i) => data[i * 4 + c]);
22
+ }
23
+ defineNode({
24
+ type: 'tex_crop', category: 'texture', packed: 'keep', usesNodeName: NAMED_BY_NODE,
25
+ summary: 'Extract an exact pixel rectangle, optionally resize it; all image layers stay aligned.',
26
+ description: 'Origin is [x,y] from the top left. Size 0 on an axis means the remaining source extent; resolution 0 keeps the crop size. Outside pixels are zero, never wrapped. Filtered resize uses area averaging down and bilinear up; nearest preserves discrete masks. Values are not colour-converted. The result takes this node\'s name unless name is set; other geometry/images pass through.',
27
+ inputs: [{ name: 'image', desc: 'geometry carrying an image' }],
28
+ params: {
29
+ image: imageParam(), name: renameParam(),
30
+ origin: { type: 'ivec2', default: [0, 0], min: -1000000, max: 1000000, desc: 'crop origin in pixels, from the top left; negative origins add zero padding' },
31
+ size: { type: 'ivec2', default: [0, 0], min: 0, max: 8192, desc: 'crop width/height in pixels; 0 = source extent minus origin' },
32
+ resolution: { type: 'ivec2', default: [0, 0], min: 0, max: 8192, desc: 'output width/height; 0 = cropped size on that axis' },
33
+ filter: { type: 'enum', options: ['filtered', 'nearest'], default: 'filtered', desc: 'resampling filter (no resampling when the crop and output sizes match)' },
34
+ },
35
+ outputs: 'selected image replaced by its cropped/resized layers',
36
+ example: { nodes: { img: { type: 'tex_pattern', params: { resolution: [64, 32] } }, out: { type: 'tex_crop', in: ['img'], params: { origin: [8, 4], size: [32, 16] } } }, output: 'out' },
37
+ cook: (ctx) => {
38
+ const { p } = ctx, s = source(ctx, 0, p.image);
39
+ const [x, y] = p.origin, w = p.size[0] || s.img.width - x, h = p.size[1] || s.img.height - y;
40
+ const ow = p.resolution[0] || w, oh = p.resolution[1] || h;
41
+ checkSize(w, h, ctx.type);
42
+ checkSize(ow, oh, ctx.type);
43
+ const name = outName(ctx), g = s.g.clone();
44
+ const img = cropImage(s.img, x, y, w, h, ow, oh, p.filter === 'nearest', name);
45
+ g.volumes[s.index] = img;
46
+ g.volumes = g.volumes.filter((v) => v === img || v.kind !== 'image' || v.name !== name);
47
+ return g;
48
+ },
49
+ });
50
+ defineNode({
51
+ type: 'tex_dilate', category: 'texture', packed: 'keep', usesNodeName: NAMED_BY_NODE,
52
+ summary: 'Extend nearest valid image values into an invalid band, preserving opacity by default.',
53
+ description: 'Validity comes from RGBA alpha or an explicit, same-sized mask. Grey images need a mask input. Valid pixels and pixels beyond radius are untouched. Nearest-site ties prefer the topmost, then leftmost source. No wrapping or colour conversion. Other layers pass through; preserve_alpha keeps every original RGBA alpha value. Uses the same exact distance transform as wide bake padding. The result takes this node\'s name unless name is set.',
54
+ inputs: [{ name: 'image', desc: 'image to pad' }, { name: 'mask', desc: 'optional explicit validity mask (same dimensions)', optional: true }],
55
+ params: {
56
+ image: imageParam(), layer: layerParam(), name: renameParam(),
57
+ radius: { type: 'int', default: 8, min: 0, max: 8192, desc: 'maximum Euclidean distance in pixels from a valid source' },
58
+ mask_image: imageParam('input 1 (the mask)', []), mask_layer: layerParam(), mask_channel: channelParam('luminance'),
59
+ mask_threshold: { type: 'float', default: 0, desc: 'mask values strictly greater than this are valid' },
60
+ preserve_alpha: { type: 'bool', default: true, desc: 'keep original alpha at every RGBA pixel while padding RGB' },
61
+ },
62
+ outputs: 'selected image layer padded; original mask/alpha preserved',
63
+ example: { nodes: { img: { type: 'tex_shape', params: { resolution: 32, falloff: 0 } }, out: { type: 'tex_dilate', in: ['img', 'img'], params: { radius: 3 } } }, output: 'out' },
64
+ cook: (ctx) => {
65
+ const { p } = ctx, s = source(ctx, 0, p.image, p.layer);
66
+ let mask;
67
+ if (ctx.hasInput(1)) {
68
+ const m = source(ctx, 1, p.mask_image, p.mask_layer, 'mask_image');
69
+ if (m.img.width !== s.img.width || m.img.height !== s.img.height)
70
+ throw new NodeError('tex_dilate: mask dimensions must match the source image');
71
+ mask = channel(m.data, m.ch, p.mask_channel);
72
+ }
73
+ else {
74
+ if (s.ch !== 4)
75
+ throw new NodeError('tex_dilate: a grey image requires an explicit mask input');
76
+ mask = channel(s.data, s.ch, 'alpha');
77
+ }
78
+ return withLayer(s, dilateImage(s.data, s.ch, s.img.width, s.img.height, mask, p.mask_threshold, p.radius, p.preserve_alpha), outName(ctx));
79
+ },
80
+ });
81
+ defineNode({
82
+ type: 'trace_image', category: 'curve',
83
+ summary: 'Trace a thresholded image into closed XY contours, with holes and disconnected components.',
84
+ description: 'Traces pixel-cell boundaries (not a bounding rectangle). Foreground is 4-connected: diagonal contacts stay separate. Simplification is conservative, topology-preserving, and bounded by tolerance in pixels. min_area filters entire foreground components by pixel area, retaining their holes. The full canvas maps to [0,width] × [0,width*height/widthPixels] in XY, including transparent margins. After fill use uv_project {method:"planar",axis:"z",scale:[width,width*heightPixels/widthPixels]}; fill does not preserve contour attributes. More than 1,000,000 boundary edges fails with a hint.',
85
+ inputs: [{ name: 'image', desc: 'geometry carrying the image to trace' }],
86
+ params: {
87
+ image: imageParam(), layer: layerParam(), channel: channelParam(),
88
+ threshold: { type: 'float', default: 0.5, desc: 'values at least this threshold are foreground' },
89
+ tolerance: { type: 'float', default: 0.5, min: 0, max: 8192, desc: 'maximum contour simplification error in source pixels; 0 only removes collinear points' },
90
+ min_area: { type: 'float', default: 0, min: 0, max: MAX_PIXELS, desc: 'minimum connected foreground component area in pixels; 0 retains all components' },
91
+ width: { type: 'float', default: 1, min: 0.000001, desc: 'full image canvas width in metres; height follows image aspect' },
92
+ },
93
+ outputs: 'closed curves; point uv; prim class (component ID), contour_id and hole (0/1); detail image_size and image_width',
94
+ example: { nodes: { img: { type: 'tex_shape', params: { resolution: [64, 32], shape: 'disc', falloff: 0 } }, out: { type: 'trace_image', in: ['img'], params: { channel: 'luminance' } } }, output: 'out' },
95
+ cook: (ctx) => {
96
+ const { p } = ctx, s = source(ctx, 0, p.image, p.layer);
97
+ const loops = traceMask(channel(s.data, s.ch, p.channel), s.img.width, s.img.height, p.threshold, p.min_area, p.tolerance);
98
+ const b = new GeoBuilder(), scale = p.width / s.img.width;
99
+ for (const loop of loops) {
100
+ // Pixel-space winding is reversed by Y-up, so reverse the sequence as well.
101
+ const points = loop.points.slice().reverse().map(([x, y]) => b.addPoint(x * scale, (s.img.height - y) * scale, 0));
102
+ b.addPrim(points, true);
103
+ }
104
+ const g = b.build(), cls = g.prims.add('class', 'int', 1), hole = g.prims.add('hole', 'int', 1), contour = g.prims.add('contour_id', 'int', 1);
105
+ loops.forEach((l, i) => { cls.set(i, l.component); hole.set(i, l.hole ? 1 : 0); contour.set(i, i); });
106
+ const uv = g.points.add('uv', 'float', 3);
107
+ for (let i = 0; i < g.numPoints; i++)
108
+ uv.set(i, [g.P[i * 3] / p.width, g.P[i * 3 + 1] / (s.img.height * scale), 0]);
109
+ g.detail.add('image_size', 'int', 2).set(0, [s.img.width, s.img.height]);
110
+ g.detail.add('image_width', 'float', 1).set(0, p.width);
111
+ return g;
112
+ },
113
+ });
114
+ defineNode({
115
+ type: 'tex_pack', category: 'texture', usesNodeName: NAMED_BY_NODE,
116
+ summary: 'Pack named images into aligned atlases and output per-item UV placement attributes.',
117
+ description: 'items is [{name:"leaf",maps:{color:"leaf_color",normal:"leaf_normal"}}]. Empty items packs each input image under the channel C. Every item must have the same map labels; images within an item must match dimensions and images within a channel must have matching channel counts. The selected images use their main layer. Native resolution, no rotation/downscaling, zero gutters. Outputs <name>_<channel> images and placement points in item order. rect is [x,y,width,height] in top-left pixels; atlasUV = localUV * uv_scale + uv_offset (V up). Connect the image output to texture_to_material and read placement attributes with a wrangle; do not merge placement points into your mesh. Padding is separate: tex_dilate. Limits: 4096 items, normal per-image pixel limit, at most 1 GiB of output image layers.',
118
+ inputs: [{ name: 'images', desc: 'geometry carrying named source images (combine with merge)' }],
119
+ params: {
120
+ items: { type: 'json', default: [], desc: 'array of {name, maps:{channel:imageName}}; empty = each image becomes one item in channel C' },
121
+ resolution: resolutionParam(2048),
122
+ padding: { type: 'int', default: 8, min: 0, max: 8192, desc: 'empty gutter on every side of each item, in pixels' },
123
+ name: { type: 'string', default: '', desc: 'atlas image name prefix ("" = this node\'s name); images are named <name>_<channel>' },
124
+ },
125
+ outputs: 'atlas images; points with name, rect, uv_offset and uv_scale; detail atlas_size',
126
+ example: { nodes: { a: { type: 'tex_shape', params: { resolution: 32, name: 'disc' } }, b: { type: 'tex_pattern', params: { resolution: [32, 16], name: 'pattern' } }, images: { type: 'merge', in: ['a', 'b'] }, out: { type: 'tex_pack', in: ['images'], params: { resolution: 128, padding: 4 } } }, output: 'out' },
127
+ cook: (ctx) => {
128
+ const { input, p } = ctx;
129
+ const images = imagesOf(input(0)), pool = new Map();
130
+ for (const im of images) {
131
+ if (pool.has(im.name))
132
+ throw new NodeError('tex_pack: duplicate input image name "' + im.name + '"');
133
+ pool.set(im.name, im);
134
+ }
135
+ if (!Array.isArray(p.items))
136
+ throw new NodeError('tex_pack: items must be an array of {name,maps}');
137
+ const items = p.items.length ? p.items : images.map((im) => ({ name: im.name, maps: { C: im.name } }));
138
+ if (!items.length || items.length > 4096)
139
+ throw new NodeError('tex_pack: needs 1..4096 items');
140
+ const prefix = outName(ctx);
141
+ const names = new Set();
142
+ let labels = [];
143
+ const sources = items.map((item, i) => {
144
+ if (!item || typeof item.name !== 'string' || !item.name.trim() || names.has(item.name))
145
+ throw new NodeError('tex_pack: item names must be non-empty and unique');
146
+ names.add(item.name);
147
+ if (!item.maps || typeof item.maps !== 'object' || Array.isArray(item.maps))
148
+ throw new NodeError('tex_pack: item "' + item.name + '" needs a maps object');
149
+ const keys = Object.keys(item.maps).sort();
150
+ if (!keys.length || keys.some((k) => !k.trim()))
151
+ throw new NodeError('tex_pack: map labels must not be empty');
152
+ if (i === 0)
153
+ labels = keys;
154
+ else if (JSON.stringify(keys) !== JSON.stringify(labels))
155
+ throw new NodeError('tex_pack: items must have matching map labels');
156
+ const maps = keys.map((key) => {
157
+ const ref = item.maps[key], img = typeof ref === 'string' ? pool.get(ref) : null;
158
+ if (!img)
159
+ throw new NodeError('tex_pack: missing image "' + ref + '" for ' + item.name + '.' + key);
160
+ if (!img.channels(img.mainLayer))
161
+ throw new NodeError('tex_pack: image "' + ref + '" has no valid main layer');
162
+ return img;
163
+ });
164
+ if (maps.some((im) => im.width !== maps[0].width || im.height !== maps[0].height))
165
+ throw new NodeError('tex_pack: map dimensions must match within item "' + item.name + '"');
166
+ return maps;
167
+ });
168
+ const [w, h] = p.resolution;
169
+ checkSize(w, h, 'tex_pack');
170
+ const channels = sources[0].map((im) => im.channels(im.mainLayer));
171
+ for (const maps of sources)
172
+ if (maps.some((im, i) => im.channels(im.mainLayer) !== channels[i]))
173
+ throw new NodeError('tex_pack: channel counts must match for each map label');
174
+ if (w * h * channels.reduce((a, b) => a + b, 0) > MAX_PIXELS * 16)
175
+ throw new NodeError('tex_pack: output layers exceed 1 GiB; reduce resolution or channel count');
176
+ const rects = sources.map((maps, id) => ({ id, w: maps[0].width + p.padding * 2, h: maps[0].height + p.padding * 2 }));
177
+ rects.sort((a, b) => Math.max(b.w, b.h) - Math.max(a.w, a.h) || b.w * b.h - a.w * a.h || a.id - b.id);
178
+ const places = skylinePack(rects, w, 1, false, h);
179
+ if (!places)
180
+ throw new NodeError('tex_pack: items and gutters do not fit ' + w + ' × ' + h + '; increase resolution, reduce padding, or resize inputs with tex_crop');
181
+ const g = new Geometry({ positions: items.flatMap(() => [0, 0, 0]) });
182
+ const name = g.points.add('name', 'string', 1), rect = g.points.add('rect', 'int', 4);
183
+ const offset = g.points.add('uv_offset', 'float', 2), scale = g.points.add('uv_scale', 'float', 2);
184
+ const atlases = labels.map((label, i) => new Image(w, h, prefix + '_' + label).set('C', new Float32Array(w * h * channels[i])));
185
+ items.forEach((item, i) => {
186
+ const x = places[i].x + p.padding, y = places[i].y + p.padding, iw = sources[i][0].width, ih = sources[i][0].height;
187
+ name.set(i, item.name);
188
+ rect.set(i, [x, y, iw, ih]);
189
+ offset.set(i, [x / w, 1 - (y + ih) / h]);
190
+ scale.set(i, [iw / w, ih / h]);
191
+ g.P[i * 3] = (x + iw / 2) / w;
192
+ g.P[i * 3 + 1] = 1 - (y + ih / 2) / h;
193
+ sources[i].forEach((im, c) => {
194
+ const ch = channels[c], data = im.layer(im.mainLayer), dest = atlases[c].layer('C');
195
+ for (let row = 0; row < ih; row++)
196
+ dest.set(data.subarray(row * iw * ch, (row + 1) * iw * ch), ((y + row) * w + x) * ch);
197
+ });
198
+ });
199
+ g.volumes = atlases;
200
+ g.detail.add('atlas_size', 'int', 2).set(0, [w, h]);
201
+ return g;
202
+ },
203
+ });
@@ -25,7 +25,11 @@ import './uv.ts';
25
25
  import './measure.ts';
26
26
  import './pcg.ts';
27
27
  import './texture.ts';
28
+ import './imageops.ts';
28
29
  import './bake.ts';
29
30
  import './particles.ts';
30
31
  import './rbd.ts';
31
32
  import './cloth.ts';
33
+ import './scene.ts';
34
+ import './solidify.ts';
35
+ import './beam.ts';
@@ -26,7 +26,11 @@ import './uv.js';
26
26
  import './measure.js';
27
27
  import './pcg.js';
28
28
  import './texture.js';
29
+ import './imageops.js';
29
30
  import './bake.js';
30
31
  import './particles.js';
31
32
  import './rbd.js';
32
33
  import './cloth.js';
34
+ import './scene.js';
35
+ import './solidify.js';
36
+ import './beam.js';
@@ -2,29 +2,41 @@
2
2
  // (see src/core/materials.ts). Exporters write them as glTF materials.
3
3
  import { defineNode } from '../graph/registry.js';
4
4
  import { NodeError } from '../graph/types.js';
5
+ import { Geometry, sameImage } from '../core/geometry.js';
6
+ import { referenceableImages } from '../core/image.js';
5
7
  import { MATERIAL_ATTRIB, normalizeMaterial, readMaterials, writeMaterials } from '../core/materials.js';
6
8
  import { P, mask } from './util.js';
7
9
  defineNode({
8
10
  type: 'material',
9
11
  category: 'attribute',
10
12
  packed: 'keep',
11
- summary: 'Assign a named material (PBR base colour, metallic, roughness, emissive, alpha) to prims; exporters write it as a glTF material.',
13
+ summary: 'Assign a named material (PBR base colour, metallic, roughness, emissive, alpha) to prims, or one from a material output; exporters write it as a glTF material.',
12
14
  description: 'Writes the prim string attribute "material" for the selected prims and adds (or replaces) the entry in the detail ' +
13
- 'material table "materials" (JSON). Vertex colours (Cd) still win in exports: a material then supplies the PBR scalars. ' +
14
- 'Assign several materials by chaining material nodes with different groups. Texture maps are file paths (PNG or ' +
15
- 'JPEG, relative to the graph/workspace): glb/gltf embed them, usda references them through UsdUVTexture shaders, ' +
16
- 'geo and json keep the paths in the table. A map replaces its scalar (base_color, roughness) in exports.',
15
+ 'material table "materials" (JSON). In glTF export the material decides the colour of its prims and their Cd is not ' +
16
+ 'written (export option vertex_colors keeps it). Assign several materials by chaining material nodes with different ' +
17
+ 'groups: by name pattern "@name=Glass*", prim ranges "0-11", or node groups (help topic "materials"). Texture maps are file paths (PNG or ' +
18
+ 'JPEG, relative to the package folder): glb/gltf embed them, usda references them through UsdUVTexture shaders, ' +
19
+ 'geo and json keep the paths in the table. A map replaces its scalar (base_color, roughness) in exports. ' +
20
+ 'Input 1 takes the material from elsewhere, typically a material output of a package ({"type": "owner/materials/steel"}): ' +
21
+ 'its entry and the maps it uses are copied in (from names it when the source holds several) and the colour and map ' +
22
+ 'params here are not used. With nothing in input 0 the result is the material alone: a material output.',
17
23
  aliases: ['material_assign', 'shop', 'assign_material', 'materialassign'],
18
- inputs: [{ name: 'geo', desc: 'geometry' }],
19
- outputs: 'prim "material" (string), detail "materials" (JSON table)',
24
+ inputs: [
25
+ { name: 'geo', desc: 'geometry (none: the material alone, for a material output)', optional: true },
26
+ { name: 'source', desc: 'a material output, or any geometry carrying materials, to take the material from', optional: true },
27
+ ],
28
+ outputs: 'prim "material" (string), detail "materials" (JSON table); with a source, the images its maps use',
20
29
  params: {
21
- name: { type: 'string', default: 'material', desc: 'material name (also the glTF material name)', aliases: ['shop_materialpath', 'material', 'path', 'materialpath'] },
30
+ name: { type: 'string', default: '', desc: 'material name, also the glTF material name ("" = "material", or the source material\'s own name with input 1)', aliases: ['shop_materialpath', 'material', 'path', 'materialpath'] },
31
+ from: { type: 'string', default: '', desc: 'input 1: which of its materials ("" = its only one)', aliases: ['source_material', 'use'] },
22
32
  group: P.group('prim', 'prims to assign ("" = all). e.g. "top", "@P.y>0", "0-9"'),
23
33
  base_color: { type: 'color', default: [0.8, 0.8, 0.8], desc: 'base colour [r,g,b] 0..1, "#rrggbb" or a name', aliases: ['basecolor', 'color', 'cd', 'albedo', 'diffuse'] },
24
34
  metallic: { type: 'float', default: 0, min: 0, max: 1, desc: 'metalness 0..1', aliases: ['metal', 'metalness'] },
25
35
  roughness: { type: 'float', default: 0.5, min: 0, max: 1, desc: 'roughness 0..1', aliases: ['rough'] },
26
36
  emissive: { type: 'color', default: [0, 0, 0], desc: 'emitted colour; components above 1 export with KHR_materials_emissive_strength', aliases: ['emission', 'emit'] },
27
37
  alpha: { type: 'float', default: 1, min: 0, max: 1, desc: 'opacity; below 1 exports with alphaMode BLEND', aliases: ['opacity', 'opac'] },
38
+ alpha_mode: { type: 'enum', options: ['auto', 'opaque', 'mask', 'blend'], default: 'auto', desc: 'auto preserves legacy scalar/vertex opacity; mask cuts out pixels below alpha_cutoff; explicit modes override auto' },
39
+ alpha_cutoff: { type: 'float', default: 0.5, min: 0, max: 1, desc: 'mask: discard where material alpha × texture alpha × vertex Alpha is below this value' },
28
40
  double_sided: { type: 'bool', default: false, desc: 'render both faces', aliases: ['doublesided', 'two_sided'] },
29
41
  unlit: { type: 'bool', default: false, desc: 'unlit shading (KHR_materials_unlit)', aliases: ['emissive_only', 'flat'] },
30
42
  base_color_map: { type: 'path', default: '', desc: 'base colour texture (sRGB PNG/JPEG path, or "image:<name>" for an image the geometry carries; "" = none); uses the uv attribute', aliases: ['basecolor_map', 'albedo_map', 'diffuse_map', 'color_map', 'basecolor_texture', 'base_color_texture'] },
@@ -32,22 +44,78 @@ defineNode({
32
44
  roughness_map: { type: 'path', default: '', desc: 'roughness texture (grey PNG/JPEG path or "image:<name>"; "" = none); glTF reads its green channel', aliases: ['roughness_texture', 'rough_map'] },
33
45
  },
34
46
  example: { type: 'material', params: { name: 'brick', base_color: '#a5462e', roughness: 0.9, group: '@P.y<0.5' } },
35
- cook: ({ input, p }) => {
36
- const name = String(p.name ?? '').trim();
37
- if (!name)
38
- throw new NodeError('material name is empty');
39
- const g = input(0).clone();
40
- const sel = mask(g, 'prim', p.group);
41
- const a = g.prims.add(MATERIAL_ATTRIB, 'string', 1);
42
- for (let i = 0; i < g.numPrims; i++)
43
- if (!sel || sel[i])
44
- a.set(i, name);
47
+ cook: ({ input, hasInput, p }) => {
48
+ const g = hasInput(0) ? input(0).clone() : new Geometry();
49
+ let name = String(p.name ?? '').trim();
50
+ let entry;
51
+ let images = [];
52
+ if (hasInput(1)) {
53
+ const src = input(1), table = readMaterials(src), names = Object.keys(table);
54
+ const want = String(p.from ?? '').trim();
55
+ if (!names.length)
56
+ throw new NodeError('input 1 carries no material', 'wire a material output (kind material) or any geometry that has materials into input 1');
57
+ if (want && !table[want])
58
+ throw new NodeError(`input 1 has no material "${want}"`, `its materials: ${names.join(', ')}`);
59
+ if (!want && names.length > 1)
60
+ throw new NodeError(`input 1 holds ${names.length} materials: say which with from`, `its materials: ${names.join(', ')}`);
61
+ const from = want || names[0];
62
+ entry = normalizeMaterial(table[from]);
63
+ if (!name)
64
+ name = from;
65
+ // the maps it uses travel with it
66
+ const pool = referenceableImages(src);
67
+ for (const ref of Object.values(entry.textures ?? {})) {
68
+ if (!ref?.startsWith('image:'))
69
+ continue;
70
+ const im = pool.get(ref.slice(6));
71
+ if (!im)
72
+ throw new NodeError(`input 1: material "${from}" uses image "${ref.slice(6)}", which it does not carry`);
73
+ images.push(im);
74
+ }
75
+ }
76
+ else {
77
+ if (!name)
78
+ name = 'material';
79
+ entry = normalizeMaterial({
80
+ baseColor: p.base_color, metallic: p.metallic, roughness: p.roughness, emissive: p.emissive,
81
+ alpha: p.alpha, doubleSided: !!p.double_sided, unlit: !!p.unlit,
82
+ alphaMode: p.alpha_mode, alphaCutoff: p.alpha_cutoff,
83
+ textures: { baseColor: p.base_color_map, normal: p.normal_map, roughness: p.roughness_map },
84
+ });
85
+ }
86
+ // copied maps join the target's images; one that differs from a target image of the same name is renamed
87
+ // "<material>_<map>" (as Geometry.merge does), and the entry follows
88
+ const have = referenceableImages(g);
89
+ const textures = { ...(entry.textures ?? {}) };
90
+ for (const im of images) {
91
+ const old = have.get(im.name);
92
+ if (old && sameImage(old, im))
93
+ continue;
94
+ let copy = im;
95
+ if (old) {
96
+ let n = `${name}_${im.name}`, k = 2;
97
+ while (have.has(n))
98
+ n = `${name}_${im.name}_${k++}`;
99
+ copy = im.clone();
100
+ copy.name = n;
101
+ for (const [slot, ref] of Object.entries(textures))
102
+ if (ref === `image:${im.name}`)
103
+ textures[slot] = `image:${n}`;
104
+ }
105
+ g.volumes.push(copy);
106
+ have.set(copy.name, copy);
107
+ }
108
+ if (images.length)
109
+ entry = { ...entry, textures: textures };
110
+ if (g.numPrims) {
111
+ const sel = mask(g, 'prim', p.group);
112
+ const a = g.prims.add(MATERIAL_ATTRIB, 'string', 1);
113
+ for (let i = 0; i < g.numPrims; i++)
114
+ if (!sel || sel[i])
115
+ a.set(i, name);
116
+ }
45
117
  const table = readMaterials(g);
46
- table[name] = normalizeMaterial({
47
- baseColor: p.base_color, metallic: p.metallic, roughness: p.roughness, emissive: p.emissive,
48
- alpha: p.alpha, doubleSided: !!p.double_sided, unlit: !!p.unlit,
49
- textures: { baseColor: p.base_color_map, normal: p.normal_map, roughness: p.roughness_map },
50
- });
118
+ table[name] = entry;
51
119
  writeMaterials(g, table);
52
120
  return g;
53
121
  },
@@ -5,8 +5,10 @@ import { Geometry } from '../core/geometry.js';
5
5
  import { defineNode } from '../graph/registry.js';
6
6
  import { NodeError } from '../graph/types.js';
7
7
  import { evalExpr, vecOut } from '../graph/params.js';
8
+ import { codeVarNames, pickVars } from '../core/usercode.js';
8
9
  import { pointNormals, primArea } from '../core/topology.js';
9
10
  import { halfEdges } from '../core/halfedge.js';
11
+ import { edgeWhere, pointWhere, primWhere } from '../core/report.js';
10
12
  import { CURVATURE_TYPES, RayScene, SurfaceQuery, bboxDiagonal, fmt, curvatureOfType, discreteCurvature, duplicatePoints, fillFromNearestValid, newNearest, nonManifoldPoints, percentileFit, pieceReport, rayMeasure, selfIntersections, shortEdges, smoothPointValues, } from '../core/analysis.js';
11
13
  import { P, getPointNormals, mask } from './util.js';
12
14
  import { andThen } from '../graph/parallel.js';
@@ -294,7 +296,7 @@ export function assertScope(g, pr) {
294
296
  closed: pr.pieces.length > 0 && pr.pieces.every((x) => x.closed), boundary_edges: sum((x) => x.boundaryEdges),
295
297
  };
296
298
  }
297
- const EXPR_NAMES = 'npoints nprims nvertices npolys nlines bbox (.min .max .size .center, each with .x .y .z) volume area pieces open_pieces genus closed boundary_edges';
299
+ const EXPR_NAMES = 'npoints nprims nvertices npolys nlines bbox (.min .max .size .center, each with .x .y .z) volume area pieces open_pieces genus closed boundary_edges and the graph vars (by their bare name; the names above come first)';
298
300
  defineNode({
299
301
  type: 'assert',
300
302
  category: 'measure',
@@ -323,6 +325,7 @@ defineNode({
323
325
  min_edge_length: { type: 'float', default: 0, min: 0, desc: 'no edge shorter than this (0 = off)' },
324
326
  no_degenerate: { type: 'bool', default: false, desc: 'no zero-area polygons (area <= tolerance²) and no two points within tolerance of each other' },
325
327
  no_self_intersections: { type: 'bool', default: false, desc: 'no two non-adjacent triangles cross each other (BVH search, capped at max_tests)', aliases: ['no_intersections'] },
328
+ strict_intersections: { type: 'bool', default: false, desc: 'no_self_intersections also fails on touching contacts, coplanar overlaps and triangles folding through a shared corner or onto a shared edge', aliases: ['strict'] },
326
329
  max_tests: { type: 'int', default: 2000000, min: 1000, max: 1000000000, desc: 'self-intersections: candidate triangle pairs to test before stopping (the message says when it stopped)', advanced: true },
327
330
  attrib: { type: 'string', default: '', desc: 'attribute that must exist ("" = off)', aliases: ['attribute'] },
328
331
  attrib_class: { type: 'enum', options: ['auto', 'point', 'vertex', 'prim', 'detail'], default: 'auto', desc: 'where attrib must live (auto = any class: vertex, point, prim, detail)' },
@@ -333,6 +336,7 @@ defineNode({
333
336
  tolerance: { type: 'float', default: 1e-6, min: 0, desc: 'distance tolerance for bbox_min/max and duplicate points', advanced: true },
334
337
  },
335
338
  outputs: 'passes geometry through; mark: detail int assert_failed, detail string assert_report, point/prim group assert_fail',
339
+ usesVars: (p) => String(p.expr ?? ''),
336
340
  example: {
337
341
  nodes: {
338
342
  body: { type: 'box', params: { size: [1, 2, 1], center: [0, 1, 0] } },
@@ -340,7 +344,7 @@ defineNode({
340
344
  },
341
345
  output: 'check',
342
346
  },
343
- cook: ({ input, p, warn, stat, engine }) => {
347
+ cook: ({ input, p, warn, stat, engine, vars }) => {
344
348
  const src = input(0);
345
349
  const g = src;
346
350
  const fails = [];
@@ -349,6 +353,9 @@ defineNode({
349
353
  let prCache = null;
350
354
  const pieces = () => prCache ?? (prCache = pieceReport(g));
351
355
  const fail = (name, msg) => fails.push(`${name}: ${msg}`);
356
+ /** the first prim / point set in a mask, in words: its part and position (core/report.ts) */
357
+ const firstPrimOf = (m) => { const q = m.indexOf(1); return q >= 0 ? `; first ${primWhere(g, q)}` : ''; };
358
+ const firstPointOf = (m) => { const q = m.indexOf(1); return q >= 0 ? `; first ${pointWhere(g, q)}` : ''; };
352
359
  const tol = p.tolerance;
353
360
  if (p.watertight) {
354
361
  checks++;
@@ -367,32 +374,40 @@ defineNode({
367
374
  bits.push(`${nme} edges shared by 3+ polygons`);
368
375
  if (lines)
369
376
  bits.push(`${lines} polylines`);
370
- fail('watertight', `${bits.join(', ')}; ${open} of ${pr.pieces.length} piece(s) open`);
371
377
  const he = halfEdges(g);
378
+ let firstEdge = -1;
372
379
  for (let e = 0; e < he.numEdges; e++)
373
- if (he.edgeValence(e) !== 2)
380
+ if (he.edgeValence(e) !== 2) {
381
+ if (firstEdge < 0)
382
+ firstEdge = e;
374
383
  for (const f of he.edgeFaces(e))
375
384
  primFail[f] = 1;
385
+ }
376
386
  for (let q = 0; q < g.numPrims; q++)
377
387
  if (!g.primClosed[q])
378
388
  primFail[q] = 1;
389
+ const where = firstEdge >= 0 ? `; first ${edgeWhere(g, he.edgeA[firstEdge], he.edgeB[firstEdge], he.edgeFaces(firstEdge)[0] ?? -1)}` : firstPrimOf(primFail);
390
+ fail('watertight', `${bits.join(', ')}; ${open} of ${pr.pieces.length} piece(s) open${where}`);
379
391
  }
380
392
  }
381
393
  if (p.manifold) {
382
394
  checks++;
383
395
  const he = halfEdges(g);
384
- let multi = 0;
396
+ let multi = 0, firstMulti = -1;
385
397
  for (let e = 0; e < he.numEdges; e++)
386
398
  if (he.edgeValence(e) > 2) {
387
399
  multi++;
400
+ if (firstMulti < 0)
401
+ firstMulti = e;
388
402
  for (const f of he.edgeFaces(e))
389
403
  primFail[f] = 1;
390
404
  }
391
405
  const bow = nonManifoldPoints(g);
392
406
  for (const q of bow)
393
407
  ptFail[q] = 1;
408
+ const where = firstMulti >= 0 ? `; first ${edgeWhere(g, he.edgeA[firstMulti], he.edgeB[firstMulti], he.edgeFaces(firstMulti)[0] ?? -1)}` : bow.length ? `; first ${pointWhere(g, bow[0])}` : '';
394
409
  if (multi || bow.length)
395
- fail('manifold', `${multi} edges shared by 3+ polygons, ${bow.length} bowtie point(s)`);
410
+ fail('manifold', `${multi} edges shared by 3+ polygons, ${bow.length} bowtie point(s)${where}`);
396
411
  }
397
412
  if (p.no_flipped) {
398
413
  checks++;
@@ -404,12 +419,15 @@ defineNode({
404
419
  bits.push(`${pr.flippedEdges} edges between oppositely wound polygons`);
405
420
  if (inward.length)
406
421
  bits.push(`${inward.length} closed piece(s) facing inward (volume ${inward.slice(0, 3).map(({ x }) => fmt(x.volume)).join(', ')}${inward.length > 3 ? ', …' : ''}; use reverse)`);
407
- fail('no_flipped', bits.join('; '));
422
+ const mark = new Uint8Array(g.numPrims);
408
423
  for (let q = 0; q < g.numPrims; q++) {
409
424
  const pc = pr.primPiece[q] >= 0 ? pr.pieces[pr.primPiece[q]] : null;
410
- if (pr.flippedPrims[q] || (pc && pc.closed && pc.volume < 0 && !pc.cavity))
425
+ if (pr.flippedPrims[q] || (pc && pc.closed && pc.volume < 0 && !pc.cavity)) {
411
426
  primFail[q] = 1;
427
+ mark[q] = 1;
428
+ }
412
429
  }
430
+ fail('no_flipped', bits.join('; ') + firstPrimOf(mark));
413
431
  }
414
432
  }
415
433
  const count = (label, have, lim, atLeast) => {
@@ -427,7 +445,7 @@ defineNode({
427
445
  if (bmin || bmax) {
428
446
  checks++;
429
447
  const P = g.P;
430
- let outside = 0;
448
+ let outside = 0, firstOut = -1;
431
449
  for (let i = 0; i < g.numPoints; i++) {
432
450
  let out = false;
433
451
  for (let c = 0; c < 3; c++) {
@@ -438,18 +456,20 @@ defineNode({
438
456
  if (out) {
439
457
  outside++;
440
458
  ptFail[i] = 1;
459
+ if (firstOut < 0)
460
+ firstOut = i;
441
461
  }
442
462
  }
443
463
  if (outside) {
444
464
  const b = g.bbox();
445
- fail('bbox', `${outside} point(s) outside${bmin ? ` min ${v3(bmin)}` : ''}${bmax ? ` max ${v3(bmax)}` : ''}; geometry spans ${v3(b.min)} .. ${v3(b.max)}`);
465
+ fail('bbox', `${outside} point(s) outside${bmin ? ` min ${v3(bmin)}` : ''}${bmax ? ` max ${v3(bmax)}` : ''}; geometry spans ${v3(b.min)} .. ${v3(b.max)}; first ${pointWhere(g, firstOut)}`);
446
466
  }
447
467
  }
448
468
  if (p.min_edge_length > 0) {
449
469
  checks++;
450
470
  const r = shortEdges(g, p.min_edge_length);
451
471
  if (r.count) {
452
- fail('min_edge_length', `${r.count} edge(s) shorter than ${fmt(p.min_edge_length)} (shortest ${fmt(r.shortest)})`);
472
+ fail('min_edge_length', `${r.count} edge(s) shorter than ${fmt(p.min_edge_length)} (shortest ${fmt(r.shortest)})${firstPrimOf(r.prims)}`);
453
473
  for (let q = 0; q < g.numPrims; q++)
454
474
  if (r.prims[q])
455
475
  primFail[q] = 1;
@@ -457,7 +477,7 @@ defineNode({
457
477
  }
458
478
  if (p.no_degenerate) {
459
479
  checks++;
460
- let zero = 0;
480
+ let zero = 0, firstZero = -1;
461
481
  const amin = tol * tol;
462
482
  for (let q = 0; q < g.numPrims; q++) {
463
483
  if (!g.primClosed[q])
@@ -465,21 +485,24 @@ defineNode({
465
485
  if (g.primSize(q) < 3 || primArea(g, q) <= amin) {
466
486
  zero++;
467
487
  primFail[q] = 1;
488
+ if (firstZero < 0)
489
+ firstZero = q;
468
490
  }
469
491
  }
470
492
  const dup = duplicatePoints(g, tol);
471
493
  for (let i = 0; i < g.numPoints; i++)
472
494
  if (dup.mask[i])
473
495
  ptFail[i] = 1;
496
+ const where = firstZero >= 0 ? `; first ${primWhere(g, firstZero)}` : firstPointOf(dup.mask);
474
497
  if (zero || dup.count)
475
- fail('no_degenerate', `${zero} zero-area polygon(s), ${dup.count} point(s) within ${fmt(tol)} of another${dup.count ? ' (fuse them)' : ''}`);
498
+ fail('no_degenerate', `${zero} zero-area polygon(s), ${dup.count} point(s) within ${fmt(tol)} of another${dup.count ? ' (fuse them)' : ''}${where}`);
476
499
  }
477
500
  if (p.no_self_intersections) {
478
501
  checks++;
479
- const r = selfIntersections(g, p.max_tests);
502
+ const r = selfIntersections(g, p.max_tests, { strict: p.strict_intersections });
480
503
  const capped = r.capped ? ` (search stopped after ${r.tested.toLocaleString('en-US')} candidate pairs: there may be more)` : '';
481
504
  if (r.pairs) {
482
- fail('no_self_intersections', `${r.pairs} pair(s) of crossing triangles${capped}`);
505
+ fail('no_self_intersections', `${r.pairs} pair(s) of ${p.strict_intersections ? 'intersecting or touching' : 'crossing'} triangles${capped}${firstPrimOf(r.prims)}`);
483
506
  for (let q = 0; q < g.numPrims; q++)
484
507
  if (r.prims[q])
485
508
  primFail[q] = 1;
@@ -499,7 +522,7 @@ defineNode({
499
522
  fail('attrib', `"${p.attrib}" is a string attribute: attrib_min/max need numbers`);
500
523
  else {
501
524
  const a = f.attr, d = a.data, s = a.size, n = a.count;
502
- let bad = 0, mn = Infinity, mx = -Infinity;
525
+ let bad = 0, mn = Infinity, mx = -Infinity, firstBad = -1;
503
526
  const vp = f.cls === 'vertex' ? g.vertexPrims() : null;
504
527
  for (let i = 0; i < n; i++) {
505
528
  const x = d[i * s];
@@ -509,6 +532,8 @@ defineNode({
509
532
  mx = x;
510
533
  if ((lo !== null && !(x >= lo)) || (hi !== null && !(x <= hi))) {
511
534
  bad++;
535
+ if (firstBad < 0)
536
+ firstBad = i;
512
537
  if (f.cls === 'point')
513
538
  ptFail[i] = 1;
514
539
  else if (f.cls === 'prim')
@@ -517,8 +542,9 @@ defineNode({
517
542
  primFail[vp[i]] = 1;
518
543
  }
519
544
  }
545
+ const where = firstBad < 0 || f.cls === 'detail' ? '' : `; first ${f.cls === 'point' ? pointWhere(g, firstBad) : primWhere(g, f.cls === 'prim' ? firstBad : vp[firstBad])}`;
520
546
  if (bad)
521
- fail('attrib', `${bad} ${f.cls} value(s) of "${p.attrib}"${s > 1 ? '[0]' : ''} outside ${lo !== null ? fmt(lo) : '-inf'} .. ${hi !== null ? fmt(hi) : 'inf'} (range ${fmt(mn)} .. ${fmt(mx)})`);
547
+ fail('attrib', `${bad} ${f.cls} value(s) of "${p.attrib}"${s > 1 ? '[0]' : ''} outside ${lo !== null ? fmt(lo) : '-inf'} .. ${hi !== null ? fmt(hi) : 'inf'} (range ${fmt(mn)} .. ${fmt(mx)})${where}`);
522
548
  }
523
549
  }
524
550
  }
@@ -546,7 +572,8 @@ defineNode({
546
572
  if (String(p.expr ?? '').trim()) {
547
573
  checks++;
548
574
  const src = String(p.expr).trim();
549
- const scope = assertScope(g, pieces());
575
+ // the measurements, over the graph vars the expression names
576
+ const scope = { ...pickVars(vars, codeVarNames(src, vars)), ...assertScope(g, pieces()) };
550
577
  let res;
551
578
  try {
552
579
  res = evalExpr(src, scope, { host: engine.host, timeoutMs: engine.scriptTimeoutMs });
@@ -243,6 +243,8 @@ defineNode({
243
243
  const perStep = Math.min(ep.maxBirths, Math.ceil(ep.rate) * prep.emitter.count);
244
244
  for (;;) {
245
245
  budget.check();
246
+ // a stopped cook stops between batches
247
+ await ctx.checkpoint();
246
248
  const { geo: st, end } = emitSteps(state, prep.emitter, s0, Math.min(s1, s0 + batchSteps(state ? state.numPoints : 0, perStep)), ep);
247
249
  batches++;
248
250
  state = await integrate(st, s0, end, prep);