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
@@ -3,9 +3,14 @@
3
3
  // a PNG, filters process one layer of one image of their first input and pass everything else through,
4
4
  // texture_to_material attaches images to a material ("image:<name>" texture slots), and exporters embed them (glTF) or
5
5
  // write them next to the file (USD, the "textures" format). Bakes from meshes live in nodes/bake.ts.
6
- import { Geometry } from '../core/geometry.js';
7
- import { Image, MAIN_LAYER, MAX_PIXELS, channelsOf, findImage, imagesOf, isImage, resizeLayer, toGrey } from '../core/image.js';
8
- import { BLEND_MODES, GRADIENTS, PATTERNS, SHAPES, WARP_MODES, blendLayers, blurLayer, colorize, curvesLayer, edgeDetect, genGradient, genPattern, genScratches, genShape, genSplatter, heightToAO, histogramScanFn, levelsFn, mapValues, normalFromHeight, rampLUT, tileSampler, transformLayer, warpLayer, } from '../core/texture.js';
6
+ // Names: every image a node makes or filters is named after that node unless its name param says otherwise, so the
7
+ // default names in a graph never collide. A node reading an input that holds several images needs to be told which
8
+ // one (its image param): it never picks the first silently.
9
+ import { Geometry, sameImage } from '../core/geometry.js';
10
+ import { Image, MAIN_LAYER, MAX_PIXELS, asImage, channelsOf, imagesOf, isImage, resizeLayer, toGrey } from '../core/image.js';
11
+ import { BLEND_MODES, GRADIENTS, GRUNGE_STYLES, NORMAL_BLEND_MODES, PATTERNS, QUANTIZE_MODES, SHAPES, SLOPE_BLUR_MODES, TILE_SAMPLER_OUTPUTS, WARP_MODES, blendLayers, blendNormals, blurLayer, colorize, curvatureFromNormal, curvesLayer, directionalBlur, edgeDetect, flipNormals, genGradient, genGrunge, coverageCut, genPattern, genScratches, genShape, genSplatter, heightAO, heightFromNormal, heightToAO, histogramRangeFn, histogramScanFn, histogramSelectFn, levelsFn, makeTile, mapValues, normalFromHeight, normalizeNormals, quantizeFn, rampLUT, slopeBlur, tileSampler, transformLayer, valueRange, warpLayer, } from '../core/texture.js';
12
+ import { BEVEL_PROFILES, EDGE_MODES, FLOOD_OUTPUTS, SDF_BOOLEANS, SDF_OPS, SDF_RENDER, SDF_SHAPES, bevelHeight, edgeBand, floodFill, profileFn, propagate, sdfBoolean, sdfOp, sdfShape, sdfToMask, shapeReach, signedDistance, } from '../core/texsdf.js';
13
+ import { texNoise } from '../core/texnoise.js';
9
14
  import { Heightfield, heightfieldsOf } from '../core/heightfield.js';
10
15
  import { MATERIAL_ATTRIB, normalizeMaterial, readMaterials, writeMaterials } from '../core/materials.js';
11
16
  import { readUV } from '../core/uv.js';
@@ -22,11 +27,36 @@ export const resolutionParam = (def = 512) => ({
22
27
  desc: `image size in pixels [width, height] (one number = square; at most ${MAX_PIXELS.toLocaleString('en-US')} pixels); powers of two suit GPUs`,
23
28
  aliases: ['res', 'output_size', 'dimensions', 'image_size'],
24
29
  });
25
- export const nameParam = (def, desc = 'image name (materials reference it as "image:<name>")') => ({ type: 'string', default: def, desc, aliases: ['image_name', 'output_name'] });
26
- const imageParam = () => ({ type: 'string', default: '', desc: 'which image of the input to process ("" = the first)', aliases: ['input_image', 'source_image'] });
30
+ /** The name of the image a node makes: "" = the node's own name (unique in its graph). */
31
+ export const nameParam = (desc = 'image name ("" = this node\'s name); materials reference it as "image:<name>"') => ({ type: 'string', default: '', desc, aliases: ['image_name', 'output_name'] });
32
+ /** Which image of an input to read: "" = its only image (an input holding several is an error that lists them). */
33
+ export const imageParam = (of = 'the input', aliases = ['input_image', 'source_image']) => ({ type: 'string', default: '', desc: `which image of ${of} to use ("" = its only image; needed when it holds several)`, aliases });
27
34
  const layerParam = () => ({ type: 'string', default: '', desc: 'layer to process ("" = the main layer "C"; others: "id", "mask", …)', aliases: ['plane', 'channel_layer'] });
28
- const renameParam = () => ({ type: 'string', default: '', desc: 'rename the result ("" = keep the input image name)', aliases: ['image_name', 'output_name'] });
35
+ /** A filter's result name: "" = the filter node's name (the processed image is renamed; one already so called is replaced). */
36
+ export const renameParam = () => nameParam('name of the result ("" = this node\'s name; an image already so called is replaced); materials reference it as "image:<name>"');
37
+ /** usesNodeName for nodes whose image takes the node's name when the name param is empty. */
38
+ export const NAMED_BY_NODE = (p) => !String(p.name ?? '').trim();
39
+ /** The name of the image a node outputs: its name param, else the node's own name. */
40
+ export const outName = (ctx) => String(ctx.p.name ?? '').trim() || ctx.node;
29
41
  const tileParam = (desc = 'the image tiles: filters read across the opposite border (keep a tileable texture tileable)') => ({ type: 'bool', default: true, desc, aliases: ['wrap', 'seamless'] });
42
+ /** Physical scale: the metres the image width covers, as in tex_normal_from_height (one texel is size / width metres). */
43
+ const sizeParam = () => ({ type: 'float', default: 1, min: 1e-6, desc: 'metres the image width covers on the model (one texel is size / width metres); the distances of this node are in metres', aliases: ['texture_size', 'world_size', 'tile_size'] });
44
+ const NORMAL_MAPS = 'normal maps are RGBA images (tex_normal_from_height, bake_normal, image_file of a normal map)';
45
+ /** A normal-map source: RGBA, or an error that says how to make one. */
46
+ function normalSource(ctx, s, what = 'input 0') {
47
+ if (s.ch !== 4)
48
+ throw new NodeError(`${ctx.type}: ${what} "${s.img.name}" is a grey image, not a normal map`, `${NORMAL_MAPS}; turn a height into one with tex_normal_from_height`);
49
+ return s;
50
+ }
51
+ /** Signed distance in metres (negative inside) of a grey source's mask at threshold. */
52
+ function maskSDF(s, threshold, size, wrap) {
53
+ const d = signedDistance(toGrey(s.data, s.ch), s.img.width, s.img.height, threshold, wrap), texel = size / s.img.width;
54
+ for (let k = 0; k < d.length; k++)
55
+ d[k] *= texel;
56
+ return d;
57
+ }
58
+ const SDF_INPUT = [{ name: 'sdf', desc: 'geometry holding an SDF image (signed distance in metres: tex_sdf_shape, tex_sdf_from_mask); everything else passes through' }];
59
+ const SDF_NOTE = 'An SDF image holds the signed distance in metres in C (negative inside, 0 on the outline), as tex_sdf_shape and tex_sdf_from_mask make it';
30
60
  export function checkSize(w, h, node) {
31
61
  if (!(w >= 1 && h >= 1))
32
62
  throw new NodeError(`${node}: image size must be at least 1 × 1 (got ${w} × ${h})`);
@@ -39,24 +69,37 @@ export function imageGeo(img) {
39
69
  g.volumes = [img];
40
70
  return g;
41
71
  }
42
- /** The image (by name, "" = first) and layer ("" = main) a node reads from input i. */
43
- export function source(ctx, i, imageName = '', layerName = '') {
72
+ /**
73
+ * The image (by name; "" = the input's only image) and layer ("" = main) a node reads from input i. `param` names the
74
+ * param that picks the image of this input, for the error when the input holds several and none is named ("" = the
75
+ * node has none: keep one image in that input).
76
+ */
77
+ export function source(ctx, i, imageName = '', layerName = '', param = 'image') {
44
78
  const g = ctx.input(i);
45
- let index = -1;
46
- for (let k = 0; k < g.volumes.length; k++) {
47
- const v = g.volumes[k];
48
- if (isImage(v) && (!imageName || v.name === imageName)) {
49
- index = k;
50
- break;
51
- }
52
- }
53
- if (index < 0) {
54
- const names = imagesOf(g).map((x) => x.name);
55
- if (imageName && names.length)
56
- throw new NodeError(`${ctx.type}: input ${i} has no image "${imageName}"`, `images: ${names.join(', ')}`);
79
+ const found = [];
80
+ for (let k = 0; k < g.volumes.length; k++)
81
+ if (isImage(g.volumes[k]))
82
+ found.push(k);
83
+ const nameOf = (k) => g.volumes[k].name;
84
+ const names = found.map(nameOf);
85
+ if (!found.length)
57
86
  throw new NodeError(`${ctx.type}: input ${i} has no image`, NO_IMAGE);
87
+ let index;
88
+ if (imageName) {
89
+ const hits = found.filter((k) => nameOf(k) === imageName);
90
+ if (!hits.length)
91
+ throw new NodeError(`${ctx.type}: input ${i} has no image "${imageName}"`, `images: ${names.join(', ')}`);
92
+ if (hits.length > 1)
93
+ throw new NodeError(`${ctx.type}: input ${i} holds ${hits.length} different images named "${imageName}"`, 'give them different names (an image takes the name of the node that made it unless its name param is set; tex_output renames one)');
94
+ index = hits[0];
95
+ }
96
+ else if (found.length > 1) {
97
+ const list = names.map((n) => `"${n}"`).join(', ');
98
+ throw new NodeError(`${ctx.type}: input ${i} holds ${found.length} images (${list}); it does not guess which one to use`, param ? `set ${param} to one of them, e.g. ${param}: "${names[0]}"` : `keep one image in input ${i}: tex_output {image: "${names[0]}", keep_only: true}`);
58
99
  }
59
- const img = findImage(g, g.volumes[index].name);
100
+ else
101
+ index = found[0];
102
+ const img = asImage(g.volumes[index]);
60
103
  const layer = layerName || img.mainLayer;
61
104
  const data = img.layer(layer);
62
105
  if (!data)
@@ -66,25 +109,27 @@ export function source(ctx, i, imageName = '', layerName = '') {
66
109
  throw new NodeError(`${ctx.type}: image "${img.name}" layer "${layer}" has ${data.length} values for ${img.width} × ${img.height} pixels`);
67
110
  return { g, img, index, layer, data, ch };
68
111
  }
69
- /** Input i's image layer resized to w × h (or null when the input is not connected). */
70
- function sourceAt(ctx, i, w, h, imageName = '', layerName = '', wrap = true) {
112
+ /** Input i's image layer resized to w × h (or null when the input is not connected); `param` as in source(). */
113
+ function sourceAt(ctx, i, w, h, imageName = '', layerName = '', wrap = true, param = '') {
71
114
  if (!ctx.hasInput(i))
72
115
  return null;
73
- const s = source(ctx, i, imageName, layerName);
116
+ const s = source(ctx, i, imageName, layerName, param);
74
117
  return { data: resizeLayer(s.data, s.ch, s.img.width, s.img.height, w, h, wrap), ch: s.ch };
75
118
  }
76
- /** The input geometry with the source image's layer replaced (and the image renamed when `rename` is set). */
77
- export function withLayer(s, data, rename = '', extra) {
119
+ /**
120
+ * The input geometry with the source image's layer replaced and the image named `name` (outName: the filter node's
121
+ * name by default); another image already called `name` is replaced by it.
122
+ */
123
+ export function withLayer(s, data, name, extra) {
78
124
  const g = s.g.clone();
79
125
  const img = s.img.clone();
80
126
  img.set(s.layer, data);
81
127
  if (extra)
82
128
  for (const [k, v] of Object.entries(extra))
83
129
  img.set(k, v);
84
- const name = String(rename ?? '').trim();
85
- if (name)
86
- img.name = name;
130
+ img.name = name;
87
131
  g.volumes[s.index] = img;
132
+ g.volumes = g.volumes.filter((v) => v === img || !(isImage(v) && v.name === name));
88
133
  return g;
89
134
  }
90
135
  export const size2 = (p, node) => {
@@ -92,7 +137,6 @@ export const size2 = (p, node) => {
92
137
  checkSize(w, h, node);
93
138
  return [w, h];
94
139
  };
95
- export const imgName = (p, def) => String(p.name ?? '').trim() || def;
96
140
  // ---------------------------------------------------------------- generators
97
141
  defineNode({
98
142
  type: 'tex_noise',
@@ -116,29 +160,34 @@ defineNode({
116
160
  offset: { type: 'vec2', default: [0, 0], desc: 'shift in cells (vary or animate without changing the seed)' },
117
161
  tileable: { type: 'bool', default: true, desc: 'repeat seamlessly at the image borders', aliases: ['tile', 'tiling', 'seamless'] },
118
162
  seed: P.seed(),
119
- name: nameParam('noise'),
163
+ name: nameParam(),
120
164
  },
121
- outputs: 'image <name>: C grey 0..1',
165
+ usesNodeName: NAMED_BY_NODE,
166
+ outputs: 'image <name> (default: the node name): C grey 0..1',
122
167
  example: { type: 'tex_noise', params: { resolution: 512, scale: 6, fractal: 'ridged', seed: 2 } },
123
- cook: ({ p, type, parallelMap }) => {
168
+ cook: (ctx) => {
169
+ const { p, type, parallelMap } = ctx;
124
170
  const [w, h] = size2(p, type);
125
171
  const job = {
126
172
  noise: p.noise, fractal: p.fractal, scale: p.scale, octaves: p.octaves, roughness: p.roughness, lacunarity: p.lacunarity,
127
173
  seed: p.seed, tileable: !!p.tileable, offset: [p.offset[0], p.offset[1]], aspect: h / w, jitter: p.jitter, width: w, height: h,
128
174
  };
129
175
  const C = new Float32Array(w * h);
130
- return andThen(parallelMap('tex_noise', { count: w * h, args: job, results: { C } }), () => imageGeo(new Image(w, h, imgName(p, 'noise')).set(MAIN_LAYER, C)));
176
+ return andThen(parallelMap('tex_noise', { count: w * h, args: job, results: { C } }), () => imageGeo(new Image(w, h, outName(ctx)).set(MAIN_LAYER, C)));
131
177
  },
132
178
  });
133
179
  defineNode({
134
180
  type: 'tex_pattern',
135
181
  category: 'texture',
136
- summary: 'Tiling pattern image: bricks, tiles, checker, stripes, hex, dots or grid lines, with gap (mortar), bevel and per-cell random id.',
137
- description: 'Substance: Tile Generator / Bricks / Checker; Houdini COP: Pattern. C is a height-like profile: 1 on the cells, 0 in ' +
138
- 'the gaps, a smooth bevel between (feed tex_normal_from_height for bricks with depth). Layer "id" holds a random 0..1 ' +
139
- 'per cell (tex_colorize it with layer "id" for per-brick colour). count = cells along u (columns) and v (rows); ' +
140
- 'bricks and dots shift every other row by offset (keep the row count even for seamless tiling); hex uses offset for ' +
141
- 'its staggered rows. gap and bevel are fractions of the smaller cell side; variation darkens cells randomly.',
182
+ summary: 'Tiling pattern image: bricks, tiles, checker, stripes, hex, dots, or a grid line mask, with gap (mortar), bevel and per-cell random id.',
183
+ description: 'Substance: Tile Generator / Bricks / Checker; Houdini COP: Pattern. For bricks, tiles, stripes, hex and dots C is ' +
184
+ 'a height-like profile: 1 on the cells, 0 in the gaps, a smooth bevel between (feed tex_normal_from_height for ' +
185
+ 'bricks with depth). grid is the opposite, a line mask: 1 on the lines (gap is their width), 0 inside the cells, so ' +
186
+ 'multiplying a material by it darkens all but the lines; for cells separated by grooves use tiles (grid is 1 - tiles ' +
187
+ 'without variation). checker alternates 1 and 0. Layer "id" holds a random 0..1 per cell (tex_colorize it with layer ' +
188
+ '"id" for per-brick colour). count = cells along u (columns) and v (rows); bricks and dots shift every other row by ' +
189
+ 'offset (keep the row count even for seamless tiling); hex uses offset for its staggered rows. gap and bevel are ' +
190
+ 'fractions of the smaller cell side; variation darkens cells randomly.',
142
191
  aliases: ['tile_generator', 'bricks', 'brick', 'checker', 'tiles_pattern', 'cop_pattern'],
143
192
  inputs: [],
144
193
  params: {
@@ -148,16 +197,18 @@ defineNode({
148
197
  offset: { type: 'float', default: 0.5, min: 0, max: 1, desc: 'bricks / hex / dots: shift of every other row (fraction of a cell)', aliases: ['row_offset', 'stagger'] },
149
198
  gap: { type: 'float', default: 0.06, min: 0, max: 1, desc: 'mortar / gap width as a fraction of the smaller cell side (dots: 1 - diameter)', aliases: ['mortar', 'spacing'] },
150
199
  bevel: { type: 'float', default: 0.08, min: 0, max: 1, desc: 'bevel width as a fraction of the smaller cell side (0 = hard antialiased edge)', aliases: ['smooth', 'roundness'] },
151
- variation: { type: 'float', default: 0, min: 0, max: 1, desc: 'random darkening per cell (0 = all cells 1)', aliases: ['height_variation', 'luminance_random'] },
200
+ variation: { type: 'float', default: 0, min: 0, max: 1, desc: 'random darkening per cell (0 = all cells 1; not grid or checker)', aliases: ['height_variation', 'luminance_random'] },
152
201
  seed: P.seed(),
153
- name: nameParam('pattern'),
202
+ name: nameParam(),
154
203
  },
155
- outputs: 'image <name>: C grey profile, id grey random per cell',
204
+ usesNodeName: NAMED_BY_NODE,
205
+ outputs: 'image <name> (default: the node name): C grey profile (1 on the cells; grid: 1 on the lines), id grey random per cell',
156
206
  example: { type: 'tex_pattern', params: { pattern: 'bricks', count: [4, 8], gap: 0.05, bevel: 0.1 } },
157
- cook: ({ p, type }) => {
207
+ cook: (ctx) => {
208
+ const { p, type } = ctx;
158
209
  const [w, h] = size2(p, type);
159
210
  const r = genPattern({ pattern: p.pattern, count: [p.count[0], p.count[1]], offset: p.offset, gap: p.gap, bevel: p.bevel, variation: p.variation, seed: p.seed }, w, h);
160
- return imageGeo(new Image(w, h, imgName(p, 'pattern')).set(MAIN_LAYER, r.C).set('id', r.id));
211
+ return imageGeo(new Image(w, h, outName(ctx)).set(MAIN_LAYER, r.C).set('id', r.id));
161
212
  },
162
213
  });
163
214
  defineNode({
@@ -173,13 +224,70 @@ defineNode({
173
224
  angle: { type: 'float', default: 0, desc: 'direction in degrees (linear, mirror) or start angle (angular)', aliases: ['rotation', 'direction'] },
174
225
  center: { type: 'vec2', default: [0.5, 0.5], desc: 'centre in uv (radial, diamond, angular)' },
175
226
  radius: { type: 'float', default: 0.5, min: 0.001, desc: 'radial / diamond: distance (uv) where the gradient reaches 1' },
176
- name: nameParam('gradient'),
227
+ name: nameParam(),
177
228
  },
178
- outputs: 'image <name>: C grey 0..1',
229
+ usesNodeName: NAMED_BY_NODE,
230
+ outputs: 'image <name> (default: the node name): C grey 0..1',
179
231
  example: { type: 'tex_gradient', params: { resolution: 256, mode: 'radial', radius: 0.5 } },
180
- cook: ({ p, type }) => {
232
+ cook: (ctx) => {
233
+ const { p, type } = ctx;
181
234
  const [w, h] = size2(p, type);
182
- return imageGeo(new Image(w, h, imgName(p, 'gradient')).set(MAIN_LAYER, genGradient(p.mode, p.angle, [p.center[0], p.center[1]], p.radius, w, h)));
235
+ return imageGeo(new Image(w, h, outName(ctx)).set(MAIN_LAYER, genGradient(p.mode, p.angle, [p.center[0], p.center[1]], p.radius, w, h)));
236
+ },
237
+ });
238
+ defineNode({
239
+ type: 'tex_constant',
240
+ category: 'texture',
241
+ summary: 'Constant image: one grey value or one RGBA colour everywhere, sized by resolution or by an input image.',
242
+ description: 'Substance: Uniform Color; Houdini COP: Constant. channels grey fills layer C with value (a flat roughness, ' +
243
+ 'metallic or height, a mask of 1); rgba with color (display values like every colour param: "#a5462e" comes out ' +
244
+ 'of the PNG as #a5462e) and alpha. With input 0 connected the image takes the size of an image there (image picks ' +
245
+ 'one when it holds several) and resolution is ignored; the output holds only the new image either way. Blend over ' +
246
+ 'it, pack it into an ORM channel, or give a material a flat map.',
247
+ aliases: ['constant_texture', 'uniform_color', 'solid_color', 'flat_color', 'fill_image', 'cop_constant'],
248
+ inputs: [{ name: 'size_from', desc: 'optional: an image whose size the constant takes', optional: true }],
249
+ params: {
250
+ resolution: resolutionParam(),
251
+ channels: { type: 'enum', options: ['grey', 'rgba'], default: 'grey', desc: 'grey = one value (value), rgba = a colour (color, alpha)', aliases: ['mode', 'type'] },
252
+ value: { type: 'float', default: 0.5, desc: 'grey: the value of every pixel', aliases: ['grey', 'level'] },
253
+ color: { type: 'color', default: [0.5, 0.5, 0.5], desc: 'rgba: the colour of every pixel', aliases: ['rgb', 'colour'] },
254
+ alpha: { type: 'float', default: 1, min: 0, max: 1, desc: 'rgba: the alpha of every pixel' },
255
+ image: imageParam('input 0 (the size source)'),
256
+ name: nameParam(),
257
+ },
258
+ usesNodeName: NAMED_BY_NODE,
259
+ outputs: 'image <name> (default: the node name): C grey or RGBA, one value everywhere',
260
+ example: {
261
+ nodes: {
262
+ noise: { type: 'tex_noise', params: { resolution: 128 } },
263
+ roughness: { type: 'tex_constant', in: ['noise'], params: { value: 0.65 } },
264
+ paint: { type: 'tex_constant', params: { resolution: 64, channels: 'rgba', color: '#a5462e' } },
265
+ out: { type: 'merge', in: ['roughness', 'paint'] },
266
+ },
267
+ output: 'out',
268
+ },
269
+ cook: (ctx) => {
270
+ const { p, type } = ctx;
271
+ let w, h;
272
+ if (ctx.hasInput(0)) {
273
+ const s = source(ctx, 0, p.image);
274
+ w = s.img.width;
275
+ h = s.img.height;
276
+ }
277
+ else
278
+ [w, h] = size2(p, type);
279
+ const rgba = p.channels === 'rgba';
280
+ const C = new Float32Array(w * h * (rgba ? 4 : 1));
281
+ if (!rgba)
282
+ C.fill(p.value);
283
+ else
284
+ for (let i = 0; i < C.length; i += 4) {
285
+ C[i] = p.color[0];
286
+ C[i + 1] = p.color[1];
287
+ C[i + 2] = p.color[2];
288
+ C[i + 3] = p.alpha;
289
+ }
290
+ return imageGeo(new Image(w, h, outName(ctx)).set(MAIN_LAYER, C));
183
291
  },
184
292
  });
185
293
  defineNode({
@@ -198,44 +306,48 @@ defineNode({
198
306
  rotation: { type: 'float', default: 0, desc: 'rotation in degrees (counter-clockwise)', aliases: ['angle', 'rotate'] },
199
307
  falloff: { type: 'float', default: 0, min: 0, max: 1, desc: 'soft edge as a fraction of the radius (0 = antialiased hard edge, 1 = a cone)', aliases: ['softness', 'blur'] },
200
308
  tile: { type: 'ivec2', default: [1, 1], min: 1, max: 512, desc: 'repeats along u and v', aliases: ['tiling', 'repeat', 'count'] },
201
- name: nameParam('shape'),
309
+ name: nameParam(),
202
310
  },
203
- outputs: 'image <name>: C grey 0..1',
311
+ usesNodeName: NAMED_BY_NODE,
312
+ outputs: 'image <name> (default: the node name): C grey 0..1',
204
313
  example: { type: 'tex_shape', params: { shape: 'star', sides: 5, falloff: 0.3, tile: [4, 4] } },
205
- cook: ({ p, type }) => {
314
+ cook: (ctx) => {
315
+ const { p, type } = ctx;
206
316
  const [w, h] = size2(p, type);
207
317
  const C = genShape({ shape: p.shape, size: p.size, sides: p.sides, inner: p.inner_radius, rotation: p.rotation, falloff: p.falloff, tile: [p.tile[0], p.tile[1]] }, w, h);
208
- return imageGeo(new Image(w, h, imgName(p, 'shape')).set(MAIN_LAYER, C));
318
+ return imageGeo(new Image(w, h, outName(ctx)).set(MAIN_LAYER, C));
209
319
  },
210
320
  });
211
321
  defineNode({
212
322
  type: 'tex_cells',
213
323
  category: 'texture',
214
324
  summary: 'Voronoi cells image: distance to the cell site, cell edges, random id per cell or crackle; tileable.',
215
- description: 'Substance: Cells / Voronoi / Crystal; Houdini COP: Worley Noise. Layer C holds the chosen output and layer "id" a random 0..1 per cell (per-cell colour or height). edges is 0 on the cell borders rising to 1 at edge_width (a fraction of a cell): stones, scales, cracked mud. crackle (F2 - F1) is bright along the borders. Runs in chunks on the worker pool for large images.',
325
+ description: 'Substance: Cells / Voronoi / Crystal; Houdini COP: Worley Noise. Layer C holds the chosen output and layer "id" a random 0..1 per cell (per-cell colour or height). edges is 0 on the cell borders rising to 1 at edge_width (a fraction of a cell): stones, scales, cracked mud. crackle (F2 - F1) is bright along the borders. crystal gives every cell a flat facet with a random tilt and level (Substance Crystal: shards, faceted stone, a per-facet roughness or normal). Runs in chunks on the worker pool for large images.',
216
326
  aliases: ['voronoi_texture', 'cells', 'worley', 'cellular', 'crystals', 'cop_worley'],
217
327
  inputs: [],
218
328
  params: {
219
329
  resolution: resolutionParam(),
220
- output: { type: 'enum', options: ['distance', 'edges', 'id', 'crackle'], default: 'edges', desc: 'what C holds', aliases: ['mode', 'type'] },
330
+ output: { type: 'enum', options: ['distance', 'edges', 'id', 'crackle', 'crystal'], default: 'edges', desc: 'what C holds (crystal = a tilted flat facet per cell)', aliases: ['mode', 'type'] },
221
331
  scale: { type: 'float', default: 8, min: 0.01, desc: 'cells across the image width (whole numbers when tileable)', aliases: ['frequency', 'freq', 'count'] },
222
332
  jitter: { type: 'float', default: 1, min: 0, max: 1, desc: 'randomness of the sites (0 = square grid)', aliases: ['randomness', 'disorder'] },
223
333
  edge_width: { type: 'float', default: 0.1, min: 0.001, max: 1, desc: 'edges: border width (fraction of a cell)', aliases: ['width', 'border'] },
224
334
  metric: { type: 'enum', options: ['euclidean', 'manhattan', 'chebyshev'], default: 'euclidean', desc: 'distance metric (manhattan = diamond cells, chebyshev = square cells)' },
225
335
  tileable: { type: 'bool', default: true, desc: 'repeat seamlessly at the image borders', aliases: ['tile', 'tiling', 'seamless'] },
226
336
  seed: P.seed(),
227
- name: nameParam('cells'),
337
+ name: nameParam(),
228
338
  },
229
- outputs: 'image <name>: C grey (the chosen output), id grey random per cell',
339
+ usesNodeName: NAMED_BY_NODE,
340
+ outputs: 'image <name> (default: the node name): C grey (the chosen output), id grey random per cell',
230
341
  example: { type: 'tex_cells', params: { output: 'edges', scale: 10, edge_width: 0.08 } },
231
- cook: ({ p, type, parallelMap }) => {
342
+ cook: (ctx) => {
343
+ const { p, type, parallelMap } = ctx;
232
344
  const [w, h] = size2(p, type);
233
345
  const job = {
234
346
  width: w, height: h, scale: p.scale, jitter: p.jitter, seed: p.seed, tileable: !!p.tileable, output: p.output, edgeWidth: p.edge_width,
235
347
  metric: ['euclidean', 'manhattan', 'chebyshev'].indexOf(p.metric),
236
348
  };
237
349
  const C = new Float32Array(w * h), id = new Float32Array(w * h);
238
- return andThen(parallelMap('tex_cells', { count: w * h, args: job, results: { C, id } }), () => imageGeo(new Image(w, h, imgName(p, 'cells')).set(MAIN_LAYER, C).set('id', id)));
350
+ return andThen(parallelMap('tex_cells', { count: w * h, args: job, results: { C, id } }), () => imageGeo(new Image(w, h, outName(ctx)).set(MAIN_LAYER, C).set('id', id)));
239
351
  },
240
352
  });
241
353
  defineNode({
@@ -256,14 +368,16 @@ defineNode({
256
368
  intensity: { type: 'vec2', default: [0.4, 1], min: 0, desc: 'intensity range of a stroke' },
257
369
  tileable: { type: 'bool', default: true, desc: 'strokes wrap at the borders', aliases: ['tile', 'wrap'] },
258
370
  seed: P.seed(),
259
- name: nameParam('scratches'),
371
+ name: nameParam(),
260
372
  },
261
- outputs: 'image <name>: C grey 0..1',
373
+ usesNodeName: NAMED_BY_NODE,
374
+ outputs: 'image <name> (default: the node name): C grey 0..1',
262
375
  example: { type: 'tex_scratches', params: { resolution: 512, count: 150, angle: 45, seed: 3 } },
263
- cook: ({ p, type }) => {
376
+ cook: (ctx) => {
377
+ const { p, type } = ctx;
264
378
  const [w, h] = size2(p, type);
265
379
  const C = genScratches({ count: p.count, length: [p.length[0], p.length[1]], width: p.width, angle: p.angle, spread: p.spread, curvature: p.curvature, intensity: [p.intensity[0], p.intensity[1]], seed: p.seed, wrap: !!p.tileable }, w, h);
266
- return imageGeo(new Image(w, h, imgName(p, 'scratches')).set(MAIN_LAYER, C));
380
+ return imageGeo(new Image(w, h, outName(ctx)).set(MAIN_LAYER, C));
267
381
  },
268
382
  });
269
383
  defineNode({
@@ -283,14 +397,16 @@ defineNode({
283
397
  combine: { type: 'enum', options: ['max', 'add'], default: 'max', desc: 'how overlapping blobs combine', aliases: ['blend'] },
284
398
  tileable: { type: 'bool', default: true, desc: 'blobs wrap at the borders', aliases: ['tile', 'wrap'] },
285
399
  seed: P.seed(),
286
- name: nameParam('splatter'),
400
+ name: nameParam(),
287
401
  },
288
- outputs: 'image <name>: C grey 0..1',
402
+ usesNodeName: NAMED_BY_NODE,
403
+ outputs: 'image <name> (default: the node name): C grey 0..1',
289
404
  example: { type: 'tex_splatter', params: { resolution: 512, count: 40, size: [0.03, 0.1], seed: 2 } },
290
- cook: ({ p, type }) => {
405
+ cook: (ctx) => {
406
+ const { p, type } = ctx;
291
407
  const [w, h] = size2(p, type);
292
408
  const C = genSplatter({ count: p.count, size: [p.size[0], p.size[1]], irregularity: p.irregularity, softness: p.softness, intensity: [p.intensity[0], p.intensity[1]], seed: p.seed, wrap: !!p.tileable, add: p.combine === 'add' }, w, h);
293
- return imageGeo(new Image(w, h, imgName(p, 'splatter')).set(MAIN_LAYER, C));
409
+ return imageGeo(new Image(w, h, outName(ctx)).set(MAIN_LAYER, C));
294
410
  },
295
411
  });
296
412
  /** Even-odd fill of closed contours (pixel coordinates) with 4 sub-scanlines per pixel row and exact horizontal coverage. */
@@ -342,9 +458,11 @@ defineNode({
342
458
  size: { type: 'float', default: 0.2, min: 0.001, desc: 'height of the text block as a fraction of the image height (shrunk to fit the width)', aliases: ['height', 'font_size'] },
343
459
  position: { type: 'vec2', default: [0.5, 0.5], desc: 'centre of the text in uv', aliases: ['center'] },
344
460
  align: { type: 'enum', options: ['left', 'center', 'right'], default: 'center', desc: 'horizontal alignment of lines' },
345
- name: nameParam('text'),
461
+ name: nameParam(),
346
462
  },
347
- outputs: 'image <name>: C grey 0..1',
463
+ outputs: 'image <name> (default: the node name): C grey 0..1',
464
+ // it cooks a text node, which reads its font through the scope
465
+ usesNodeName: NAMED_BY_NODE,
348
466
  example: { type: 'tex_text', params: { resolution: [512, 128], text: 'EXIT', size: 0.7 } },
349
467
  async cook(ctx) {
350
468
  const { p, type } = ctx;
@@ -353,7 +471,7 @@ defineNode({
353
471
  if (!r.ok || !r.geo)
354
472
  throw new NodeError(`${type}: ${r.errors.map((e) => e.message).join('; ') || 'text failed'}`);
355
473
  const g = r.geo;
356
- const img = new Image(w, h, imgName(p, 'text'));
474
+ const img = new Image(w, h, outName(ctx));
357
475
  if (!g.numPrims)
358
476
  return imageGeo(img.set(MAIN_LAYER, new Float32Array(w * h)));
359
477
  const b = g.bbox();
@@ -373,48 +491,128 @@ defineNode({
373
491
  return imageGeo(img.set(MAIN_LAYER, fillContours(contours, w, h)));
374
492
  },
375
493
  });
494
+ defineNode({
495
+ type: 'tex_sdf_shape',
496
+ category: 'texture',
497
+ summary: 'SDF shape image: the signed distance in metres to a disc, box, polygon, star, capsule or cross (or a grid of them), for SDF offsets, booleans, bevels and outlines.',
498
+ description: 'Houdini COP: SDF Shape; Substance: Shape (as a distance field). C holds the signed distance in metres (negative ' +
499
+ 'inside, 0 on the outline) on an image whose width covers `size` metres, so every distance node downstream ' +
500
+ '(tex_sdf_op, tex_sdf_boolean, tex_sdf_to_mask) works in metres and gives the same result at any resolution. ' +
501
+ 'radius sizes disc, polygon and star; extent sizes box (width, height), capsule (length, thickness) and cross (arm ' +
502
+ 'length, thickness); corner rounds box, polygon and cross. tile repeats the shape (center places it in each tile, ' +
503
+ 'in the tile\'s uv); with tileable the grid continues past the borders, so the field tiles and shapes cut by a ' +
504
+ 'border continue on the other side. Panels, plates, rivets, slots, vents, decals. See it with tex_sdf_to_mask.',
505
+ aliases: ['sdf_shape_texture', 'cop_sdfshape', 'shape_sdf', 'distance_shape'],
506
+ inputs: [],
507
+ params: {
508
+ resolution: resolutionParam(),
509
+ shape: { type: 'enum', options: SDF_SHAPES, default: 'box', desc: 'shape', aliases: ['type'] },
510
+ radius: { type: 'float', default: 0.3, min: 0, desc: 'disc, polygon, star: (outer) radius in metres' },
511
+ extent: { type: 'vec2', default: [0.6, 0.4], min: 0, desc: 'box: width and height; capsule: length and thickness; cross: arm length and thickness (metres)', aliases: ['box_size', 'shape_size'] },
512
+ corner: { type: 'float', default: 0, min: 0, desc: 'corner rounding radius in metres (box, polygon, cross)', aliases: ['corner_radius', 'rounding'] },
513
+ sides: { type: 'int', default: 6, min: 3, max: 64, desc: 'polygon: sides; star: points' },
514
+ inner_radius: { type: 'float', default: 0.5, min: 0.01, max: 1, desc: 'star: inner radius / outer radius', aliases: ['inner'] },
515
+ rotation: { type: 'float', default: 0, desc: 'rotation in degrees (counter-clockwise)', aliases: ['angle', 'rotate'] },
516
+ center: { type: 'vec2', default: [0.5, 0.5], desc: 'centre in each tile\'s uv (0.5, 0.5 = the middle)', aliases: ['position'] },
517
+ tile: { type: 'ivec2', default: [1, 1], min: 1, max: 512, desc: 'repeats along u and v', aliases: ['tiling', 'repeat', 'count'] },
518
+ size: sizeParam(),
519
+ tileable: tileParam('the grid of shapes continues past the borders (the field tiles)'),
520
+ name: nameParam(),
521
+ },
522
+ usesNodeName: NAMED_BY_NODE,
523
+ outputs: 'image <name> (default: the node name): C grey signed distance in metres (negative inside)',
524
+ example: { type: 'tex_sdf_shape', params: { resolution: 256, shape: 'box', extent: [0.4, 0.4], corner: 0.06, tile: [2, 2] } },
525
+ cook: (ctx) => {
526
+ const { p, type } = ctx;
527
+ const [w, h] = size2(p, type);
528
+ const o = {
529
+ shape: p.shape, radius: p.radius, extent: [p.extent[0], p.extent[1]], sides: p.sides, inner: p.inner_radius, corner: p.corner,
530
+ rotation: p.rotation, center: [p.center[0], p.center[1]], tile: [p.tile[0], p.tile[1]], size: p.size, wrap: !!p.tileable,
531
+ };
532
+ const { kx, ky } = shapeReach(o, w, h), per = (2 * kx + 1) * (2 * ky + 1);
533
+ if (per > 289)
534
+ ctx.warn(`${type}: each shape reaches over ${2 * kx + 1} × ${2 * ky + 1} cells of the tile grid, so every pixel measures ${per} instances (slow at high resolutions): fewer tiles, or a smaller shape`);
535
+ const C = sdfShape(o, w, h);
536
+ return imageGeo(new Image(w, h, outName(ctx)).set(MAIN_LAYER, C));
537
+ },
538
+ });
539
+ defineNode({
540
+ type: 'tex_grunge',
541
+ category: 'texture',
542
+ summary: 'Grunge mask: dirt patches, vertical leaks or scattered spots, with a set coverage and edge hardness; tileable.',
543
+ description: 'Substance: Grunge Map / Dirt / Leaks / Rust spots. dirt is blotchy domain-warped noise with speckle; leaks are ' +
544
+ 'vertical runs streaking down from random sources (rain marks, rust runs under bolts: mask them with an AO or ' +
545
+ 'cavity map); spots are round stains and pits of random size. coverage is the fraction of the image that turns ' +
546
+ 'white, measured on the mask\'s own histogram like tex_histogram_scan, so 0.2 is a fifth whatever the style or ' +
547
+ 'seed; contrast is the edge hardness (1 = hard); detail mixes in fine breakup. scale = features across the image ' +
548
+ 'width. Built from noise over uv, so the same at any resolution.',
549
+ aliases: ['grunge_generator', 'dirt_texture', 'leaks', 'rust_spots', 'grunge_map'],
550
+ inputs: [],
551
+ params: {
552
+ resolution: resolutionParam(),
553
+ style: { type: 'enum', options: GRUNGE_STYLES, default: 'dirt', desc: 'dirt patches, vertical leaks or round spots', aliases: ['type', 'mode'] },
554
+ scale: { type: 'float', default: 4, min: 0.1, max: 256, desc: 'features across the image width', aliases: ['frequency'] },
555
+ coverage: { type: 'float', default: 0.35, min: 0, max: 1, desc: 'fraction of the image that turns white', aliases: ['amount', 'density'] },
556
+ contrast: { type: 'float', default: 0.6, min: 0, max: 1, desc: 'edge hardness (1 = hard)', aliases: ['hardness'] },
557
+ detail: { type: 'float', default: 0.4, min: 0, max: 1, desc: 'fine breakup mixed in (0 = smooth shapes)', aliases: ['breakup'] },
558
+ tileable: { type: 'bool', default: true, desc: 'repeat seamlessly at the image borders', aliases: ['tile', 'tiling', 'seamless'] },
559
+ seed: P.seed(),
560
+ name: nameParam(),
561
+ },
562
+ usesNodeName: NAMED_BY_NODE,
563
+ outputs: 'image <name> (default: the node name): C grey 0..1 (white = grime)',
564
+ example: { type: 'tex_grunge', params: { resolution: 256, style: 'leaks', scale: 6, coverage: 0.3, seed: 2 } },
565
+ cook: (ctx) => {
566
+ const { p, type } = ctx;
567
+ const [w, h] = size2(p, type);
568
+ const C = genGrunge({ style: p.style, scale: p.scale, coverage: p.coverage, contrast: p.contrast, detail: p.detail, seed: p.seed, tileable: !!p.tileable }, w, h);
569
+ return imageGeo(new Image(w, h, outName(ctx)).set(MAIN_LAYER, C));
570
+ },
571
+ });
376
572
  // ---------------------------------------------------------------- files
377
573
  defineNode({
378
574
  type: 'image_file',
379
575
  category: 'texture',
380
576
  packed: 'keep',
381
577
  summary: 'Load a PNG (8 or 16 bit, grey or colour) as an image: your own textures and masks into the texture nodes and materials.',
382
- description: 'Houdini COP: File; Substance: Bitmap. The image is named after the file ("inputs/brick.png" → "brick") unless name ' +
383
- 'is set; layer C holds it, grey or RGBA (layers), and a grey image keeps the file\'s alpha, when it has one, in layer ' +
578
+ description: 'Houdini COP: File; Substance: Bitmap. The image is named after this node, like every image a node makes, unless ' +
579
+ 'name is set; layer C holds it, grey or RGBA (layers), and a grey image keeps the file\'s alpha, when it has one, in layer ' +
384
580
  '"A". Values are samples / 255 (16-bit files / 65535: their precision is kept). Colour layers hold display values, as ' +
385
581
  'every colour in the engine does ("#a5462e" is 0.65, 0.27, 0.18), so srgb (on by default) keeps the numbers the file ' +
386
582
  'stores: a PNG this engine wrote reads back unchanged, and masks, heights, normal and roughness maps load as they are. ' +
387
583
  'Turn srgb off only for a file holding linear-light colour (a linear render): grey and RGB are then encoded to display ' +
388
584
  'values, alpha never (unlike Unreal\'s sRGB checkbox, off does not mean "data"). With input 0 connected the image is ' +
389
585
  'added to that geometry, replacing an image of the same name, so image_file nodes chain. The file node reads .png ' +
390
- 'files the same way (with these defaults).',
586
+ 'files the same way (with these defaults), naming the image after the file.',
391
587
  aliases: ['image_read', 'png_read', 'texture_file'],
392
588
  inputs: [{ name: 'geo', desc: 'optional: add the image to this geometry (chain image_file nodes, or carry a mesh); else the output holds only the image', optional: true }],
393
589
  params: {
394
- path: { type: 'path', default: '', desc: 'PNG file (relative to the workspace, e.g. "inputs/brick.png") or URL', aliases: ['file', 'filename'] },
395
- name: nameParam('', 'image name ("" = the file name without .png); materials reference it as "image:<name>"'),
590
+ path: { type: 'path', default: '', desc: 'PNG file (relative to the package folder, e.g. "inputs/brick.png") or URL', aliases: ['file', 'filename'] },
591
+ name: nameParam(),
396
592
  layers: { type: 'enum', options: [...PNG_LAYERS], default: 'auto', desc: 'auto = grey for grey PNGs (1–2 channels), RGBA for colour ones; grey = the luminance of a colour file; rgba = always four channels', aliases: ['channels'] },
397
593
  srgb: { type: 'bool', default: true, desc: 'the file holds display (sRGB) values: kept as stored, like every colour in the engine (masks and data maps load unchanged too); off = it holds linear-light colour, encoded to display values on load (alpha never)' },
398
594
  },
399
- signatureExtra: (p, engine) => engine.host.fileStamp(p.path),
400
- outputs: 'image <name>: C grey or RGBA 0..1; A grey (the file\'s alpha, for a grey image of a file with alpha)',
595
+ // relative paths read the scope's folder
596
+ usesNodeName: NAMED_BY_NODE,
597
+ signatureExtra: (p, scope) => scope.files.fileStamp(p.path),
598
+ outputs: 'image <name> (default: the node name): C grey or RGBA 0..1; A grey (the file\'s alpha, for a grey image of a file with alpha)',
401
599
  example: {
402
600
  nodes: {
403
- color: { type: 'image_file', params: { path: 'inputs/brick_color.png' } },
404
- maps: { type: 'image_file', in: ['color'], params: { path: 'inputs/brick_rough.png', layers: 'grey' } },
601
+ brick_color: { type: 'image_file', params: { path: 'inputs/brick_color.png' } },
602
+ brick_rough: { type: 'image_file', in: ['brick_color'], params: { path: 'inputs/brick_rough.png', layers: 'grey' } },
405
603
  box: { type: 'box' },
406
604
  uv: { type: 'uv_project', in: ['box'], params: { method: 'box' } },
407
- out: { type: 'texture_to_material', in: ['uv', 'maps'], params: { material: 'brick', base_color: 'brick_color', roughness: 'brick_rough' } },
605
+ out: { type: 'texture_to_material', in: ['uv', 'brick_rough'], params: { material: 'brick', base_color: 'brick_color', roughness: 'brick_rough' } },
408
606
  },
409
607
  output: 'out',
410
608
  },
411
609
  async cook(ctx) {
412
- const { p, type, engine } = ctx;
610
+ const { p, type, scope } = ctx;
413
611
  if (!String(p.path ?? '').trim())
414
- throw new NodeError(`${type}: path is empty`, 'a PNG relative to the workspace (people drop theirs into inputs/) or a URL');
612
+ throw new NodeError(`${type}: path is empty`, 'a PNG relative to the package folder (people drop theirs into inputs/) or a URL');
415
613
  let img;
416
614
  try {
417
- img = await readImageFile((f) => engine.host.readFile(f), p.path, { name: String(p.name ?? '').trim(), layers: p.layers, srgb: !!p.srgb });
615
+ img = await readImageFile((f) => scope.files.readFile(f), p.path, { name: outName(ctx), layers: p.layers, srgb: !!p.srgb });
418
616
  }
419
617
  catch (e) {
420
618
  throw new NodeError(`${type}: ${e?.message ?? e}`);
@@ -429,12 +627,13 @@ defineNode({
429
627
  },
430
628
  });
431
629
  // ---------------------------------------------------------------- filters
432
- const FILTER_INPUT = [{ name: 'image', desc: 'geometry holding the image to process (everything else passes through)' }];
630
+ const FILTER_INPUT = [{ name: 'image', desc: 'geometry holding the image to process (everything else passes through; with several images, image names the one)' }];
433
631
  defineNode({
434
632
  type: 'tex_blend',
633
+ usesNodeName: NAMED_BY_NODE,
435
634
  category: 'texture',
436
635
  summary: 'Blend a foreground image over a background with a mode (normal, add, multiply, screen, overlay, min, max, difference …), opacity and an optional mask.',
437
- description: 'Substance: Blend; Houdini COP: Blend / Composite. result = mix(background, mode(background, foreground), opacity × mask × foreground alpha). The foreground and mask are resized to the background. A grey and an RGBA input give RGBA; alpha is the background\'s. clamp keeps the result in 0..1.',
636
+ description: 'Substance: Blend; Houdini COP: Blend / Composite. result = mix(background, mode(background, foreground), opacity × mask × foreground alpha). The foreground and mask are resized to the background. A grey and an RGBA input give RGBA; alpha is the background\'s. clamp keeps the result in 0..1. For normal maps use tex_normal_blend (overlay flattens them).',
438
637
  aliases: ['blend', 'composite', 'cop_blend', 'layer_blend', 'mix_images'],
439
638
  inputs: [
440
639
  { name: 'background', desc: 'image A (its geometry passes through)' },
@@ -445,19 +644,21 @@ defineNode({
445
644
  mode: { type: 'enum', options: BLEND_MODES, default: 'normal', desc: 'blend mode', aliases: ['blend_mode', 'operation'] },
446
645
  opacity: { type: 'float', default: 1, min: 0, max: 1, desc: 'strength of the foreground', aliases: ['amount', 'alpha', 'weight'] },
447
646
  clamp: { type: 'bool', default: true, desc: 'clamp the result to 0..1' },
448
- image: imageParam(), layer: layerParam(),
449
- foreground_image: { type: 'string', default: '', desc: 'image of input 1 ("" = first)' },
647
+ image: imageParam('input 0 (the background)'), layer: layerParam(),
648
+ foreground_image: imageParam('input 1 (the foreground)', []),
450
649
  foreground_layer: { type: 'string', default: '', desc: 'layer of the foreground ("" = main)' },
650
+ mask_image: imageParam('input 2 (the mask)', []),
451
651
  mask_layer: { type: 'string', default: '', desc: 'layer of the mask image ("" = main)' },
452
652
  tileable: tileParam('resizing wraps at the borders'),
453
653
  name: renameParam(),
454
654
  },
455
- outputs: 'the background image with the blended layer',
655
+ outputs: 'the background image with the blended layer, named <name> (default: the node name)',
456
656
  example: {
457
657
  nodes: {
458
- a: { type: 'tex_noise', params: { resolution: 256 } },
459
- b: { type: 'tex_pattern', params: { resolution: 256 } },
460
- out: { type: 'tex_blend', in: ['a', 'b'], params: { mode: 'multiply' } },
658
+ paint: { type: 'tex_noise', params: { resolution: 256, scale: 3 } },
659
+ metal: { type: 'tex_pattern', params: { resolution: 256 } },
660
+ wear: { type: 'tex_cells', params: { resolution: 256, output: 'edges' } },
661
+ out: { type: 'tex_blend', in: ['paint', 'metal', 'wear'], params: { mode: 'normal', opacity: 0.8 } },
461
662
  },
462
663
  output: 'out',
463
664
  },
@@ -465,16 +666,17 @@ defineNode({
465
666
  const { p } = ctx;
466
667
  const A = source(ctx, 0, p.image, p.layer);
467
668
  const w = A.img.width, h = A.img.height, wrap = !!p.tileable;
468
- const B = sourceAt(ctx, 1, w, h, p.foreground_image, p.foreground_layer, wrap);
669
+ const B = sourceAt(ctx, 1, w, h, p.foreground_image, p.foreground_layer, wrap, 'foreground_image');
469
670
  if (!B)
470
671
  throw new NodeError(`${ctx.type}: connect a foreground image to input 1`);
471
- const M = sourceAt(ctx, 2, w, h, '', p.mask_layer, wrap);
672
+ const M = sourceAt(ctx, 2, w, h, p.mask_image, p.mask_layer, wrap, 'mask_image');
472
673
  const r = blendLayers(A.data, A.ch, B.data, B.ch, M ? toGrey(M.data, M.ch) : null, p.mode, p.opacity, !!p.clamp);
473
- return withLayer(A, r.data, p.name);
674
+ return withLayer(A, r.data, outName(ctx));
474
675
  },
475
676
  });
476
677
  defineNode({
477
678
  type: 'tex_levels',
679
+ usesNodeName: NAMED_BY_NODE,
478
680
  category: 'texture',
479
681
  summary: 'Levels: remap the input range, apply gamma, remap to the output range (contrast, brightness, inversion).',
480
682
  description: 'Substance: Levels; Houdini COP: Levels. value = out_low + (out_high - out_low) × ((value - in_low) / (in_high - in_low))^(1/gamma). Applies to grey or RGB (alpha untouched).',
@@ -499,11 +701,12 @@ defineNode({
499
701
  cook: (ctx) => {
500
702
  const { p } = ctx;
501
703
  const s = source(ctx, 0, p.image, p.layer);
502
- return withLayer(s, mapValues(s.data, s.ch, levelsFn(p.in_low, p.in_high, p.gamma, p.out_low, p.out_high, !!p.clamp)), p.name);
704
+ return withLayer(s, mapValues(s.data, s.ch, levelsFn(p.in_low, p.in_high, p.gamma, p.out_low, p.out_high, !!p.clamp)), outName(ctx));
503
705
  },
504
706
  });
505
707
  defineNode({
506
708
  type: 'tex_curves',
709
+ usesNodeName: NAMED_BY_NODE,
507
710
  category: 'texture',
508
711
  summary: 'Curves: map every value through a ramp (a tone curve).',
509
712
  description: 'Substance: Curve; Houdini COP: Lookup. ramp keys [[in, out], …] interpolated linearly (input clamped to 0..1). Applies to grey or RGB (alpha untouched); a colour ramp maps through its luminance.',
@@ -519,11 +722,12 @@ defineNode({
519
722
  const s = source(ctx, 0, p.image, p.layer);
520
723
  const { lut, ch } = rampLUT((t) => evalRamp(p.ramp, t));
521
724
  const grey = ch === 1 ? lut : Float32Array.from({ length: lut.length / 3 }, (_, k) => lut[k * 3] * 0.2126 + lut[k * 3 + 1] * 0.7152 + lut[k * 3 + 2] * 0.0722);
522
- return withLayer(s, curvesLayer(s.data, s.ch, grey), p.name);
725
+ return withLayer(s, curvesLayer(s.data, s.ch, grey), outName(ctx));
523
726
  },
524
727
  });
525
728
  defineNode({
526
729
  type: 'tex_blur',
730
+ usesNodeName: NAMED_BY_NODE,
527
731
  category: 'texture',
528
732
  summary: 'Blur an image: gaussian or box, separable; tileable images blur across their borders (the mean is preserved).',
529
733
  description: 'Substance: Blur HQ; Houdini COP: Blur. radius in pixels (gaussian: radius = 2 sigma, three box passes of running sums, so the cost does not depend on the radius).',
@@ -545,26 +749,120 @@ defineNode({
545
749
  cook: (ctx) => {
546
750
  const { p } = ctx;
547
751
  const s = source(ctx, 0, p.image, p.layer);
548
- return withLayer(s, blurLayer(s.data, s.ch, s.img.width, s.img.height, p.radius, p.mode, !!p.tileable), p.name);
752
+ return withLayer(s, blurLayer(s.data, s.ch, s.img.width, s.img.height, p.radius, p.mode, !!p.tileable), outName(ctx));
753
+ },
754
+ });
755
+ defineNode({
756
+ type: 'tex_directional_blur',
757
+ usesNodeName: NAMED_BY_NODE,
758
+ category: 'texture',
759
+ summary: 'Directional (motion) blur along an angle, length in metres: brushed metal from noise, streaks, rain and speed lines.',
760
+ description: 'Substance: Directional Blur / Motion Blur; Houdini COP: Blur (directional). Every pixel averages the image along ' +
761
+ 'a line `length` metres long at angle (0 = +u, 90 = +v): centred on the pixel when symmetric, else trailing behind ' +
762
+ 'it, so bright marks streak along the angle. length is in metres of an image `size` metres wide, so a blur looks ' +
763
+ 'the same at any resolution. Brushed metal: tex_noise {scale: 60} → tex_directional_blur {length: 0.2} → ' +
764
+ 'tex_levels. Grey or RGBA (alpha blurs too).',
765
+ aliases: ['directional_blur', 'motion_blur', 'blur_directional', 'anisotropic_blur', 'streak_blur'],
766
+ inputs: FILTER_INPUT,
767
+ params: {
768
+ length: { type: 'float', default: 0.05, min: 0, desc: 'blur length in metres', aliases: ['distance', 'intensity'] },
769
+ angle: { type: 'float', default: 0, desc: 'direction in degrees (0 = +u, 90 = +v)', aliases: ['direction', 'rotation'] },
770
+ symmetric: { type: 'bool', default: true, desc: 'blur both ways around each pixel (off = a one-sided trail along angle)', aliases: ['centered'] },
771
+ size: sizeParam(),
772
+ tileable: tileParam(),
773
+ image: imageParam(), layer: layerParam(), name: renameParam(),
774
+ },
775
+ example: {
776
+ nodes: {
777
+ grain: { type: 'tex_noise', params: { resolution: 256, scale: 60, octaves: 3, seed: 4 } },
778
+ brushed: { type: 'tex_directional_blur', in: ['grain'], params: { length: 0.15, angle: 0 } },
779
+ },
780
+ output: 'brushed',
781
+ },
782
+ cook: (ctx) => {
783
+ const { p } = ctx;
784
+ const s = source(ctx, 0, p.image, p.layer);
785
+ const w = s.img.width, h = s.img.height;
786
+ return withLayer(s, directionalBlur(s.data, s.ch, w, h, (p.length / p.size) * w, p.angle, !!p.symmetric, !!p.tileable), outName(ctx));
787
+ },
788
+ });
789
+ defineNode({
790
+ type: 'tex_slope_blur',
791
+ usesNodeName: NAMED_BY_NODE,
792
+ category: 'texture',
793
+ summary: 'Slope blur: smear an image along the slopes of a second grey image (blur, min or max): flowing edges, melted and eroded looks, organic paint wear.',
794
+ description: 'Substance: Slope Blur Grayscale / Color. Every pixel walks down (or up) the slope of the grey map on input 1 for ' +
795
+ '`distance` metres in `samples` steps, re-reading the slope at each step, and combines what it meets: blur (the ' +
796
+ 'mean: flowing smears), min (eats bright areas along the flow: eroded, chipped edges) or max (grows them). Where ' +
797
+ 'the map is flatter than half its average slope the steps shrink in proportion, so flat areas stay put. Distances ' +
798
+ 'in metres of an image `size` metres wide, so the same at any resolution. Typical: ' +
799
+ 'a histogram_scan wear mask slope-blurred by tex_noise for ragged paint edges. Grey or RGBA (alpha is kept).',
800
+ aliases: ['slope_blur', 'slopeblur', 'slope_blur_grayscale', 'flow_blur'],
801
+ inputs: [
802
+ { name: 'image', desc: 'image to blur (its geometry passes through)' },
803
+ { name: 'slope', desc: 'grey map whose slopes the blur follows (noise, a height)' },
804
+ ],
805
+ params: {
806
+ distance: { type: 'float', default: 0.02, min: 0, desc: 'how far each pixel follows the slope, in metres', aliases: ['intensity', 'length'] },
807
+ samples: { type: 'int', default: 16, min: 1, max: 64, desc: 'steps along the slope (more = smoother)', aliases: ['steps'] },
808
+ mode: { type: 'enum', options: SLOPE_BLUR_MODES, default: 'blur', desc: 'blur = mean, min = erode bright areas, max = grow them', aliases: ['type'] },
809
+ direction: { type: 'enum', options: ['downhill', 'uphill'], default: 'downhill', desc: 'follow the slope down (default) or up' },
810
+ size: sizeParam(),
811
+ tileable: tileParam(),
812
+ image: imageParam(), layer: layerParam(),
813
+ slope_image: imageParam('input 1 (the slope map)', []),
814
+ slope_layer: { type: 'string', default: '', desc: 'layer of the slope map ("" = main)' },
815
+ name: renameParam(),
816
+ },
817
+ example: {
818
+ nodes: {
819
+ mask: { type: 'tex_sdf_shape', params: { resolution: 256, shape: 'disc', radius: 0.3 } },
820
+ fill: { type: 'tex_sdf_to_mask', in: ['mask'] },
821
+ flow: { type: 'tex_noise', params: { resolution: 256, scale: 8, seed: 3 } },
822
+ out: { type: 'tex_slope_blur', in: ['fill', 'flow'], params: { distance: 0.04, mode: 'min' } },
823
+ },
824
+ output: 'out',
825
+ },
826
+ cook: (ctx) => {
827
+ const { p, type } = ctx;
828
+ const s = source(ctx, 0, p.image, p.layer);
829
+ const w = s.img.width, h = s.img.height, wrap = !!p.tileable;
830
+ const S = sourceAt(ctx, 1, w, h, p.slope_image, p.slope_layer, wrap, 'slope_image');
831
+ if (!S)
832
+ throw new NodeError(`${type}: connect a slope map to input 1`, 'a grey image whose slopes the blur follows: tex_noise, tex_grunge, a height');
833
+ return withLayer(s, slopeBlur(s.data, s.ch, w, h, toGrey(S.data, S.ch), (p.distance / p.size) * w, p.samples, p.mode, p.direction === 'uphill', wrap), outName(ctx));
549
834
  },
550
835
  });
551
836
  defineNode({
552
837
  type: 'tex_warp',
838
+ usesNodeName: NAMED_BY_NODE,
553
839
  category: 'texture',
554
- summary: 'Warp an image by a second image: directional, along its slope, or by an RG vector map.',
555
- description: 'Substance: Warp / Directional Warp / Vector Warp; Houdini COP: Displace. intensity is the largest offset as a fraction of the image width: directional moves each pixel by intensity × warp value along angle; slope along the warp image\'s gradient (normalised so the steepest slope moves intensity); vector by (R, G) × 2 − 1 of an RGBA warp image.',
556
- aliases: ['warp', 'directional_warp', 'vector_warp', 'cop_displace', 'distort'],
840
+ summary: 'Warp an image by a second image: directional, along its slope, by an RG vector map, with a per-pixel angle map (non-uniform), or in several directions at once.',
841
+ description: 'Substance: Warp / Directional Warp / Vector Warp / Non-Uniform Directional Warp / Multi-Directional Warp; Houdini ' +
842
+ 'COP: Displace. intensity is the largest offset as a fraction of the image width (metres when the image spans one ' +
843
+ 'metre), so a warp looks the same at any resolution. directional moves each pixel by intensity × warp value along ' +
844
+ 'angle; slope along the warp image\'s gradient (normalised so the steepest slope moves intensity); vector by ' +
845
+ '(R, G) × 2 − 1 of an RGBA warp image; nonuniform like directional, with the angle map on input 2 (grey 0..1 = ' +
846
+ '0..360°) added to angle per pixel (flow along a pattern: wood grain around knots, fibres, brushed swirls); multi ' +
847
+ 'averages `directions` directional warps whose angles split the circle evenly from angle (a soft, direction-free ' +
848
+ 'smear: melted edges, worn paint borders).',
849
+ aliases: ['warp', 'directional_warp', 'vector_warp', 'cop_displace', 'distort', 'non_uniform_directional_warp', 'multi_directional_warp'],
557
850
  inputs: [
558
851
  { name: 'image', desc: 'image to warp (its geometry passes through)' },
559
- { name: 'warp', desc: 'grey (directional, slope) or RGBA (vector) warp image' },
852
+ { name: 'warp', desc: 'grey (directional, slope, nonuniform, multi) or RGBA (vector) warp image' },
853
+ { name: 'angle', desc: 'nonuniform: grey angle map (0..1 = 0..360°, added to angle)', optional: true },
560
854
  ],
561
855
  params: {
562
856
  mode: { type: 'enum', options: WARP_MODES, default: 'slope', desc: 'how the warp image moves pixels', aliases: ['type'] },
563
857
  intensity: { type: 'float', default: 0.02, desc: 'largest offset as a fraction of the image width', aliases: ['amount', 'strength'] },
564
- angle: { type: 'float', default: 0, desc: 'directional: direction in degrees (0 = +u)' },
858
+ angle: { type: 'float', default: 0, desc: 'directional, nonuniform, multi: direction in degrees (0 = +u)' },
859
+ directions: { type: 'int', default: 4, min: 1, max: 32, desc: 'multi: number of directions averaged' },
565
860
  tileable: tileParam(),
566
861
  image: imageParam(), layer: layerParam(),
862
+ warp_image: imageParam('input 1 (the warp image)', []),
567
863
  warp_layer: { type: 'string', default: '', desc: 'layer of the warp image ("" = main)' },
864
+ angle_image: imageParam('input 2 (the angle map)', []),
865
+ angle_layer: { type: 'string', default: '', desc: 'layer of the angle map ("" = main)' },
568
866
  name: renameParam(),
569
867
  },
570
868
  example: {
@@ -579,14 +877,18 @@ defineNode({
579
877
  const { p } = ctx;
580
878
  const s = source(ctx, 0, p.image, p.layer);
581
879
  const w = s.img.width, h = s.img.height;
582
- const W = sourceAt(ctx, 1, w, h, '', p.warp_layer, !!p.tileable);
880
+ const W = sourceAt(ctx, 1, w, h, p.warp_image, p.warp_layer, !!p.tileable, 'warp_image');
583
881
  if (!W)
584
- throw new NodeError(`${ctx.type}: connect a warp image to input 1`);
585
- return withLayer(s, warpLayer(s.data, s.ch, w, h, W.data, W.ch, p.mode, p.intensity, p.angle, !!p.tileable), p.name);
882
+ throw new NodeError(`${ctx.type}: connect a warp image to input 1`, 'a grey image whose values set how far each pixel moves (tex_noise, tex_cells …)');
883
+ const A = p.mode === 'nonuniform' ? sourceAt(ctx, 2, w, h, p.angle_image, p.angle_layer, !!p.tileable, 'angle_image') : null;
884
+ if (p.mode === 'nonuniform' && !A)
885
+ throw new NodeError(`${ctx.type}: mode nonuniform needs an angle map on input 2`, 'a grey image: 0..1 turns the direction by 0..360° (tex_noise for swirls, tex_gradient angular for a vortex); for one direction use mode directional');
886
+ return withLayer(s, warpLayer(s.data, s.ch, w, h, W.data, W.ch, p.mode, p.intensity, p.angle, !!p.tileable, A ? toGrey(A.data, A.ch) : null, p.directions), outName(ctx));
586
887
  },
587
888
  });
588
889
  defineNode({
589
890
  type: 'tex_transform',
891
+ usesNodeName: NAMED_BY_NODE,
590
892
  category: 'texture',
591
893
  summary: 'Offset, rotate, scale and tile an image (2D transform with wrap).',
592
894
  description: 'Substance: Transformation 2D; Houdini COP: Transform. The content is repeated `tile` times, scaled by `scale` (> 1 enlarges), rotated about the centre and shifted by offset (uv). With tileable the source repeats, else the outside is 0. Whole-number tiling and offsets keep a tileable image tileable; other rotations generally do not.',
@@ -610,19 +912,30 @@ defineNode({
610
912
  cook: (ctx) => {
611
913
  const { p } = ctx;
612
914
  const s = source(ctx, 0, p.image, p.layer);
613
- return withLayer(s, transformLayer(s.data, s.ch, s.img.width, s.img.height, [p.offset[0], p.offset[1]], p.rotate, [p.scale[0], p.scale[1]], [p.tile[0], p.tile[1]], !!p.tileable), p.name);
915
+ return withLayer(s, transformLayer(s.data, s.ch, s.img.width, s.img.height, [p.offset[0], p.offset[1]], p.rotate, [p.scale[0], p.scale[1]], [p.tile[0], p.tile[1]], !!p.tileable), outName(ctx));
614
916
  },
615
917
  });
616
918
  defineNode({
617
919
  type: 'tex_edge_detect',
920
+ usesNodeName: NAMED_BY_NODE,
618
921
  category: 'texture',
619
- summary: 'Edge detection: Sobel gradient magnitude of the (grey) image, scaled and optionally thickened.',
620
- description: 'Substance: Edge Detect; Houdini COP: Edge Detect. A 0 → 1 step gives about 1 at strength 1; width grows the lines by that many pixels (max filter).',
922
+ summary: 'Edge detection: Sobel gradient magnitude, or lines of a set width in metres along a mask\'s outline (centred, inside or outside), flat or rounded.',
923
+ description: 'Substance: Edge Detect; Houdini COP: Edge Detect. sobel: the gradient magnitude of the (grey) image; a 0 → 1 step ' +
924
+ 'gives about 1 at strength 1, and width grows the lines by that many pixels (max filter). outline, inner and outer ' +
925
+ 'draw a line line_width metres wide along where the image crosses threshold (centred on it, just inside, just ' +
926
+ 'outside), from its signed distance to a tenth of a pixel, so the line is the same width in metres at any ' +
927
+ 'resolution: panel seams, grout lines, the rim of a decal, edge wear bands. roundness 0 gives a flat antialiased ' +
928
+ 'line, 1 a rounded ridge (a height: feed tex_normal_from_height).',
621
929
  aliases: ['edge_detect', 'edges_texture', 'sobel', 'cop_edge'],
622
930
  inputs: FILTER_INPUT,
623
931
  params: {
624
- strength: { type: 'float', default: 1, min: 0, desc: 'multiplier of the gradient magnitude', aliases: ['intensity', 'contrast'] },
625
- width: { type: 'float', default: 0, min: 0, max: 64, desc: 'thicken the edges by this many pixels' },
932
+ mode: { type: 'enum', options: EDGE_MODES, default: 'sobel', desc: 'sobel = gradient magnitude; outline / inner / outer = a line of line_width metres along the mask\'s outline', aliases: ['type', 'method'] },
933
+ strength: { type: 'float', default: 1, min: 0, desc: 'sobel: multiplier of the gradient magnitude', aliases: ['intensity', 'contrast'] },
934
+ width: { type: 'float', default: 0, min: 0, max: 64, desc: 'sobel: thicken the edges by this many pixels' },
935
+ line_width: { type: 'float', default: 0.01, min: 0, desc: 'outline / inner / outer: line width in metres', aliases: ['edge_width', 'thickness'] },
936
+ roundness: { type: 'float', default: 0, min: 0, max: 1, desc: 'outline / inner / outer: 0 = flat line, 1 = rounded ridge', aliases: ['edge_roundness'] },
937
+ threshold: { type: 'float', default: 0.5, desc: 'outline / inner / outer: the value where the outline runs', aliases: ['tolerance'] },
938
+ size: sizeParam(),
626
939
  tileable: tileParam(),
627
940
  image: imageParam(), layer: layerParam(), name: renameParam(),
628
941
  },
@@ -636,11 +949,14 @@ defineNode({
636
949
  cook: (ctx) => {
637
950
  const { p } = ctx;
638
951
  const s = source(ctx, 0, p.image, p.layer);
639
- return withLayer(s, edgeDetect(toGrey(s.data, s.ch), s.img.width, s.img.height, p.strength, p.width, !!p.tileable), p.name);
952
+ if (p.mode !== 'sobel')
953
+ return withLayer(s, edgeBand(maskSDF(s, p.threshold, p.size, !!p.tileable), p.mode, p.line_width, p.roundness, p.size / s.img.width), outName(ctx));
954
+ return withLayer(s, edgeDetect(toGrey(s.data, s.ch), s.img.width, s.img.height, p.strength, p.width, !!p.tileable), outName(ctx));
640
955
  },
641
956
  });
642
957
  defineNode({
643
958
  type: 'tex_invert',
959
+ usesNodeName: NAMED_BY_NODE,
644
960
  category: 'texture',
645
961
  summary: 'Invert: 1 - value (grey or RGB; alpha untouched).',
646
962
  aliases: ['invert', 'cop_invert', 'negate'],
@@ -649,11 +965,12 @@ defineNode({
649
965
  example: { nodes: { n: { type: 'tex_noise', params: { resolution: 256 } }, out: { type: 'tex_invert', in: ['n'] } }, output: 'out' },
650
966
  cook: (ctx) => {
651
967
  const s = source(ctx, 0, ctx.p.image, ctx.p.layer);
652
- return withLayer(s, mapValues(s.data, s.ch, (x) => 1 - x), ctx.p.name);
968
+ return withLayer(s, mapValues(s.data, s.ch, (x) => 1 - x), outName(ctx));
653
969
  },
654
970
  });
655
971
  defineNode({
656
972
  type: 'tex_threshold',
973
+ usesNodeName: NAMED_BY_NODE,
657
974
  category: 'texture',
658
975
  summary: 'Threshold: grey 1 where the value (luminance) is above threshold, else 0, with an optional soft band.',
659
976
  aliases: ['threshold', 'cop_threshold', 'binarize'],
@@ -684,47 +1001,240 @@ defineNode({
684
1001
  out[i] = t * t * (3 - 2 * t);
685
1002
  }
686
1003
  }
687
- return withLayer(s, out, p.name);
1004
+ return withLayer(s, out, outName(ctx));
688
1005
  },
689
1006
  });
690
1007
  defineNode({
691
1008
  type: 'tex_histogram_scan',
1009
+ usesNodeName: NAMED_BY_NODE,
692
1010
  category: 'texture',
693
- summary: 'Histogram scan: slide a threshold through a grey image (position) with adjustable hardness (contrast); the classic mask maker.',
694
- description: 'Substance: Histogram Scan. position 0 = black, 1 = white, 0.5 with contrast 0 = unchanged; contrast 1 = a hard cut at 1 - position. Use on noise or a curvature bake to grow wear or dirt masks.',
1011
+ summary: 'Histogram scan: turn a grey image into a mask with a set white coverage (or a threshold position) and hardness (contrast); the classic mask maker.',
1012
+ description: 'Substance: Histogram Scan. coverage is the fraction of the image that turns white, measured on its own histogram: ' +
1013
+ '0.3 makes the brightest 30 % of the pixels white whatever the input\'s range (a noise of 0..0.48, a curvature bake), ' +
1014
+ 'so a value read off a wear reference works on any input. With coverage -1, position sets a value cut instead: the ' +
1015
+ 'cut sits at 1 - position (0 = black, 1 = white; 0.5 with contrast 0 = unchanged), so how much turns white depends ' +
1016
+ 'on the input. contrast is the hardness of the transition around the cut (1 = hard; softer edges blend around the ' +
1017
+ 'same cut). The stat coverage reports the fraction of the result above 0.5. Use on noise or a curvature bake to ' +
1018
+ 'grow wear or dirt masks.',
695
1019
  aliases: ['histogram_scan', 'histogramscan', 'scan'],
696
1020
  inputs: FILTER_INPUT,
697
1021
  params: {
698
- position: { type: 'float', default: 0.5, min: 0, max: 1, desc: 'how much is white (0 = none, 1 = all)' },
1022
+ coverage: { type: 'float', default: -1, min: -1, max: 1, desc: 'fraction of the pixels that turn white (0.3 = the brightest 30 %), from the image\'s own histogram; -1 = use position', aliases: ['white_fraction', 'amount'] },
1023
+ position: { type: 'float', default: 0.5, min: 0, max: 1, desc: 'coverage -1: value cut at 1 - position (higher = more white; how much depends on the input\'s range)' },
699
1024
  contrast: { type: 'float', default: 0.5, min: 0, max: 1, desc: 'hardness of the transition (1 = hard cut)' },
700
1025
  image: imageParam(), layer: layerParam(), name: renameParam(),
701
1026
  },
1027
+ outputs: 'the mask (grey) named <name> (default: the node name); stat coverage = its fraction above 0.5',
702
1028
  example: {
703
1029
  nodes: {
704
1030
  n: { type: 'tex_noise', params: { resolution: 256, scale: 4 } },
705
- out: { type: 'tex_histogram_scan', in: ['n'], params: { position: 0.4, contrast: 0.8 } },
1031
+ out: { type: 'tex_histogram_scan', in: ['n'], params: { coverage: 0.3, contrast: 0.8 } },
706
1032
  },
707
1033
  output: 'out',
708
1034
  },
709
1035
  cook: (ctx) => {
710
1036
  const { p } = ctx;
711
1037
  const s = source(ctx, 0, p.image, p.layer);
712
- const f = histogramScanFn(p.position, p.contrast), g = toGrey(s.data, s.ch);
1038
+ const g = toGrey(s.data, s.ch);
1039
+ const f = p.coverage >= 0 ? histogramScanFn(1 - coverageCut(g, p.coverage, p.contrast), p.contrast) : histogramScanFn(p.position, p.contrast);
713
1040
  const out = new Float32Array(g.length);
1041
+ let white = 0;
1042
+ for (let i = 0; i < g.length; i++) {
1043
+ out[i] = f(g[i]);
1044
+ if (out[i] > 0.5)
1045
+ white++;
1046
+ }
1047
+ ctx.stat('coverage', white / Math.max(1, g.length));
1048
+ return withLayer(s, out, outName(ctx));
1049
+ },
1050
+ });
1051
+ defineNode({
1052
+ type: 'tex_histogram_range',
1053
+ usesNodeName: NAMED_BY_NODE,
1054
+ category: 'texture',
1055
+ summary: 'Histogram range: squeeze the values toward a position (range 1 = unchanged, 0 = flat at position); a contrast and level control in one.',
1056
+ description: 'Substance: Histogram Range. value = position + (value - 0.5) × range, clamped to 0..1: range scales the contrast around the middle grey, position moves the result\'s centre (0.5 keeps it). Narrow a mask to a subtle variation (range 0.2, position 0.6: a roughness that varies between 0.5 and 0.7). Grey or RGB (alpha untouched).',
1057
+ aliases: ['histogram_range', 'histogramrange', 'range_texture'],
1058
+ inputs: FILTER_INPUT,
1059
+ params: {
1060
+ range: { type: 'float', default: 0.5, min: 0, max: 1, desc: 'contrast kept (1 = unchanged, 0 = flat)', aliases: ['contrast', 'amount'] },
1061
+ position: { type: 'float', default: 0.5, min: 0, max: 1, desc: 'where the middle grey lands', aliases: ['center', 'level'] },
1062
+ image: imageParam(), layer: layerParam(), name: renameParam(),
1063
+ },
1064
+ example: {
1065
+ nodes: {
1066
+ n: { type: 'tex_noise', params: { resolution: 256 } },
1067
+ out: { type: 'tex_histogram_range', in: ['n'], params: { range: 0.3, position: 0.65 } },
1068
+ },
1069
+ output: 'out',
1070
+ },
1071
+ cook: (ctx) => {
1072
+ const { p } = ctx;
1073
+ const s = source(ctx, 0, p.image, p.layer);
1074
+ return withLayer(s, mapValues(s.data, s.ch, histogramRangeFn(p.range, p.position)), outName(ctx));
1075
+ },
1076
+ });
1077
+ defineNode({
1078
+ type: 'tex_histogram_select',
1079
+ usesNodeName: NAMED_BY_NODE,
1080
+ category: 'texture',
1081
+ summary: 'Histogram select: a mask of the values within a band (position ± range / 2), with soft or hard edges.',
1082
+ description: 'Substance: Histogram Select. White where the (grey, or luminance) value lies within range / 2 of position, black beyond; contrast 1 is a hard band, lower values soften both edges around the same half-way points (0 = a tent that peaks at position). Pick one height band of a terrain or heightmap, one id range of tex_flood_fill, the mid-tones of a noise.',
1083
+ aliases: ['histogram_select', 'histogramselect', 'value_band', 'band_select'],
1084
+ inputs: FILTER_INPUT,
1085
+ params: {
1086
+ position: { type: 'float', default: 0.5, desc: 'centre of the selected band', aliases: ['center', 'value'] },
1087
+ range: { type: 'float', default: 0.25, min: 0, desc: 'width of the band', aliases: ['width'] },
1088
+ contrast: { type: 'float', default: 0.5, min: 0, max: 1, desc: 'edge hardness (1 = hard)', aliases: ['hardness'] },
1089
+ image: imageParam(), layer: layerParam(), name: renameParam(),
1090
+ },
1091
+ outputs: 'the mask (grey) named <name> (default: the node name)',
1092
+ example: {
1093
+ nodes: {
1094
+ g: { type: 'tex_gradient', params: { resolution: 256 } },
1095
+ out: { type: 'tex_histogram_select', in: ['g'], params: { position: 0.5, range: 0.2, contrast: 0.8 } },
1096
+ },
1097
+ output: 'out',
1098
+ },
1099
+ cook: (ctx) => {
1100
+ const { p } = ctx;
1101
+ const s = source(ctx, 0, p.image, p.layer);
1102
+ const f = histogramSelectFn(p.position, p.range, p.contrast), g = toGrey(s.data, s.ch), out = new Float32Array(g.length);
714
1103
  for (let i = 0; i < g.length; i++)
715
1104
  out[i] = f(g[i]);
716
- return withLayer(s, out, p.name);
1105
+ return withLayer(s, out, outName(ctx));
1106
+ },
1107
+ });
1108
+ defineNode({
1109
+ type: 'tex_auto_levels',
1110
+ usesNodeName: NAMED_BY_NODE,
1111
+ category: 'texture',
1112
+ summary: 'Auto levels: stretch the image\'s own value range to 0..1, optionally ignoring a fraction of outliers at each end.',
1113
+ description: 'Substance: Auto Levels; Houdini COP: Normalize. The darkest value becomes 0 and the brightest 1 (RGB together, so colours keep their hue, or each channel by itself with per_channel). clip ignores that fraction of the values at each end (0.01 = the darkest and brightest 1 %), so a few outliers do not keep the rest grey. The stats range_min and range_max report the range used. Good after blends, AO and curvature that land in a narrow band. Alpha untouched.',
1114
+ aliases: ['auto_levels', 'autolevels', 'normalize_range', 'cop_normalize', 'stretch_levels'],
1115
+ inputs: FILTER_INPUT,
1116
+ params: {
1117
+ clip: { type: 'float', default: 0, min: 0, max: 0.49, desc: 'fraction of the values ignored at each end (outliers)', aliases: ['percentile', 'cutoff'] },
1118
+ per_channel: { type: 'bool', default: false, desc: 'stretch R, G and B each by its own range (shifts hues)' },
1119
+ image: imageParam(), layer: layerParam(), name: renameParam(),
1120
+ },
1121
+ outputs: 'the image stretched to 0..1, named <name> (default: the node name); stats range_min, range_max',
1122
+ example: {
1123
+ nodes: {
1124
+ n: { type: 'tex_noise', params: { resolution: 256 } },
1125
+ dim: { type: 'tex_levels', in: ['n'], params: { out_low: 0.3, out_high: 0.5 } },
1126
+ out: { type: 'tex_auto_levels', in: ['dim'] },
1127
+ },
1128
+ output: 'out',
1129
+ },
1130
+ cook: (ctx) => {
1131
+ const { p, type } = ctx;
1132
+ const s = source(ctx, 0, p.image, p.layer);
1133
+ const stretch = (lo, hi) => (hi > lo ? (x) => (x - lo) / (hi - lo) : (x) => x - lo + 0.5);
1134
+ let out;
1135
+ if (p.per_channel && s.ch === 4) {
1136
+ out = s.data.slice();
1137
+ let low = Infinity, high = -Infinity, flat = 0;
1138
+ for (let c = 0; c < 3; c++) {
1139
+ const [lo, hi] = valueRange(s.data, 4, p.clip, c), f = stretch(lo, hi);
1140
+ if (!(hi > lo))
1141
+ flat++;
1142
+ low = Math.min(low, lo);
1143
+ high = Math.max(high, hi);
1144
+ for (let i = c; i < out.length; i += 4)
1145
+ out[i] = f(s.data[i]);
1146
+ }
1147
+ if (flat)
1148
+ ctx.warn(`${type}: ${flat === 3 ? 'every channel' : `${flat} channel${flat > 1 ? 's' : ''}`} of the image ${flat > 1 ? 'are' : 'is'} flat; ${flat > 1 ? 'they are' : 'it is'} set to 0.5`);
1149
+ ctx.stat('range_min', low);
1150
+ ctx.stat('range_max', high);
1151
+ }
1152
+ else {
1153
+ const [lo, hi] = valueRange(s.data, s.ch, p.clip);
1154
+ if (!(hi > lo))
1155
+ ctx.warn(`${type}: the image is flat (every value ${lo.toFixed(4)}); it is set to 0.5`);
1156
+ ctx.stat('range_min', lo);
1157
+ ctx.stat('range_max', hi);
1158
+ out = mapValues(s.data, s.ch, stretch(lo, hi));
1159
+ }
1160
+ if (p.clip > 0)
1161
+ out = mapValues(out, s.ch, (x) => (x < 0 ? 0 : x > 1 ? 1 : x));
1162
+ return withLayer(s, out, outName(ctx));
1163
+ },
1164
+ });
1165
+ defineNode({
1166
+ type: 'tex_clamp',
1167
+ usesNodeName: NAMED_BY_NODE,
1168
+ category: 'texture',
1169
+ summary: 'Clamp values to a range (default 0..1): cut overshoots after add, subtract or levels without clamping.',
1170
+ description: 'Substance: Clamp; Houdini COP: Clamp. Every value below min becomes min and above max becomes max (grey or RGB; alpha untouched). Unclamped blends and levels, SDF images and heights can run outside 0..1; PNGs clamp anyway, a material input may not.',
1171
+ aliases: ['clamp_texture', 'cop_clamp', 'clamp_values'],
1172
+ inputs: FILTER_INPUT,
1173
+ params: {
1174
+ min: { type: 'float', default: 0, desc: 'lowest value kept', aliases: ['low', 'minimum'] },
1175
+ max: { type: 'float', default: 1, desc: 'highest value kept', aliases: ['high', 'maximum'] },
1176
+ image: imageParam(), layer: layerParam(), name: renameParam(),
1177
+ },
1178
+ example: {
1179
+ nodes: {
1180
+ n: { type: 'tex_noise', params: { resolution: 256 } },
1181
+ out: { type: 'tex_clamp', in: ['n'], params: { min: 0.3, max: 0.7 } },
1182
+ },
1183
+ output: 'out',
1184
+ },
1185
+ cook: (ctx) => {
1186
+ const { p, type } = ctx;
1187
+ if (p.min > p.max)
1188
+ throw new NodeError(`${type}: min (${p.min}) is above max (${p.max})`, 'swap them; to invert an image use tex_invert');
1189
+ const s = source(ctx, 0, p.image, p.layer);
1190
+ return withLayer(s, mapValues(s.data, s.ch, (x) => (x < p.min ? p.min : x > p.max ? p.max : x)), outName(ctx));
1191
+ },
1192
+ });
1193
+ defineNode({
1194
+ type: 'tex_quantize',
1195
+ usesNodeName: NAMED_BY_NODE,
1196
+ category: 'texture',
1197
+ summary: 'Quantize (posterize): reduce the values to a few even levels: terraces, stepped masks, toon bands, palette ids.',
1198
+ description: 'Substance: Quantize / Posterize; Houdini COP: Quantize. levels evenly spaced values 0 … 1 (2 = black and white). round snaps every value to the nearest level; floor cuts 0..1 into `levels` equal bands (posterize: as many pixels per band as the input has in that range). Grey or RGB per channel (alpha untouched).',
1199
+ aliases: ['quantize', 'posterize', 'cop_quantize', 'quantize_grayscale', 'posterize_texture', 'steps_texture'],
1200
+ inputs: FILTER_INPUT,
1201
+ params: {
1202
+ levels: { type: 'int', default: 4, min: 2, max: 256, desc: 'number of output values', aliases: ['steps', 'count'] },
1203
+ mode: { type: 'enum', options: QUANTIZE_MODES, default: 'round', desc: 'round = nearest level, floor = equal bands (posterize)', aliases: ['method', 'type'] },
1204
+ image: imageParam(), layer: layerParam(), name: renameParam(),
1205
+ },
1206
+ example: {
1207
+ nodes: {
1208
+ n: { type: 'tex_noise', params: { resolution: 256 } },
1209
+ out: { type: 'tex_quantize', in: ['n'], params: { levels: 5 } },
1210
+ },
1211
+ output: 'out',
1212
+ },
1213
+ cook: (ctx) => {
1214
+ const { p } = ctx;
1215
+ const s = source(ctx, 0, p.image, p.layer);
1216
+ return withLayer(s, mapValues(s.data, s.ch, quantizeFn(p.levels, p.mode)), outName(ctx));
717
1217
  },
718
1218
  });
719
1219
  defineNode({
720
1220
  type: 'tex_normal_from_height',
1221
+ usesNodeName: NAMED_BY_NODE,
721
1222
  category: 'texture',
722
- summary: 'Normal map from a height image (Sobel): tangent-space RGBA, OpenGL (+Y up) or DirectX (Y down).',
723
- description: 'Substance: Normal (from height); Houdini COP: Bump to Normal. strength 1 tilts the normal 45° where the height rises by 1 over 1/64 of the image width (the same look at any resolution). A flat image gives (0.5, 0.5, 1). glTF and Blender use OpenGL; Unreal uses DirectX (or flip green on import).',
1223
+ renamed: { strength: 'it is now depth, the relief in metres for a height of 1, with size, the texture\'s width in metres (strength k matches depth k/64 with size 1)' },
1224
+ summary: 'Normal map from a height image (Sobel) in physical units (relief depth and texture size in metres): tangent-space RGBA, OpenGL (+Y up) or DirectX (Y down).',
1225
+ description: 'Substance: Normal (from height); Houdini COP: Bump to Normal. The slope is real: a value of 1 stands `depth` metres ' +
1226
+ 'high and the image spans `size` metres on the model, so one texel is size / width metres and the normal tilts by ' +
1227
+ 'atan(height step × depth / texel size). The same graph gives the same normals at any resolution, and a value you ' +
1228
+ 'can measure picks the strength: 0.0003 for paint and cast grain, 0.002 for hammered metal, 0.01 to 0.02 for brick ' +
1229
+ 'and mortar. For bake_height\'s "distance" layer (metres already) use depth 1 and the size the uv square covers. ' +
1230
+ 'Steps narrower than a texel (hard pattern edges, thresholds) stay steeper at higher resolutions, as a finer step is ' +
1231
+ 'physically steeper; give them a bevel or blur them in uv units. A flat image gives (0.5, 0.5, 1). glTF and Blender ' +
1232
+ 'use OpenGL; Unreal uses DirectX (or flip green on import). Combine with another normal map in tex_normal_blend.',
724
1233
  aliases: ['normal_from_height', 'height_to_normal', 'normal_map', 'bump_to_normal', 'cop_bumptonormal'],
725
1234
  inputs: FILTER_INPUT,
726
1235
  params: {
727
- strength: { type: 'float', default: 1, desc: 'slope scale (negative inverts the relief)', aliases: ['intensity', 'height_scale'] },
1236
+ depth: { type: 'float', default: 0.01, desc: 'relief: metres a height value of 1 stands above 0 (negative inverts the relief)', aliases: ['height', 'height_scale', 'bump_depth', 'relief'] },
1237
+ size: { type: 'float', default: 1, min: 1e-6, desc: 'metres the image width covers on the model (the texel size is size / width)', aliases: ['texture_size', 'world_size', 'tile_size'] },
728
1238
  format: { type: 'enum', options: ['opengl', 'directx'], default: 'opengl', desc: 'green channel convention', aliases: ['convention'] },
729
1239
  tileable: tileParam(),
730
1240
  image: imageParam(), layer: layerParam(), name: renameParam(),
@@ -732,18 +1242,215 @@ defineNode({
732
1242
  example: {
733
1243
  nodes: {
734
1244
  bricks: { type: 'tex_pattern', params: { resolution: 256 } },
735
- out: { type: 'tex_normal_from_height', in: ['bricks'], params: { strength: 3, name: 'brick_normal' } },
1245
+ brick_normal: { type: 'tex_normal_from_height', in: ['bricks'], params: { depth: 0.015, size: 1 } },
736
1246
  },
737
- output: 'out',
1247
+ output: 'brick_normal',
738
1248
  },
739
1249
  cook: (ctx) => {
740
1250
  const { p } = ctx;
741
1251
  const s = source(ctx, 0, p.image, p.layer);
742
- return withLayer(s, normalFromHeight(toGrey(s.data, s.ch), s.img.width, s.img.height, p.strength, p.format === 'directx', !!p.tileable), p.name);
1252
+ return withLayer(s, normalFromHeight(toGrey(s.data, s.ch), s.img.width, s.img.height, p.depth, p.size, p.format === 'directx', !!p.tileable), outName(ctx));
1253
+ },
1254
+ });
1255
+ defineNode({
1256
+ type: 'tex_normal_blend',
1257
+ usesNodeName: NAMED_BY_NODE,
1258
+ category: 'texture',
1259
+ summary: 'Combine two normal maps: a detail (micro grain, a tiling pattern) over a base (a baked normal map), reoriented (RNM) by default, with strength and an optional mask.',
1260
+ description: 'Substance: Normal Combine / Normal Blend; Unreal: BlendAngleCorrectedNormals. The detail\'s tilt is scaled by ' +
1261
+ 'strength (0 = no detail, 2 = twice as steep), then: rnm (reoriented normal mapping) rotates the detail onto the ' +
1262
+ 'base normal, so the baked shapes and the detail both keep their depth; udn adds the detail\'s x and y to the base ' +
1263
+ '(cheaper, flattens strong detail on steep base slopes); linear normalises the sum (softens both, even the base). ' +
1264
+ 'The mask (input 2, grey) fades from the base where it is 0 to the blend where it is 1. The detail and mask are ' +
1265
+ 'resized to the base; the base\'s alpha is kept. Both maps must use the same green convention (OpenGL or DirectX). ' +
1266
+ 'tex_blend overlay is no substitute: it flattens and skews normal maps.',
1267
+ aliases: ['normal_blend', 'blend_normals', 'normal_combine', 'rnm', 'detail_normal', 'combine_normals'],
1268
+ inputs: [
1269
+ { name: 'base', desc: 'base normal map (RGBA; its geometry passes through)' },
1270
+ { name: 'detail', desc: 'detail normal map (RGBA) laid over the base' },
1271
+ { name: 'mask', desc: 'grey mask: where the detail applies (optional)', optional: true },
1272
+ ],
1273
+ params: {
1274
+ mode: { type: 'enum', options: NORMAL_BLEND_MODES, default: 'rnm', desc: 'rnm = reoriented (keeps both reliefs), udn = add x and y (cheaper), linear = normalised sum (softens both)', aliases: ['method', 'blend_mode'] },
1275
+ strength: { type: 'float', default: 1, min: 0, desc: 'detail tilt multiplier (0 = base only, 1 = as baked, 2 = twice as steep)', aliases: ['intensity', 'detail_strength', 'amount'] },
1276
+ image: imageParam('input 0 (the base)'), layer: layerParam(),
1277
+ detail_image: imageParam('input 1 (the detail)', []),
1278
+ detail_layer: { type: 'string', default: '', desc: 'layer of the detail ("" = main)' },
1279
+ mask_image: imageParam('input 2 (the mask)', []),
1280
+ mask_layer: { type: 'string', default: '', desc: 'layer of the mask ("" = main)' },
1281
+ tileable: tileParam('resizing the detail and mask wraps at the borders'),
1282
+ name: renameParam(),
1283
+ },
1284
+ outputs: 'the base image with the combined normal map (RGBA), named <name> (default: the node name)',
1285
+ example: {
1286
+ nodes: {
1287
+ bricks: { type: 'tex_pattern', params: { resolution: 256, count: [4, 8] } },
1288
+ base: { type: 'tex_normal_from_height', in: ['bricks'], params: { depth: 0.015 } },
1289
+ grain: { type: 'tex_noise', params: { resolution: 256, scale: 40, octaves: 3 } },
1290
+ detail: { type: 'tex_normal_from_height', in: ['grain'], params: { depth: 0.0004 } },
1291
+ out: { type: 'tex_normal_blend', in: ['base', 'detail'], params: { mode: 'rnm', strength: 1 } },
1292
+ },
1293
+ output: 'out',
1294
+ },
1295
+ cook: (ctx) => {
1296
+ const { p, type } = ctx;
1297
+ const A = source(ctx, 0, p.image, p.layer);
1298
+ const w = A.img.width, h = A.img.height, wrap = !!p.tileable;
1299
+ const B = sourceAt(ctx, 1, w, h, p.detail_image, p.detail_layer, wrap, 'detail_image');
1300
+ if (!B)
1301
+ throw new NodeError(`${type}: connect a detail normal map to input 1`);
1302
+ const rgba = 'normal maps are RGBA images (tex_normal_from_height, bake_normal, image_file of a normal map)';
1303
+ if (A.ch !== 4)
1304
+ throw new NodeError(`${type}: the base "${A.img.name}" is a grey image, not a normal map`, rgba);
1305
+ if (B.ch !== 4)
1306
+ throw new NodeError(`${type}: the detail on input 1 is a grey image, not a normal map`, `${rgba}; turn a height into one with tex_normal_from_height`);
1307
+ const M = sourceAt(ctx, 2, w, h, p.mask_image, p.mask_layer, wrap, 'mask_image');
1308
+ return withLayer(A, blendNormals(A.data, B.data, M ? toGrey(M.data, M.ch) : null, p.mode, Math.max(0, p.strength)), outName(ctx));
1309
+ },
1310
+ });
1311
+ defineNode({
1312
+ type: 'tex_normal_normalize',
1313
+ usesNodeName: NAMED_BY_NODE,
1314
+ category: 'texture',
1315
+ summary: 'Normalize a normal map: scale every vector back to unit length after blurs, resizes, blends or hand edits.',
1316
+ description: 'Substance: Normal Normalize. Blurring, resizing, tex_blend or levels on a normal map leave vectors shorter than 1 (flatter shading, wrong reflections); this rescales each to length 1 and lifts any below the surface (z < 0) to it. Alpha is kept. A grey input is an error: it is not a normal map.',
1317
+ aliases: ['normal_normalize', 'normalize_normal', 'renormalize_normals'],
1318
+ inputs: FILTER_INPUT,
1319
+ params: { image: imageParam(), layer: layerParam(), name: renameParam() },
1320
+ example: {
1321
+ nodes: {
1322
+ bricks: { type: 'tex_pattern', params: { resolution: 256 } },
1323
+ n: { type: 'tex_normal_from_height', in: ['bricks'], params: { depth: 0.015 } },
1324
+ soft: { type: 'tex_blur', in: ['n'], params: { radius: 3 } },
1325
+ out: { type: 'tex_normal_normalize', in: ['soft'] },
1326
+ },
1327
+ output: 'out',
1328
+ },
1329
+ cook: (ctx) => {
1330
+ const { p } = ctx;
1331
+ const s = normalSource(ctx, source(ctx, 0, p.image, p.layer));
1332
+ return withLayer(s, normalizeNormals(s.data), outName(ctx));
1333
+ },
1334
+ });
1335
+ defineNode({
1336
+ type: 'tex_normal_invert',
1337
+ usesNodeName: NAMED_BY_NODE,
1338
+ category: 'texture',
1339
+ summary: 'Invert a normal map\'s green (OpenGL ↔ DirectX) or red channel, or both (turn the relief inside out).',
1340
+ description: 'Substance: Normal Invert. green flips the Y convention: OpenGL (glTF, Blender, TopoTopo) ↔ DirectX (Unreal), the usual fix for normal maps lit from below. red flips X; both inverts the relief (bumps become dents). Alpha is kept.',
1341
+ aliases: ['normal_invert', 'invert_normal', 'flip_green', 'normal_flip', 'directx_to_opengl'],
1342
+ inputs: FILTER_INPUT,
1343
+ params: {
1344
+ channel: { type: 'enum', options: ['green', 'red', 'both'], default: 'green', desc: 'channel(s) to flip (green = OpenGL ↔ DirectX)', aliases: ['flip', 'axis'] },
1345
+ image: imageParam(), layer: layerParam(), name: renameParam(),
1346
+ },
1347
+ example: {
1348
+ nodes: {
1349
+ bricks: { type: 'tex_pattern', params: { resolution: 256 } },
1350
+ gl: { type: 'tex_normal_from_height', in: ['bricks'], params: { depth: 0.015 } },
1351
+ dx: { type: 'tex_normal_invert', in: ['gl'], params: { channel: 'green' } },
1352
+ },
1353
+ output: 'dx',
1354
+ },
1355
+ cook: (ctx) => {
1356
+ const { p } = ctx;
1357
+ const s = normalSource(ctx, source(ctx, 0, p.image, p.layer));
1358
+ return withLayer(s, flipNormals(s.data, p.channel !== 'green', p.channel !== 'red'), outName(ctx));
1359
+ },
1360
+ });
1361
+ defineNode({
1362
+ type: 'tex_height_from_normal',
1363
+ usesNodeName: NAMED_BY_NODE,
1364
+ category: 'texture',
1365
+ summary: 'Height from a normal map: integrate its slopes back into a height in physical units (the inverse of tex_normal_from_height).',
1366
+ description: 'Substance: Normal to Height; Houdini COP: Normal to Height. The slopes of the normals are integrated by solving a ' +
1367
+ 'Poisson equation over the whole image (FFT when tileable, else with mirrored borders), so the height is the one ' +
1368
+ 'whose normal map best matches, in metres of an image `size` metres wide: tex_normal_from_height {depth, size} ' +
1369
+ 'then this node with the same depth and size gives the height back (up to an offset). range depth writes (height − ' +
1370
+ 'lowest) / depth (0 at the lowest point; a relief deeper than depth runs past 1); normalize fits lowest..highest to ' +
1371
+ '0..1. The stat relief is the height range in metres. Use it for AO and curvature from a baked or downloaded normal ' +
1372
+ 'map, or to blend normals as heights.',
1373
+ aliases: ['height_from_normal', 'normal_to_height', 'normal_integrate', 'cop_normaltoheight'],
1374
+ inputs: FILTER_INPUT,
1375
+ params: {
1376
+ depth: { type: 'float', default: 0.01, min: 1e-9, desc: 'metres a height value of 1 stands for', aliases: ['height', 'height_scale', 'relief'] },
1377
+ size: { type: 'float', default: 1, min: 1e-6, desc: 'metres the image width covers on the model (the texel size is size / width)', aliases: ['texture_size', 'world_size', 'tile_size'] },
1378
+ format: { type: 'enum', options: ['opengl', 'directx'], default: 'opengl', desc: 'green channel convention of the input', aliases: ['convention'] },
1379
+ range: { type: 'enum', options: ['depth', 'normalize'], default: 'depth', desc: 'depth = (height − lowest) / depth; normalize = lowest..highest to 0..1', aliases: ['fit'] },
1380
+ tileable: tileParam('the normal map tiles (integrated as periodic)'),
1381
+ image: imageParam(), layer: layerParam(), name: renameParam(),
1382
+ },
1383
+ outputs: 'the height (grey) named <name> (default: the node name); stat relief (metres)',
1384
+ example: {
1385
+ nodes: {
1386
+ bumps: { type: 'tex_noise', params: { resolution: 256, scale: 6, octaves: 3 } },
1387
+ n: { type: 'tex_normal_from_height', in: ['bumps'], params: { depth: 0.02 } },
1388
+ back: { type: 'tex_height_from_normal', in: ['n'], params: { depth: 0.02 } },
1389
+ },
1390
+ output: 'back',
1391
+ },
1392
+ cook: (ctx) => {
1393
+ const { p } = ctx;
1394
+ const s = normalSource(ctx, source(ctx, 0, p.image, p.layer));
1395
+ const w = s.img.width, h = s.img.height;
1396
+ const hm = heightFromNormal(s.data, w, h, p.size / w, p.format === 'directx', !!p.tileable);
1397
+ let lo = Infinity, hi = -Infinity;
1398
+ for (let k = 0; k < hm.length; k++) {
1399
+ if (hm[k] < lo)
1400
+ lo = hm[k];
1401
+ if (hm[k] > hi)
1402
+ hi = hm[k];
1403
+ }
1404
+ ctx.stat('relief', hi - lo);
1405
+ const span = p.range === 'normalize' ? hi - lo : p.depth, out = new Float32Array(hm.length);
1406
+ for (let k = 0; k < hm.length; k++)
1407
+ out[k] = span > 0 ? (hm[k] - lo) / span : 0;
1408
+ return withLayer(s, out, outName(ctx));
1409
+ },
1410
+ });
1411
+ defineNode({
1412
+ type: 'tex_curvature',
1413
+ usesNodeName: NAMED_BY_NODE,
1414
+ category: 'texture',
1415
+ summary: 'Curvature from a normal map in physical units: 0.5 flat, bright on convex edges and bumps, dark in creases; layers convex and concave.',
1416
+ description: 'Substance: Curvature / Curvature Smooth; Houdini COP: Curvature. The mean curvature (the divergence of the ' +
1417
+ 'normals, in 1/metres of an image `size` metres wide): C = 0.5 + 0.5 × curvature × radius, so bends of radius ' +
1418
+ '`radius` metres or tighter read full white (convex) or black (concave), the same at any resolution. blur (metres) ' +
1419
+ 'smooths the normals first to measure broader curvature (Curvature Smooth). Layers convex and concave hold the two ' +
1420
+ 'sides 0..1, like bake_curvature: tex_output {layer: "convex"} → tex_histogram_scan gives edge wear, concave gives ' +
1421
+ 'dirt. Needs a normal map (tex_normal_from_height of a height, bake_normal).',
1422
+ aliases: ['curvature_texture', 'curvature_from_normal', 'normal_to_curvature', 'curvature_smooth', 'cop_curvature'],
1423
+ inputs: [{ name: 'normal', desc: 'geometry holding a tangent-space normal map (RGBA); everything else passes through' }],
1424
+ params: {
1425
+ radius: { type: 'float', default: 0.02, min: 1e-6, desc: 'bend radius in metres that reads full white / black (larger = more contrast)', aliases: ['range', 'intensity'] },
1426
+ blur: { type: 'float', default: 0, min: 0, desc: 'smooth the normals over this many metres first (broader curvature)', aliases: ['smooth', 'smoothing'] },
1427
+ format: { type: 'enum', options: ['opengl', 'directx'], default: 'opengl', desc: 'green channel convention of the normal map', aliases: ['convention'] },
1428
+ size: sizeParam(),
1429
+ tileable: tileParam(),
1430
+ image: imageParam(), layer: layerParam(), name: renameParam(),
1431
+ },
1432
+ outputs: 'the curvature (grey, 0.5 = flat) named <name> (default: the node name); layers convex and concave (0..1)',
1433
+ example: {
1434
+ nodes: {
1435
+ plates: { type: 'tex_pattern', params: { resolution: 256, pattern: 'tiles', count: [4, 4], bevel: 0.1 } },
1436
+ n: { type: 'tex_normal_from_height', in: ['plates'], params: { depth: 0.01 } },
1437
+ out: { type: 'tex_curvature', in: ['n'], params: { radius: 0.02 } },
1438
+ },
1439
+ output: 'out',
1440
+ },
1441
+ cook: (ctx) => {
1442
+ const { p } = ctx;
1443
+ const s = normalSource(ctx, source(ctx, 0, p.image, p.layer));
1444
+ const w = s.img.width, h = s.img.height, texel = p.size / w;
1445
+ // a blur wider than the image changes nothing more (and the box passes' tables grow with the radius)
1446
+ const N = p.blur > 0 ? blurLayer(s.data, 4, w, h, Math.min(p.blur / texel, 2 * Math.max(w, h)), 'gaussian', !!p.tileable) : s.data;
1447
+ const r = curvatureFromNormal(N, w, h, texel, p.radius, p.format === 'directx', !!p.tileable);
1448
+ return withLayer(s, r.C, outName(ctx), { convex: r.convex, concave: r.concave });
743
1449
  },
744
1450
  });
745
1451
  defineNode({
746
1452
  type: 'tex_height_to_ao',
1453
+ usesNodeName: NAMED_BY_NODE,
747
1454
  category: 'texture',
748
1455
  summary: 'Ambient occlusion of a height image (horizon based): white = open, dark in pits, gaps and mortar.',
749
1456
  description: 'Substance: Ambient Occlusion (HBAO). For each pixel, `directions` rays march `steps` samples up to radius (a fraction of the image width) and keep the highest horizon; depth sets how tall a height of 1 is (in image widths).',
@@ -767,14 +1474,54 @@ defineNode({
767
1474
  cook: (ctx) => {
768
1475
  const { p } = ctx;
769
1476
  const s = source(ctx, 0, p.image, p.layer);
770
- return withLayer(s, heightToAO(toGrey(s.data, s.ch), s.img.width, s.img.height, p.radius, p.depth, p.directions, p.steps, !!p.tileable), p.name);
1477
+ return withLayer(s, heightToAO(toGrey(s.data, s.ch), s.img.width, s.img.height, p.radius, p.depth, p.directions, p.steps, !!p.tileable), outName(ctx));
1478
+ },
1479
+ });
1480
+ defineNode({
1481
+ type: 'tex_ao',
1482
+ usesNodeName: NAMED_BY_NODE,
1483
+ category: 'texture',
1484
+ summary: 'Ambient occlusion of a height image in physical units (ground-truth style, cosine-weighted): 1 on any plane, dark in pits, gaps and at the foot of walls; the same at any resolution.',
1485
+ description: 'Substance: Ambient Occlusion (RTAO / HBAO); Houdini COP: Ambient Occlusion. A value of 1 stands `depth` metres ' +
1486
+ 'high on an image `size` metres wide (as in tex_normal_from_height), and the search reaches `radius` metres: ' +
1487
+ 'for each of `directions` slices through a pixel the highest horizon on both sides is found from bilinear samples ' +
1488
+ '(closer together near the pixel, fading out over the last 40 % of the radius) and the cosine-weighted sky between ' +
1489
+ 'them is integrated exactly. Unlike tex_height_to_ao (image-width units, nearest samples, any slope reads as ' +
1490
+ 'shadow) a tilted plane stays white and the result does not change with the resolution. strength scales the ' +
1491
+ 'darkening (1 = as measured). More directions and steps = smoother, slower.',
1492
+ aliases: ['ao_texture', 'gtao', 'height_ao', 'ambient_occlusion_texture', 'cop_ambientocclusion'],
1493
+ inputs: FILTER_INPUT,
1494
+ params: {
1495
+ radius: { type: 'float', default: 0.05, min: 1e-6, desc: 'how far occluders count, in metres', aliases: ['distance', 'search_radius'] },
1496
+ depth: { type: 'float', default: 0.01, min: 0, desc: 'metres a height value of 1 stands', aliases: ['height', 'height_scale', 'relief'] },
1497
+ directions: { type: 'int', default: 8, min: 1, max: 32, desc: 'slices per pixel (each looks both ways)', aliases: ['dirs', 'slices'] },
1498
+ steps: { type: 'int', default: 8, min: 1, max: 32, desc: 'samples along each way' },
1499
+ strength: { type: 'float', default: 1, min: 0, max: 4, desc: 'darkening multiplier (0 = none, 1 = as measured)', aliases: ['intensity', 'amount'] },
1500
+ size: sizeParam(),
1501
+ tileable: tileParam(),
1502
+ image: imageParam(), layer: layerParam(), name: renameParam(),
1503
+ },
1504
+ example: {
1505
+ nodes: {
1506
+ bricks: { type: 'tex_pattern', params: { resolution: 256, bevel: 0.1 } },
1507
+ out: { type: 'tex_ao', in: ['bricks'], params: { radius: 0.04, depth: 0.015, name: 'brick_ao' } },
1508
+ },
1509
+ output: 'out',
1510
+ },
1511
+ cook: (ctx) => {
1512
+ const { p } = ctx;
1513
+ const s = source(ctx, 0, p.image, p.layer);
1514
+ const w = s.img.width, h = s.img.height;
1515
+ const ao = heightAO(toGrey(s.data, s.ch), w, h, { texel: p.size / w, depth: p.depth, radius: p.radius, directions: p.directions, steps: p.steps, strength: p.strength, wrap: !!p.tileable });
1516
+ return withLayer(s, ao, outName(ctx));
771
1517
  },
772
1518
  });
773
1519
  defineNode({
774
1520
  type: 'tex_channel',
1521
+ usesNodeName: NAMED_BY_NODE,
775
1522
  category: 'texture',
776
1523
  summary: 'Pack grey images into the R, G, B, A channels of one RGBA image (e.g. ORM for glTF/Unreal: occlusion, roughness, metallic), or extract one channel as grey.',
777
- description: 'Substance: RGBA Merge / RGBA Split / Channel Shuffle; Houdini COP: Channel Copy. pack: inputs 0..3 fill R, G, B, A (their luminance); unconnected channels take fill (default [1, 0.5, 0, 1]: occlusion 1, roughness 0.5, metallic 0, alpha 1, the ORM convention of glTF and Unreal). The size is the first connected input\'s; others are resized. extract: one channel of input 0 as a grey image (keeps the input, replacing the layer).',
1524
+ description: 'Substance: RGBA Merge / RGBA Split / Channel Shuffle; Houdini COP: Channel Copy. pack: inputs 0..3 fill R, G, B, A (their luminance; each input holds one image); unconnected channels take fill (default [1, 0.5, 0, 1]: occlusion 1, roughness 0.5, metallic 0, alpha 1, the ORM convention of glTF and Unreal). The size is the first connected input\'s; others are resized. extract: one channel of an image of input 0 as a grey image (keeps the input, replacing the layer).',
778
1525
  aliases: ['channel_pack', 'pack_channels', 'rgba_merge', 'rgba_split', 'channel_shuffle', 'orm_pack', 'cop_channelcopy'],
779
1526
  inputs: [
780
1527
  { name: 'r', desc: 'red source (pack) or the image to split (extract)', optional: true },
@@ -786,21 +1533,22 @@ defineNode({
786
1533
  mode: { type: 'enum', options: ['pack', 'extract'], default: 'pack', desc: 'pack inputs into RGBA, or extract a channel of input 0' },
787
1534
  channel: { type: 'enum', options: ['r', 'g', 'b', 'a', 'luminance'], default: 'r', desc: 'extract: which channel' },
788
1535
  fill: { type: 'vec4', default: [1, 0.5, 0, 1], desc: 'pack: values of unconnected channels' },
789
- name: nameParam('', 'pack: the new image\'s name ("" = "packed"); extract: rename the result ("" = keep)'),
1536
+ image: imageParam('input 0 (extract)'),
1537
+ name: nameParam('pack: the new image\'s name, extract: the result\'s ("" = this node\'s name)'),
790
1538
  },
791
- outputs: 'pack: a new RGBA image <name> (default "packed"); extract: input 0 with the channel as its layer',
1539
+ outputs: 'pack: a new RGBA image <name> (default: the node name); extract: input 0 with the channel as its layer, renamed <name>',
792
1540
  example: {
793
1541
  nodes: {
794
1542
  ao: { type: 'tex_noise', params: { resolution: 256, scale: 3 } },
795
1543
  rough: { type: 'tex_cells', params: { resolution: 256 } },
796
- orm: { type: 'tex_channel', in: ['ao', 'rough'], params: { name: 'orm', fill: [1, 0.5, 0, 1] } },
1544
+ orm: { type: 'tex_channel', in: ['ao', 'rough'], params: { fill: [1, 0.5, 0, 1] } },
797
1545
  },
798
1546
  output: 'orm',
799
1547
  },
800
1548
  cook: (ctx) => {
801
1549
  const { p, type } = ctx;
802
1550
  if (p.mode === 'extract') {
803
- const s = source(ctx, 0);
1551
+ const s = source(ctx, 0, p.image);
804
1552
  const k = ['r', 'g', 'b', 'a'].indexOf(p.channel);
805
1553
  const n = s.img.count, out = new Float32Array(n);
806
1554
  if (s.ch === 1)
@@ -810,12 +1558,12 @@ defineNode({
810
1558
  else
811
1559
  for (let i = 0; i < n; i++)
812
1560
  out[i] = s.data[i * 4 + k];
813
- return withLayer(s, out, p.name);
1561
+ return withLayer(s, out, outName(ctx));
814
1562
  }
815
1563
  const first = [0, 1, 2, 3].find((i) => ctx.hasInput(i));
816
1564
  if (first === undefined)
817
1565
  throw new NodeError(`${type}: connect at least one input (R, G, B or A)`);
818
- const ref = source(ctx, first);
1566
+ const ref = source(ctx, first, '', '', '');
819
1567
  const w = ref.img.width, h = ref.img.height, n = w * h;
820
1568
  const out = new Float32Array(n * 4);
821
1569
  for (let c = 0; c < 4; c++) {
@@ -824,11 +1572,12 @@ defineNode({
824
1572
  for (let i = 0; i < n; i++)
825
1573
  out[i * 4 + c] = g ? g[i] : p.fill[c];
826
1574
  }
827
- return imageGeo(new Image(w, h, imgName(p, 'packed')).set(MAIN_LAYER, out));
1575
+ return imageGeo(new Image(w, h, outName(ctx)).set(MAIN_LAYER, out));
828
1576
  },
829
1577
  });
830
1578
  defineNode({
831
1579
  type: 'tex_colorize',
1580
+ usesNodeName: NAMED_BY_NODE,
832
1581
  category: 'texture',
833
1582
  summary: 'Colorize: map a grey image through a colour ramp (gradient map) into RGBA.',
834
1583
  description: 'Substance: Gradient Map; Houdini COP: Ramp lookup. ramp keys [[pos, colour], …] with colours as [r, g, b] or "#hex"; the image holds those numbers as they are, so a "#a5462e" key comes out of the PNG as #a5462e. RGBA input uses its luminance.',
@@ -843,18 +1592,30 @@ defineNode({
843
1592
  const { p } = ctx;
844
1593
  const s = source(ctx, 0, p.image, p.layer);
845
1594
  const { lut, ch } = rampLUT((t) => evalRamp(p.ramp, t));
846
- return withLayer(s, colorize(toGrey(s.data, s.ch), lut, ch), p.name);
1595
+ return withLayer(s, colorize(toGrey(s.data, s.ch), lut, ch), outName(ctx));
847
1596
  },
848
1597
  });
849
1598
  defineNode({
850
1599
  type: 'tex_tile_sampler',
1600
+ usesNodeName: NAMED_BY_NODE,
851
1601
  category: 'texture',
852
- summary: 'Tile sampler: scatter an image (a shape, a brick, a pebble) N × M times with random offset, rotation, scale and intensity; optional mask.',
853
- description: 'Substance: Tile Sampler / Splatter Circular. One instance per grid cell: position jitter (fraction of a cell), rotation ± degrees, scale range relative to a cell, intensity range; with a mask (input 1), a cell keeps its instance with probability mask(cell centre). Instances wrap at the borders (tileable) and combine with max or add. Output grey (the source\'s luminance).',
1602
+ summary: 'Tile sampler: scatter an image (a shape, a brick, a pebble; or several, picked at random) N × M times with random offset, rotation, scale and intensity; masks and per-instance maps; grey, id or colour output.',
1603
+ description: 'Substance: Tile Sampler / Splatter Circular. One instance per grid cell: position jitter (fraction of a cell), ' +
1604
+ 'rotation ± degrees, scale range relative to a cell, intensity range. With a mask (input 1) a cell keeps its ' +
1605
+ 'instance with probability mask(cell centre). The maps on inputs 2–4 are read at each instance\'s centre: scale ' +
1606
+ 'map × scale, rotation map × 360° added to the rotation, intensity map × intensity (bigger stones where a gradient ' +
1607
+ 'is bright, scales that follow a flow, studs that fade out). stamps random uses every image in input 0 and picks one ' +
1608
+ 'per instance (several pebbles, leaves, bolts). Instances wrap at the borders when tileable and combine with max or ' +
1609
+ 'add. output grey is the stamps\' luminance; id gives each instance a flat random 0..1 and color a random RGB (alpha = ' +
1610
+ 'the stamps), both taken from the strongest instance at a pixel, with the grey stamps in layer "mask" (tex_colorize ' +
1611
+ 'an id for a palette, or tex_blend a colour over a base: its alpha masks it).',
854
1612
  aliases: ['tile_sampler', 'tilesampler', 'scatter_texture', 'stamp_scatter'],
855
1613
  inputs: [
856
- { name: 'pattern', desc: 'image to scatter (e.g. tex_shape)' },
1614
+ { name: 'pattern', desc: 'image to scatter (e.g. tex_shape); with stamps random, every image here' },
857
1615
  { name: 'mask', desc: 'grey mask: probability of a cell keeping its instance', optional: true },
1616
+ { name: 'scale_map', desc: 'grey: multiplies each instance\'s scale (read at its centre)', optional: true },
1617
+ { name: 'rotation_map', desc: 'grey: 0..1 adds 0..360° to each instance\'s rotation', optional: true },
1618
+ { name: 'intensity_map', desc: 'grey: multiplies each instance\'s intensity', optional: true },
858
1619
  ],
859
1620
  params: {
860
1621
  resolution: resolutionParam(),
@@ -865,11 +1626,18 @@ defineNode({
865
1626
  offset: { type: 'float', default: 0, min: 0, max: 1, desc: 'shift of every other row (fraction of a cell)' },
866
1627
  intensity: { type: 'vec2', default: [0.6, 1], min: 0, desc: 'intensity range per instance', aliases: ['luminance_random'] },
867
1628
  combine: { type: 'enum', options: ['max', 'add'], default: 'max', desc: 'how overlapping instances combine', aliases: ['blend'] },
1629
+ output: { type: 'enum', options: TILE_SAMPLER_OUTPUTS, default: 'grey', desc: 'grey = the stamps; id = a random grey per instance; color = a random colour per instance (alpha = the stamps)', aliases: ['mode', 'output_type'] },
1630
+ stamps: { type: 'enum', options: ['one', 'random'], default: 'one', desc: 'one = the image picked by image; random = every image of input 0, one at random per instance', aliases: ['pattern_input', 'pattern_select'] },
1631
+ tileable: tileParam('instances wrap at the borders (the result tiles)'),
868
1632
  seed: P.seed(),
869
- image: imageParam(), layer: layerParam(),
870
- name: nameParam('tiles'),
871
- },
872
- outputs: 'a new image <name>: C grey',
1633
+ image: imageParam('input 0 (the pattern)'), layer: layerParam(),
1634
+ mask_image: imageParam('input 1 (the mask)', []),
1635
+ scale_map_image: imageParam('input 2 (the scale map)', []),
1636
+ rotation_map_image: imageParam('input 3 (the rotation map)', []),
1637
+ intensity_map_image: imageParam('input 4 (the intensity map)', []),
1638
+ name: nameParam(),
1639
+ },
1640
+ outputs: 'a new image <name> (default: the node name): C grey (or the id grey, or the RGBA colour); mask grey (the stamps; id and color only)',
873
1641
  example: {
874
1642
  nodes: {
875
1643
  stamp: { type: 'tex_shape', params: { resolution: 128, shape: 'disc', falloff: 0.6 } },
@@ -880,41 +1648,386 @@ defineNode({
880
1648
  cook: (ctx) => {
881
1649
  const { p, type } = ctx;
882
1650
  const [w, h] = size2(p, type);
883
- const s = source(ctx, 0, p.image, p.layer);
884
- const m = sourceAt(ctx, 1, w, h);
885
- const C = tileSampler(toGrey(s.data, s.ch), s.img.width, s.img.height, w, h, {
1651
+ const wrap = !!p.tileable;
1652
+ const stamps = [];
1653
+ if (p.stamps === 'random') {
1654
+ const imgs = imagesOf(ctx.input(0));
1655
+ if (!imgs.length)
1656
+ throw new NodeError(`${type}: input 0 has no image`, NO_IMAGE);
1657
+ for (const im of imgs) {
1658
+ const l = p.layer || im.mainLayer, a = im.layer(l);
1659
+ if (!a)
1660
+ throw new NodeError(`${type}: image "${im.name}" has no layer "${l}"`, `layers: ${[...im.layers.keys()].join(', ') || 'none'}`);
1661
+ stamps.push({ data: toGrey(a, channelsOf(a, im.count) || 1), w: im.width, h: im.height });
1662
+ }
1663
+ }
1664
+ else {
1665
+ const s = source(ctx, 0, p.image, p.layer);
1666
+ stamps.push({ data: toGrey(s.data, s.ch), w: s.img.width, h: s.img.height });
1667
+ }
1668
+ const grey = (i, img, param) => {
1669
+ const m = sourceAt(ctx, i, w, h, img, '', wrap, param);
1670
+ return m ? toGrey(m.data, m.ch) : null;
1671
+ };
1672
+ const r = tileSampler(stamps, w, h, {
886
1673
  count: [p.count[0], p.count[1]], scale: [p.scale[0], p.scale[1]], rotation: p.rotation, jitter: p.jitter, offset: p.offset,
887
- intensity: [p.intensity[0], p.intensity[1]], seed: p.seed, add: p.combine === 'add',
888
- }, m ? toGrey(m.data, m.ch) : null);
889
- return imageGeo(new Image(w, h, imgName(p, 'tiles')).set(MAIN_LAYER, C));
1674
+ intensity: [p.intensity[0], p.intensity[1]], seed: p.seed, add: p.combine === 'add', wrap, output: p.output,
1675
+ scaleMap: grey(2, p.scale_map_image, 'scale_map_image'), rotationMap: grey(3, p.rotation_map_image, 'rotation_map_image'),
1676
+ intensityMap: grey(4, p.intensity_map_image, 'intensity_map_image'),
1677
+ }, grey(1, p.mask_image, 'mask_image'));
1678
+ const img = new Image(w, h, outName(ctx)).set(MAIN_LAYER, r.C);
1679
+ if (p.output !== 'grey')
1680
+ img.set('mask', r.mask);
1681
+ return imageGeo(img);
1682
+ },
1683
+ });
1684
+ // ---------------------------------------------------------------- distance fields, bevels and regions
1685
+ const thresholdParam = () => ({ type: 'float', default: 0.5, desc: 'the value where the mask\'s outline runs (inside = at or above it)', aliases: ['level', 'cut'] });
1686
+ defineNode({
1687
+ type: 'tex_sdf_from_mask',
1688
+ usesNodeName: NAMED_BY_NODE,
1689
+ category: 'texture',
1690
+ summary: 'SDF from a mask: the signed distance in metres (negative inside) to where a grey image crosses threshold, accurate to about a tenth of a pixel.',
1691
+ description: 'Houdini COP: SDF from Mono; Substance: Distance / SDF. The outline is found between pixels by interpolation, so ' +
1692
+ 'antialiased masks (tex_pattern, tex_shape, tex_text, a threshold with softness) give smooth distances that are ' +
1693
+ 'the same in metres at any resolution; an exact distance transform carries them across the image. With tileable ' +
1694
+ 'distances are measured across the borders. A mask without any outline (all inside or all outside) gives ± the ' +
1695
+ 'image\'s width + height in texels. Feed tex_sdf_op, tex_sdf_boolean and tex_sdf_to_mask.',
1696
+ aliases: ['sdf_from_mask', 'mask_to_sdf', 'sdf_from_mono', 'cop_sdffrommono', 'distance_field'],
1697
+ inputs: FILTER_INPUT,
1698
+ params: {
1699
+ threshold: thresholdParam(),
1700
+ size: sizeParam(),
1701
+ tileable: tileParam(),
1702
+ image: imageParam(), layer: layerParam(), name: renameParam(),
1703
+ },
1704
+ outputs: 'the SDF (grey, metres, negative inside) named <name> (default: the node name)',
1705
+ example: {
1706
+ nodes: {
1707
+ word: { type: 'tex_text', params: { resolution: [256, 128], text: 'SDF', size: 0.6 } },
1708
+ sdf: { type: 'tex_sdf_from_mask', in: ['word'], params: { size: 1, tileable: false } },
1709
+ },
1710
+ output: 'sdf',
1711
+ },
1712
+ cook: (ctx) => {
1713
+ const { p } = ctx;
1714
+ const s = source(ctx, 0, p.image, p.layer);
1715
+ return withLayer(s, maskSDF(s, p.threshold, p.size, !!p.tileable), outName(ctx));
1716
+ },
1717
+ });
1718
+ defineNode({
1719
+ type: 'tex_sdf_op',
1720
+ usesNodeName: NAMED_BY_NODE,
1721
+ category: 'texture',
1722
+ summary: 'Operate on an SDF image in metres: offset (grow or shrink), round convex corners, fillet concave ones, stroke (an outline band), invert, redistance.',
1723
+ description: `Houdini COP: SDF Offset / Round; Substance: SDF operations. ${SDF_NOTE}. offset grows the shape by amount metres ` +
1724
+ '(negative shrinks); round rounds its convex corners with radius amount and fillet its concave ones (shrink or ' +
1725
+ 'grow, measure again, return); stroke turns it into a band amount wide centred on the outline (rings from discs, ' +
1726
+ 'frames from boxes, then tex_sdf_to_mask); invert swaps inside and outside; redistance measures the distance ' +
1727
+ 'to the outline again after smooth booleans or a morph. Distances are metres of an image `size` metres wide.',
1728
+ aliases: ['sdf_op', 'sdf_operation', 'sdf_texture_offset', 'cop_sdfoffset', 'sdf_round'],
1729
+ inputs: SDF_INPUT,
1730
+ params: {
1731
+ mode: { type: 'enum', options: SDF_OPS, default: 'offset', desc: 'operation', aliases: ['operation', 'type'] },
1732
+ amount: { type: 'float', default: 0.01, desc: 'offset distance, corner radius or stroke width in metres', aliases: ['distance', 'radius', 'width'] },
1733
+ size: sizeParam(),
1734
+ tileable: tileParam(),
1735
+ image: imageParam(), layer: layerParam(), name: renameParam(),
1736
+ },
1737
+ example: {
1738
+ nodes: {
1739
+ star: { type: 'tex_sdf_shape', params: { resolution: 256, shape: 'star', radius: 0.4, sides: 5 } },
1740
+ soft: { type: 'tex_sdf_op', in: ['star'], params: { mode: 'round', amount: 0.04 } },
1741
+ ring: { type: 'tex_sdf_op', in: ['soft'], params: { mode: 'stroke', amount: 0.03 } },
1742
+ out: { type: 'tex_sdf_to_mask', in: ['ring'] },
1743
+ },
1744
+ output: 'out',
1745
+ },
1746
+ cook: (ctx) => {
1747
+ const { p } = ctx;
1748
+ const s = source(ctx, 0, p.image, p.layer);
1749
+ const w = s.img.width, h = s.img.height;
1750
+ return withLayer(s, sdfOp(toGrey(s.data, s.ch), w, h, p.mode, p.amount, p.size / w, !!p.tileable), outName(ctx));
1751
+ },
1752
+ });
1753
+ defineNode({
1754
+ type: 'tex_sdf_boolean',
1755
+ usesNodeName: NAMED_BY_NODE,
1756
+ category: 'texture',
1757
+ summary: 'Combine two SDF images: union, subtract, intersect or xor, hard or smooth (blend width in metres), or morph from one to the other.',
1758
+ description: `Houdini COP: SDF Blend; Substance: SDF Boolean. ${SDF_NOTE}. union = either shape, subtract = input 0 minus input ` +
1759
+ '1, intersect = both, xor = one but not both. smoothness blends the seam over that many metres (a fillet where ' +
1760
+ 'shapes meet: welded plates, melted blobs); 0 is a hard cut. morph mixes the two fields by amount (0 = input 0, ' +
1761
+ '1 = input 1). Input 1 is resized to input 0. Smooth results and morphs are not exact distances away from the ' +
1762
+ 'outline: follow with tex_sdf_op redistance before offsets.',
1763
+ aliases: ['sdf_boolean_texture', 'sdf_combine_texture', 'cop_sdfblend', 'sdf_union'],
1764
+ inputs: [
1765
+ { name: 'a', desc: 'SDF image A (its geometry passes through)' },
1766
+ { name: 'b', desc: 'SDF image B' },
1767
+ ],
1768
+ params: {
1769
+ mode: { type: 'enum', options: SDF_BOOLEANS, default: 'union', desc: 'how the shapes combine', aliases: ['operation', 'type'] },
1770
+ smoothness: { type: 'float', default: 0, min: 0, desc: 'width of the smooth blend in metres (0 = hard)', aliases: ['smooth', 'blend', 'radius'] },
1771
+ amount: { type: 'float', default: 0.5, min: 0, max: 1, desc: 'morph: 0 = A, 1 = B', aliases: ['mix', 't'] },
1772
+ tileable: tileParam('resizing B wraps at the borders'),
1773
+ image: imageParam('input 0 (A)'), layer: layerParam(),
1774
+ b_image: imageParam('input 1 (B)', []),
1775
+ b_layer: { type: 'string', default: '', desc: 'layer of B ("" = main)' },
1776
+ name: renameParam(),
1777
+ },
1778
+ example: {
1779
+ nodes: {
1780
+ plate: { type: 'tex_sdf_shape', params: { resolution: 256, shape: 'box', extent: [0.7, 0.5], corner: 0.05 } },
1781
+ hole: { type: 'tex_sdf_shape', params: { resolution: 256, shape: 'disc', radius: 0.12 } },
1782
+ cut: { type: 'tex_sdf_boolean', in: ['plate', 'hole'], params: { mode: 'subtract', smoothness: 0.03 } },
1783
+ out: { type: 'tex_sdf_to_mask', in: ['cut'], params: { mode: 'bevel', width: 0.04 } },
1784
+ },
1785
+ output: 'out',
1786
+ },
1787
+ cook: (ctx) => {
1788
+ const { p, type } = ctx;
1789
+ const A = source(ctx, 0, p.image, p.layer);
1790
+ const w = A.img.width, h = A.img.height;
1791
+ const B = sourceAt(ctx, 1, w, h, p.b_image, p.b_layer, !!p.tileable, 'b_image');
1792
+ if (!B)
1793
+ throw new NodeError(`${type}: connect a second SDF image to input 1`, 'an SDF image: tex_sdf_shape, or tex_sdf_from_mask of a mask');
1794
+ return withLayer(A, sdfBoolean(toGrey(A.data, A.ch), toGrey(B.data, B.ch), p.mode, p.smoothness, p.amount), outName(ctx));
1795
+ },
1796
+ });
1797
+ defineNode({
1798
+ type: 'tex_sdf_to_mask',
1799
+ usesNodeName: NAMED_BY_NODE,
1800
+ category: 'texture',
1801
+ summary: 'Render an SDF image: an antialiased fill, an outline of a set width, a bevel profile (a height), or the field encoded 0..1 for export.',
1802
+ description: `Houdini COP: SDF to Mono; Substance: SDF to mask. ${SDF_NOTE}. fill: 1 inside, 0 outside, antialiased over one ` +
1803
+ 'texel or softened over softness metres. outline: a line width metres wide centred on the outline. bevel: 0 on the ' +
1804
+ 'outline rising through the profile (linear, smooth, round = a quarter circle, ramp = your curve) to 1 at width ' +
1805
+ 'metres inside: a height for tex_normal_from_height. distance: 0.5 on the outline, 1 at width metres inside, 0 at ' +
1806
+ 'width outside (the usual encoding of distance-field textures for decals and text in shaders).',
1807
+ aliases: ['sdf_to_mask', 'sdf_to_mono', 'sdf_render', 'cop_sdftomono', 'sdf_fill'],
1808
+ inputs: SDF_INPUT,
1809
+ params: {
1810
+ mode: { type: 'enum', options: SDF_RENDER, default: 'fill', desc: 'what to draw', aliases: ['type', 'output'] },
1811
+ width: { type: 'float', default: 0.02, min: 0, desc: 'outline width, bevel width or distance range in metres', aliases: ['distance', 'bevel_width'] },
1812
+ softness: { type: 'float', default: 0, min: 0, desc: 'fill and outline: edge softness in metres (0 = antialiased over a texel)', aliases: ['falloff', 'blur'] },
1813
+ profile: { type: 'enum', options: BEVEL_PROFILES, default: 'smooth', desc: 'bevel: profile from the outline inward', aliases: ['curve_type'] },
1814
+ ramp: { type: 'ramp', default: [[0, 0], [1, 1]], desc: 'bevel with profile ramp: height [[t, value], …] from the outline (t 0) to width inside (t 1)', aliases: ['curve'] },
1815
+ size: sizeParam(),
1816
+ image: imageParam(), layer: layerParam(), name: renameParam(),
1817
+ },
1818
+ outputs: 'the grey result named <name> (default: the node name)',
1819
+ example: {
1820
+ nodes: {
1821
+ rivets: { type: 'tex_sdf_shape', params: { resolution: 256, shape: 'disc', radius: 0.04, tile: [6, 6] } },
1822
+ out: { type: 'tex_sdf_to_mask', in: ['rivets'], params: { mode: 'bevel', width: 0.04, profile: 'round' } },
1823
+ },
1824
+ output: 'out',
1825
+ },
1826
+ cook: (ctx) => {
1827
+ const { p } = ctx;
1828
+ const s = source(ctx, 0, p.image, p.layer);
1829
+ const prof = profileFn(p.profile, (t) => Number(evalRamp(p.ramp, t)));
1830
+ return withLayer(s, sdfToMask(toGrey(s.data, s.ch), p.mode, p.width, p.softness, p.size / s.img.width, prof), outName(ctx));
1831
+ },
1832
+ });
1833
+ defineNode({
1834
+ type: 'tex_bevel',
1835
+ usesNodeName: NAMED_BY_NODE,
1836
+ category: 'texture',
1837
+ summary: 'Bevel a mask into a height: 0 on the outline rising to 1 at a distance in metres inside (or outward), through a linear, smooth, round or custom profile.',
1838
+ description: 'Substance: Bevel; Houdini COP: Bevel. The mask\'s outline (where it crosses threshold) is measured to a tenth of ' +
1839
+ 'a pixel, so the bevel is `distance` metres wide at any resolution. A positive distance bevels inward (0 on the ' +
1840
+ 'outline, 1 on the plateau); a negative one bevels outward (1 inside, falling to 0 at |distance| outside). round ' +
1841
+ 'is a quarter circle (a rolled edge), smooth an S-curve, linear a chamfer, ramp your curve. Inner corners stay ' +
1842
+ 'sharp, outer corners of an outward bevel round off. Feed tex_normal_from_height (with the same size) and ' +
1843
+ 'tex_curvature or tex_ao.',
1844
+ aliases: ['bevel_texture', 'texture_bevel', 'cop_bevel', 'mask_bevel', 'chamfer_texture'],
1845
+ inputs: FILTER_INPUT,
1846
+ params: {
1847
+ distance: { type: 'float', default: 0.02, desc: 'bevel width in metres (> 0 inward, < 0 outward)', aliases: ['width', 'bevel_width'] },
1848
+ profile: { type: 'enum', options: BEVEL_PROFILES, default: 'smooth', desc: 'profile from the outline to the plateau', aliases: ['curve_type'] },
1849
+ ramp: { type: 'ramp', default: [[0, 0], [1, 1]], desc: 'profile ramp: height [[t, value], …] from the outline (t 0) to the full distance (t 1)', aliases: ['curve'] },
1850
+ threshold: thresholdParam(),
1851
+ size: sizeParam(),
1852
+ tileable: tileParam(),
1853
+ image: imageParam(), layer: layerParam(), name: renameParam(),
1854
+ },
1855
+ outputs: 'the bevel height (grey 0..1) named <name> (default: the node name)',
1856
+ example: {
1857
+ nodes: {
1858
+ tiles: { type: 'tex_pattern', params: { resolution: 256, pattern: 'tiles', count: [4, 4], gap: 0.08, bevel: 0 } },
1859
+ out: { type: 'tex_bevel', in: ['tiles'], params: { distance: 0.03, profile: 'round' } },
1860
+ },
1861
+ output: 'out',
1862
+ },
1863
+ cook: (ctx) => {
1864
+ const { p } = ctx;
1865
+ const s = source(ctx, 0, p.image, p.layer);
1866
+ const prof = profileFn(p.profile, (t) => Number(evalRamp(p.ramp, t)));
1867
+ return withLayer(s, bevelHeight(maskSDF(s, p.threshold, p.size, !!p.tileable), p.distance, prof, p.size / s.img.width), outName(ctx));
1868
+ },
1869
+ });
1870
+ defineNode({
1871
+ type: 'tex_distance',
1872
+ usesNodeName: NAMED_BY_NODE,
1873
+ category: 'texture',
1874
+ summary: 'Grow a mask by a distance in metres: a falloff gradient or a hard grown mask; with a source, carry its values (colours, ids) out into the grown area.',
1875
+ description: 'Substance: Distance. gradient: 1 inside the mask (value ≥ threshold) falling linearly to 0 at `distance` metres ' +
1876
+ 'outside (glows, soft dirt around shapes, fall-off masks). grow: the mask grown by `distance` metres, antialiased. ' +
1877
+ 'With a source image on input 1, C is instead the source\'s value at the nearest mask pixel, carried out to ' +
1878
+ '`distance` (0 beyond, inside the mask the source itself): per-tile colours or ids bled into the gaps, texture ' +
1879
+ 'padding in metres; layer "mask" holds the gradient or grown mask. Distances in metres of an image `size` metres ' +
1880
+ 'wide, so the same at any resolution; with tileable they cross the borders.',
1881
+ aliases: ['distance_texture', 'grow_mask', 'mask_distance', 'mask_grow', 'expand_mask'],
1882
+ inputs: [
1883
+ { name: 'mask', desc: 'grey mask to grow (its geometry passes through)' },
1884
+ { name: 'source', desc: 'optional: an image whose values are carried out from the mask', optional: true },
1885
+ ],
1886
+ params: {
1887
+ distance: { type: 'float', default: 0.05, min: 0, desc: 'how far the mask grows, in metres', aliases: ['radius', 'grow'] },
1888
+ mode: { type: 'enum', options: ['gradient', 'grow'], default: 'gradient', desc: 'gradient = linear falloff to 0 at distance; grow = hard edge at distance', aliases: ['type'] },
1889
+ threshold: thresholdParam(),
1890
+ size: sizeParam(),
1891
+ tileable: tileParam(),
1892
+ image: imageParam('input 0 (the mask)', ['input_image']), layer: layerParam(),
1893
+ source_image: imageParam('input 1 (the source)', []),
1894
+ source_layer: { type: 'string', default: '', desc: 'layer of the source ("" = main)' },
1895
+ name: renameParam(),
1896
+ },
1897
+ outputs: 'the grown mask (grey), or with a source its carried values (grey or RGBA) and layer mask; named <name> (default: the node name)',
1898
+ example: {
1899
+ nodes: {
1900
+ dots: { type: 'tex_sdf_shape', params: { resolution: 256, shape: 'disc', radius: 0.05, tile: [4, 4] } },
1901
+ mask: { type: 'tex_sdf_to_mask', in: ['dots'] },
1902
+ glow: { type: 'tex_distance', in: ['mask'], params: { distance: 0.06 } },
1903
+ },
1904
+ output: 'glow',
1905
+ },
1906
+ cook: (ctx) => {
1907
+ const { p } = ctx;
1908
+ const s = source(ctx, 0, p.image, p.layer);
1909
+ const w = s.img.width, h = s.img.height, texel = p.size / w, wrap = !!p.tileable;
1910
+ const d = maskSDF(s, p.threshold, p.size, wrap), D = Math.max(0, p.distance);
1911
+ const mask = new Float32Array(w * h);
1912
+ for (let k = 0; k < mask.length; k++) {
1913
+ const x = d[k];
1914
+ mask[k] = p.mode === 'grow' ? Math.max(0, Math.min(1, 0.5 - (x - D) / texel)) : x <= 0 ? 1 : D > 0 ? Math.max(0, 1 - x / D) : 0;
1915
+ }
1916
+ const src = sourceAt(ctx, 1, w, h, p.source_image, p.source_layer, wrap, 'source_image');
1917
+ if (!src)
1918
+ return withLayer(s, mask, outName(ctx));
1919
+ const inside = Uint8Array.from(d, (x) => (x <= 0 ? 1 : 0));
1920
+ return withLayer(s, propagate(src.data, src.ch, inside, w, h, D / texel, wrap), outName(ctx), { mask });
1921
+ },
1922
+ });
1923
+ defineNode({
1924
+ type: 'tex_flood_fill',
1925
+ usesNodeName: NAMED_BY_NODE,
1926
+ category: 'texture',
1927
+ summary: 'Flood fill: find the separate tiles of a mask (bricks, planks, stones, panels) and give each a random grey or colour, a gradient across it, its size or its position.',
1928
+ description: 'Substance: Flood Fill + Flood Fill to Random Grayscale / Random Color / Gradient / BBox Size / Position. A tile ' +
1929
+ 'is a connected area at or above threshold (4- or 8-connected); with tileable a tile cut by a border is one tile. ' +
1930
+ 'random: a random grey per tile; color: a random RGB (alpha 1 on tiles, 0 in the gaps); gradient: 0 → 1 across ' +
1931
+ 'each tile along angle, turned by up to ± angle_random per tile (directional wear, per-plank shading); bbox_size: ' +
1932
+ 'the longer side of the tile\'s bounding box in metres (bigger stones darker, small chips brighter); position: ' +
1933
+ 'the tile\'s centre as (u, v, 0, 1) (feed per-tile offsets). Layer "id" holds the random grey. Random values come ' +
1934
+ 'from each tile\'s centre (area-weighted with its antialiased edge), so they stay with the tile whatever the ' +
1935
+ 'resolution or the order tiles are found in. The gaps are 0. Stat tiles = the number of tiles.',
1936
+ aliases: ['flood_fill', 'floodfill', 'flood_fill_to_random', 'flood_fill_to_color', 'flood_fill_to_gradient', 'tile_id', 'connected_components'],
1937
+ inputs: FILTER_INPUT,
1938
+ params: {
1939
+ output: { type: 'enum', options: FLOOD_OUTPUTS, default: 'random', desc: 'what each tile gets in C', aliases: ['mode', 'type'] },
1940
+ threshold: thresholdParam(),
1941
+ connectivity: { type: 'enum', options: [4, 8], default: 4, desc: 'pixels touching at corners join (8) or not (4)', aliases: ['neighbours'] },
1942
+ angle: { type: 'float', default: 0, desc: 'gradient: direction in degrees (0 = +u, 90 = +v)', aliases: ['direction'] },
1943
+ angle_random: { type: 'float', default: 0, min: 0, max: 180, desc: 'gradient: random turn per tile, ± degrees', aliases: ['angle_variation'] },
1944
+ seed: P.seed(),
1945
+ size: sizeParam(),
1946
+ tileable: tileParam('tiles continue across the borders'),
1947
+ image: imageParam(), layer: layerParam(), name: renameParam(),
1948
+ },
1949
+ outputs: 'the per-tile values (grey, or RGBA for color and position) named <name> (default: the node name); layer id (random grey per tile); stat tiles',
1950
+ example: {
1951
+ nodes: {
1952
+ bricks: { type: 'tex_pattern', params: { resolution: 256, pattern: 'bricks', count: [4, 8], bevel: 0 } },
1953
+ out: { type: 'tex_flood_fill', in: ['bricks'], params: { output: 'gradient', angle: 0, angle_random: 20 } },
1954
+ },
1955
+ output: 'out',
1956
+ },
1957
+ cook: (ctx) => {
1958
+ const { p, type } = ctx;
1959
+ const s = source(ctx, 0, p.image, p.layer);
1960
+ const w = s.img.width, h = s.img.height;
1961
+ const r = floodFill(toGrey(s.data, s.ch), w, h, {
1962
+ threshold: p.threshold, connectivity: Number(p.connectivity), output: p.output, angle: p.angle, angleRandom: p.angle_random,
1963
+ seed: p.seed, wrap: !!p.tileable, texel: p.size / w,
1964
+ });
1965
+ ctx.stat('tiles', r.tiles);
1966
+ if (!r.tiles)
1967
+ ctx.warn(`${type}: no pixel of "${s.img.name}" reaches threshold ${p.threshold}: no tiles`);
1968
+ return withLayer(s, r.C, outName(ctx), { id: r.id });
1969
+ },
1970
+ });
1971
+ defineNode({
1972
+ type: 'tex_make_tile',
1973
+ usesNodeName: NAMED_BY_NODE,
1974
+ category: 'texture',
1975
+ summary: 'Make it tile: blend an image (a photo, a non-tileable noise) with copies shifted by half, so its borders meet seamlessly.',
1976
+ description: 'Substance: Make It Tile Photo / Patch. Along u, then along v, the image is blended with a copy shifted by half ' +
1977
+ 'the image: near the borders the copy shows (it runs on across them), from `blend` (a fraction of the image) ' +
1978
+ 'inward the original does (covering the copy\'s seam). noise 0 is a smooth cross-fade over the band; toward 1 the ' +
1979
+ 'hand-over becomes a narrow edge that wanders with a noise of noise_scale cells (a patch edge hides the blend ' +
1980
+ 'better on photos and coarse noise). The result always tiles; the middle of the image is untouched.',
1981
+ aliases: ['make_tile', 'make_it_tile', 'makeittile', 'make_tileable', 'seamless_texture'],
1982
+ inputs: FILTER_INPUT,
1983
+ params: {
1984
+ blend: { type: 'float', default: 0.25, min: 0.01, max: 0.5, desc: 'width of the blended band at each border (fraction of the image)', aliases: ['band', 'mask_size'] },
1985
+ noise: { type: 'float', default: 0.5, min: 0, max: 1, desc: '0 = smooth cross-fade, 1 = a narrow edge wandering with noise', aliases: ['patch', 'warp'] },
1986
+ noise_scale: { type: 'float', default: 6, min: 1, max: 64, desc: 'cells of the edge noise across the image', aliases: ['frequency'] },
1987
+ seed: P.seed(),
1988
+ image: imageParam(), layer: layerParam(), name: renameParam(),
1989
+ },
1990
+ example: {
1991
+ nodes: {
1992
+ n: { type: 'tex_noise', params: { resolution: 256, scale: 5.5, tileable: false } },
1993
+ out: { type: 'tex_make_tile', in: ['n'], params: { blend: 0.2, noise: 0.6 } },
1994
+ },
1995
+ output: 'out',
1996
+ },
1997
+ cook: (ctx) => {
1998
+ const { p } = ctx;
1999
+ const s = source(ctx, 0, p.image, p.layer);
2000
+ const w = s.img.width, h = s.img.height;
2001
+ const nz = (k) => texNoise({ noise: 'perlin', fractal: 'fbm', scale: p.noise_scale, octaves: 3, roughness: 0.5, lacunarity: 2, seed: p.seed * 3 + k, tileable: true, offset: [0, 0], aspect: h / w });
2002
+ return withLayer(s, makeTile(s.data, s.ch, w, h, p.blend, nz(1), nz(2), p.noise), outName(ctx));
890
2003
  },
891
2004
  });
892
2005
  // ---------------------------------------------------------------- output, materials and bridges
893
2006
  defineNode({
894
2007
  type: 'tex_output',
2008
+ usesNodeName: NAMED_BY_NODE,
895
2009
  category: 'texture',
896
2010
  summary: 'Name an image (rename), or copy one of its layers out as a new image (e.g. the "id" layer of a pattern).',
897
- description: 'Substance: Output node; Houdini COP: Null / Output. With layer "" the image is renamed to `name`; with a layer, a new image `name` holds that layer as C and the original stays. An image already called `name` is replaced. keep_only drops every other image (and the mesh) from the output.',
2011
+ description: 'Substance: Output node; Houdini COP: Null / Output. With layer "" the image is renamed to `name` (default: this node\'s name); with a layer, a new image `name` holds that layer as C and the original stays. An image already called `name` is replaced. keep_only drops every other image (and the mesh) from the output: the way to isolate one image of a stack.',
898
2012
  aliases: ['texture_output', 'rename_image', 'image_output', 'cop_null'],
899
2013
  inputs: FILTER_INPUT,
900
2014
  params: {
901
- name: { type: 'string', default: 'image', desc: 'the image name (materials reference it as "image:<name>")', aliases: ['image_name', 'output_name'] },
2015
+ name: nameParam(),
902
2016
  image: imageParam(),
903
2017
  layer: { type: 'string', default: '', desc: 'copy this layer out as a new image ("" = rename the whole image)' },
904
2018
  keep_only: { type: 'bool', default: false, desc: 'output only this image' },
905
2019
  },
2020
+ outputs: 'the image renamed <name> (default: the node name), or with layer set a new image <name> holding that layer',
906
2021
  example: {
907
2022
  nodes: {
908
2023
  bricks: { type: 'tex_pattern', params: { resolution: 256 } },
909
- out: { type: 'tex_output', in: ['bricks'], params: { name: 'brick_id', layer: 'id' } },
2024
+ brick_id: { type: 'tex_output', in: ['bricks'], params: { layer: 'id' } },
910
2025
  },
911
- output: 'out',
2026
+ output: 'brick_id',
912
2027
  },
913
2028
  cook: (ctx) => {
914
- const { p, type } = ctx;
915
- const name = String(p.name ?? '').trim();
916
- if (!name)
917
- throw new NodeError(`${type}: name is empty`);
2029
+ const { p } = ctx;
2030
+ const name = outName(ctx);
918
2031
  const s = source(ctx, 0, p.image, p.layer);
919
2032
  let img;
920
2033
  const g = s.g.clone();
@@ -940,16 +2053,19 @@ defineNode({
940
2053
  category: 'texture',
941
2054
  summary: 'Attach images as texture maps (base colour, normal, roughness, ORM) to a named material and assign it; the images travel with the geometry and exporters embed them.',
942
2055
  description: 'Input 0 is the mesh (with uv), input 1 the images (merge several texture branches first). Each slot names an image ' +
943
- 'of input 1 (or input 0); it is copied into the output and the material table entry gets "image:<name>" in that slot. ' +
2056
+ 'of input 1 (or input 0), by default the name of the node that made it; it is copied into the output and the ' +
2057
+ 'material table entry gets "image:<name>" in that slot (two different images under the named one are an error). ' +
944
2058
  'orm is a packed occlusion (R) / roughness (G) / metallic (B) map (tex_channel pack), written to glTF as the ' +
945
2059
  'metallicRoughness and occlusion textures and to USD through the r/g/b outputs; occlusion and metallic images given ' +
946
2060
  'separately are packed into "<material>_orm" (missing channels from the material: occlusion 1, its roughness and ' +
947
2061
  'metallic; a roughness image goes in too). The material is created with defaults when missing (or updated) and ' +
948
2062
  'assigned to the prims of `group` ("" = every prim when the material is new, none when it exists). render ' +
949
- '{textures: true} shows base colour maps on the mesh; views "texture" shows the images.',
2063
+ '{textures: true} shows base colour maps on the mesh; views "texture" shows the images. With nothing in input 0 the ' +
2064
+ 'result is the material alone with the maps it uses: a material output (kind material), which other packages ' +
2065
+ 'assign through input 1 of the material node.',
950
2066
  aliases: ['texture_material', 'material_textures', 'attach_textures', 'apply_textures'],
951
2067
  inputs: [
952
- { name: 'geo', desc: 'mesh to texture (needs uv)' },
2068
+ { name: 'geo', desc: 'mesh to texture (needs uv); none: the material alone, for a material output', optional: true },
953
2069
  { name: 'images', desc: 'geometry holding the images (merge texture branches)', optional: true },
954
2070
  ],
955
2071
  params: {
@@ -970,10 +2086,10 @@ defineNode({
970
2086
  nodes: {
971
2087
  box: { type: 'box' },
972
2088
  uv: { type: 'uv_project', in: ['box'], params: { method: 'box' } },
973
- bricks: { type: 'tex_pattern', params: { resolution: 256, name: 'brick_height' } },
974
- color: { type: 'tex_colorize', in: ['bricks'], params: { ramp: [[0, '#6b6b66'], [0.5, '#7a3424'], [1, '#a5462e']], name: 'brick_color' } },
975
- nrm: { type: 'tex_normal_from_height', in: ['bricks'], params: { strength: 2, name: 'brick_normal' } },
976
- maps: { type: 'merge', in: ['color', 'nrm'] },
2089
+ bricks: { type: 'tex_pattern', params: { resolution: 256 } },
2090
+ brick_color: { type: 'tex_colorize', in: ['bricks'], params: { ramp: [[0, '#6b6b66'], [0.5, '#7a3424'], [1, '#a5462e']] } },
2091
+ brick_normal: { type: 'tex_normal_from_height', in: ['bricks'], params: { depth: 0.02 } },
2092
+ maps: { type: 'merge', in: ['brick_color', 'brick_normal'] },
977
2093
  out: { type: 'texture_to_material', in: ['uv', 'maps'], params: { material: 'brick', base_color: 'brick_color', normal: 'brick_normal' } },
978
2094
  },
979
2095
  output: 'out',
@@ -983,15 +2099,22 @@ defineNode({
983
2099
  const mat = String(p.material ?? '').trim();
984
2100
  if (!mat)
985
2101
  throw new NodeError(`${type}: material name is empty`);
986
- const g = ctx.input(0).clone();
987
- const pool = new Map();
988
- for (const im of imagesOf(ctx.input(0)))
989
- if (!pool.has(im.name))
2102
+ const g = ctx.hasInput(0) ? ctx.input(0).clone() : new Geometry();
2103
+ // images by name; two different images under one name are ambiguous (reported when a slot names them)
2104
+ const pool = new Map(), clash = new Set();
2105
+ const add = (im) => {
2106
+ const had = pool.get(im.name);
2107
+ if (!had)
990
2108
  pool.set(im.name, im);
2109
+ else if (!sameImage(had, im))
2110
+ clash.add(im.name);
2111
+ };
2112
+ if (ctx.hasInput(0))
2113
+ for (const im of imagesOf(ctx.input(0)))
2114
+ add(im);
991
2115
  if (ctx.hasInput(1))
992
2116
  for (const im of imagesOf(ctx.input(1)))
993
- if (!pool.has(im.name))
994
- pool.set(im.name, im);
2117
+ add(im);
995
2118
  const need = (param) => {
996
2119
  const n = String(p[param] ?? '').trim().replace(/^image:/, '');
997
2120
  if (!n)
@@ -999,6 +2122,8 @@ defineNode({
999
2122
  const im = pool.get(n);
1000
2123
  if (!im)
1001
2124
  throw new NodeError(`${type}: no image "${n}" for ${param}`, pool.size ? `images: ${[...pool.keys()].join(', ')}` : NO_IMAGE);
2125
+ if (clash.has(n))
2126
+ throw new NodeError(`${type}: ${param}: the inputs hold different images named "${n}"`, 'give them different names (an image takes the name of the node that made it unless its name param is set; tex_output renames one)');
1002
2127
  return im;
1003
2128
  };
1004
2129
  const table = readMaterials(g);
@@ -1044,7 +2169,7 @@ defineNode({
1044
2169
  writeMaterials(g, table);
1045
2170
  // assign
1046
2171
  const groupSet = String(p.group ?? '').trim();
1047
- if (isNew || groupSet) {
2172
+ if (g.numPrims && (isNew || groupSet)) {
1048
2173
  const sel = groupSet ? mask(g, 'prim', groupSet) : null;
1049
2174
  const a = g.prims.add(MATERIAL_ATTRIB, 'string', 1);
1050
2175
  for (let i = 0; i < g.numPrims; i++)
@@ -1113,25 +2238,29 @@ defineNode({
1113
2238
  });
1114
2239
  defineNode({
1115
2240
  type: 'heightfield_to_tex',
2241
+ usesNodeName: NAMED_BY_NODE,
1116
2242
  category: 'texture',
1117
- summary: 'Bridge: a heightfield layer becomes a grey image of the same sample count (normalised to 0..1 by default).',
1118
- description: 'Sample (i, j) → pixel (i, j) (the −Z row at the top). normalize fits the layer\'s min..max to 0..1 (the range is recorded as the stats range_min / range_max); off writes raw values. Feed tex_normal_from_height or tex_height_to_ao for terrain maps, or bake terrain masks into textures.',
2243
+ summary: 'Bridge: a heightfield layer becomes a grey image of the same sample count (input_min..input_max fitted to 0..1 by default).',
2244
+ description: 'Sample (i, j) → pixel (i, j) (the −Z row at the top). normalize fits input_min..input_max to 0..1 (absolute, so every tile of a map gets the same grey for the same height; values outside the range fall outside 0..1); auto_range fits the layer\'s own min..max instead, which depend on the field\'s extent; off writes raw values. The range used is recorded as the stats range_min / range_max. Feed tex_normal_from_height or tex_height_to_ao for terrain maps, or bake terrain masks into textures.',
1119
2245
  aliases: ['heightfield_to_image', 'hf2tex', 'heightfield_texture'],
1120
2246
  inputs: [{ name: 'heightfield', desc: 'geometry with a heightfield' }],
1121
2247
  params: {
1122
2248
  layer: { type: 'string', default: 'height', desc: 'heightfield layer' },
1123
- normalize: { type: 'bool', default: true, desc: 'fit min..max to 0..1', aliases: ['fit'] },
2249
+ normalize: { type: 'bool', default: true, desc: 'fit the input range to 0..1 (off writes raw values)', aliases: ['fit'] },
2250
+ input_min: { type: 'float', default: 0, desc: 'layer value that becomes 0 (e.g. the lowest height in metres)' },
2251
+ input_max: { type: 'float', default: 1, desc: 'layer value that becomes 1' },
2252
+ auto_range: { type: 'bool', default: false, desc: 'use the layer\'s own min..max as the input range instead (depends on the field\'s extent)' },
1124
2253
  keep: { type: 'bool', default: false, desc: 'keep the input (heightfield and all) and add the image; off outputs only the image' },
1125
- name: nameParam('', 'image name ("" = the layer name)'),
2254
+ name: nameParam(),
1126
2255
  },
1127
- outputs: 'image <name> (default: the layer name): C grey',
2256
+ outputs: 'image <name> (default: the node name): C grey',
1128
2257
  example: {
1129
2258
  nodes: {
1130
2259
  hf: { type: 'heightfield' },
1131
2260
  hills: { type: 'heightfield_noise', in: ['hf'], params: { amplitude: 3 } },
1132
- out: { type: 'heightfield_to_tex', in: ['hills'], params: { name: 'height' } },
2261
+ height: { type: 'heightfield_to_tex', in: ['hills'], params: { input_min: -3, input_max: 3 } },
1133
2262
  },
1134
- output: 'out',
2263
+ output: 'height',
1135
2264
  },
1136
2265
  cook: (ctx) => {
1137
2266
  const { p, type } = ctx;
@@ -1142,18 +2271,22 @@ defineNode({
1142
2271
  const a = hf.layer(p.layer);
1143
2272
  if (!a)
1144
2273
  throw new NodeError(`${type}: heightfield "${hf.name}" has no layer "${p.layer}"`, `layers: ${[...hf.layers.keys()].join(', ')}`);
1145
- let lo = Infinity, hi = -Infinity;
1146
- for (let k = 0; k < a.length; k++) {
1147
- if (a[k] < lo)
1148
- lo = a[k];
1149
- if (a[k] > hi)
1150
- hi = a[k];
2274
+ let lo = p.input_min, hi = p.input_max;
2275
+ if (p.auto_range) {
2276
+ lo = Infinity;
2277
+ hi = -Infinity;
2278
+ for (let k = 0; k < a.length; k++) {
2279
+ if (a[k] < lo)
2280
+ lo = a[k];
2281
+ if (a[k] > hi)
2282
+ hi = a[k];
2283
+ }
1151
2284
  }
1152
2285
  const out = new Float32Array(a.length);
1153
2286
  const span = hi - lo;
1154
2287
  for (let k = 0; k < a.length; k++)
1155
- out[k] = p.normalize ? (span > 0 ? (a[k] - lo) / span : 0) : a[k];
1156
- const img = new Image(hf.width, hf.height, imgName(p, p.layer)).set(MAIN_LAYER, out);
2288
+ out[k] = p.normalize ? (span !== 0 ? (a[k] - lo) / span : 0) : a[k];
2289
+ const img = new Image(hf.width, hf.height, outName(ctx)).set(MAIN_LAYER, out);
1157
2290
  if (p.normalize) {
1158
2291
  ctx.stat('range_min', lo);
1159
2292
  ctx.stat('range_max', hi);