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
@@ -4,28 +4,44 @@
4
4
  // Opt-in overlays answer specific questions (help topic "render"): crisp 1 px edge overlays
5
5
  // (all / hard / boundary / edge groups), a section view and a persp clip plane with filled caps,
6
6
  // vector glyphs (N, up, orient, v), point/prim numbers, group/piece/attribute labels, legends,
7
- // flat/matcap/AO shading and a self-describing annotation footer. With none of them set the
8
- // output is exactly what it always was.
7
+ // flat/matcap/AO shading and a self-describing annotation footer. A heightfield drawn at fewer samples than it has
8
+ // (above heightfieldRes quads per side) gets a second footer line saying so.
9
+ // Framing: every 3D view fits the bounds (the 8 bbox corners projected into the view, with a small margin), so
10
+ // nothing is cropped; zoom is relative to that fit. Views can be W×H (size [w, h]), have a transparent background,
11
+ // a reference image (underlay) behind them, and scene empties (sockets) drawn as labelled dots.
9
12
  import { readMaterials, primMaterials } from '../core/materials.js';
10
13
  import { Geometry } from '../core/geometry.js';
11
14
  import { buildEdges, connectivity, primNormals, resolveVertexNormals, triangulate } from '../core/topology.js';
12
15
  import { halfEdges } from '../core/halfedge.js';
13
16
  import { drawText, textWidth } from './font.js';
14
17
  import { readUV, polygonSides, uvSeamPairs } from '../core/uv.js';
18
+ import { chartKinds, chartRoots, primLods } from '../core/uvreport.js';
15
19
  import { expandForRender } from '../core/packed.js';
16
20
  import { qNormalize, qRotate } from '../core/math.js';
17
21
  import { PLANE_UV, sliceTriangles, windingGrid } from './section.js';
22
+ import { openEdgesText, partsOf, primWhere, solidReport } from '../core/report.js';
18
23
  import { LabelPlacer, ambientOcclusion, dotOv, drawLabel, drawLegend, lineOv } from './overlay.js';
19
- import { withHeightfieldPreview } from '../core/heightfield.js';
24
+ import { heightfieldPreviewStep, isHeightfield, layerStats, withHeightfieldPreview } from '../core/heightfield.js';
20
25
  import { withSdfGridPreview } from '../core/sdfgrid.js';
21
- import { drawTextureView, textureSampler } from './texview.js';
26
+ import { drawTextureView, textureSampler, withMaterialPreview } from './texview.js';
27
+ import { EMPTY_ATTRIB } from '../core/scene.js';
28
+ import { pbrScene, preparePBR } from './pbr.js';
29
+ import { decodePNG } from '../io/png-decode.js';
30
+ /**
31
+ * Named three-quarter views: persp views at these azimuths (degrees; 0 = the camera on +Z looking at the front, 90 =
32
+ * on +X looking at the right side), at the elevation of the persp view.
33
+ */
34
+ export const NAMED_VIEWS = { front_left: -45, front_right: 45, back_left: -135, back_right: 135 };
35
+ export const UNDERLAY_FITS = ['bounds', 'width', 'height', 'view'];
36
+ /** The most quads per side a heightfield is drawn with by default (RenderOptions.heightfieldRes). */
37
+ export const HEIGHTFIELD_RENDER_RES = 256;
22
38
  /** View presets accepted by parseViews (MCP render "views", CLI --views). */
23
39
  export const VIEW_PRESETS = {
24
40
  quad: ['persp', 'front', 'right', 'top'],
25
41
  quad_uv: ['persp', 'uv'],
26
42
  turntable: ['persp@0', 'persp@90', 'persp@180', 'persp@270'],
27
43
  };
28
- export const BASE_VIEWS = ['persp', 'front', 'back', 'left', 'right', 'top', 'bottom', 'uv', 'section', 'texture'];
44
+ export const BASE_VIEWS = ['persp', 'front', 'back', 'left', 'right', 'top', 'bottom', ...Object.keys(NAMED_VIEWS), 'uv', 'section', 'texture'];
29
45
  /** Views from a preset name, a comma/space separated list or an array (presets expand inside lists). Throws on unknown names. */
30
46
  export function parseViews(spec) {
31
47
  if (spec == null)
@@ -48,8 +64,16 @@ export function parseViews(spec) {
48
64
  const AXES = ['x', 'y', 'z'];
49
65
  const WIRE_MODES = ['none', 'all', 'hard', 'boundary', 'groups'];
50
66
  const GLYPH_MODES = ['none', 'N', 'up', 'orient', 'v', 'custom'];
51
- const SHADING_MODES = ['default', 'flat', 'matcap', 'ao'];
52
- const CUT_C = [0.93, 0.4, 0.3], CUT_FLIP_C = [0.25, 0.38, 0.9];
67
+ const SHADING_MODES = ['default', 'flat', 'matcap', 'ao', 'pbr'];
68
+ /** The automatic wireframe draws polygon edges up to this many polygons. */
69
+ export const AUTO_WIRE_MAX = 6000;
70
+ const CUT_C = [0.93, 0.4, 0.3], CUT_FLIP_C = [0.25, 0.38, 0.9], SOCKET_C = [0.35, 1, 0.72];
71
+ /** Margins of the fit: the bounds fill this fraction of a view's width and height (room for the label and gizmo). */
72
+ const FIT_W = 0.9, FIT_H = 0.84;
73
+ /** Whether a zoom above 1 may crop the bounds: only when the person framed the view (look_at or ortho_scale). */
74
+ const zoomFramed = (o) => !!o.target || !!(o.orthoScale && o.orthoScale > 0);
75
+ /** The zoom a view uses: within 0.05..20, held at 1 above 1 unless the view is framed by look_at / ortho_scale. */
76
+ const zoomOf = (o) => { const z = Math.max(0.05, Math.min(20, o.zoom ?? 1)); return z > 1 && !zoomFramed(o) ? 1 : z; };
53
77
  const ORTHO = {
54
78
  front: { f: [0, 0, -1], r: [1, 0, 0], u: [0, 1, 0], label: 'FRONT X> Y^' },
55
79
  back: { f: [0, 0, 1], r: [-1, 0, 0], u: [0, 1, 0], label: 'BACK -X> Y^' },
@@ -58,6 +82,9 @@ const ORTHO = {
58
82
  top: { f: [0, -1, 0], r: [1, 0, 0], u: [0, 0, -1], label: 'TOP X> -Z^' },
59
83
  bottom: { f: [0, 1, 0], r: [1, 0, 0], u: [0, 0, 1], label: 'BOTTOM X> Z^' },
60
84
  };
85
+ /** persp, persp@<azimuth> and the named three-quarter views are perspective views. */
86
+ export const isPerspView = (v) => v.startsWith('persp') || NAMED_VIEWS[v] !== undefined;
87
+ const glAxisC = [[0.95, 0.3, 0.3], [0.4, 0.9, 0.4], [0.4, 0.6, 1]];
61
88
  const dot3 = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
62
89
  const norm3 = (a) => { const l = Math.hypot(a[0], a[1], a[2]) || 1; return [a[0] / l, a[1] / l, a[2] / l]; };
63
90
  const cross3 = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
@@ -76,15 +103,72 @@ function hashStr(s) { let h = 2166136261; for (let i = 0; i < s.length; i++)
76
103
  h = Math.imul(h ^ s.charCodeAt(i), 16777619); return h >>> 0; }
77
104
  /** Section views look along the section axis from its + side (same framing as right / top / front). */
78
105
  const SECTION_CAM = [ORTHO.right, ORTHO.top, ORTHO.front];
79
- function makeCam(name, bmin, bmax, W, H, o, kind = name, azDeg, secAxis = 1) {
106
+ /**
107
+ * The points a view fits: the geometry's points (evenly subsampled above 200,000), or the bbox corners when there are
108
+ * none (volumes only). Fitting the points rather than the bbox keeps rotated content (a square turned 20°) as large as
109
+ * it can be; nothing outside the bbox exists, so the fit never crops.
110
+ */
111
+ function fitPoints(g, bmin, bmax) {
112
+ const np = g.numPoints, n = Math.min(np, 200_000);
113
+ // volumes drawn in 3D (SDFs as their bounds) count with their bbox corners
114
+ const corners = !np || g.volumes.some((v) => v.kind !== 'image') ? 8 : 0;
115
+ const out = new Float64Array((n + corners) * 3);
116
+ for (let k = 0; k < n; k++) {
117
+ const i = Math.floor((k * np) / n) * 3;
118
+ out[k * 3] = g.P[i];
119
+ out[k * 3 + 1] = g.P[i + 1];
120
+ out[k * 3 + 2] = g.P[i + 2];
121
+ }
122
+ for (let k = 0; k < corners; k++) {
123
+ const o = (n + k) * 3;
124
+ out[o] = k & 1 ? bmax[0] : bmin[0];
125
+ out[o + 1] = k & 2 ? bmax[1] : bmin[1];
126
+ out[o + 2] = k & 4 ? bmax[2] : bmin[2];
127
+ }
128
+ return out;
129
+ }
130
+ /**
131
+ * The camera of a view. Persp views stand where they always stood (the bounding sphere seen through a 32° lens, so the
132
+ * perspective does not change with the framing) and then fit the image of the geometry into the view: the focal length
133
+ * and the image centre are chosen so the projected points (fitPoints) fill FIT_W × FIT_H of it, centred (or around the
134
+ * look-at point when target is set). Ortho and section views fit the same way. zoom scales the fit.
135
+ */
136
+ function makeCam(name, bmin, bmax, W, H, o, kind = name, azDeg, secAxis, pts) {
80
137
  const c = o.target ?? [(bmin[0] + bmax[0]) / 2, (bmin[1] + bmax[1]) / 2, (bmin[2] + bmax[2]) / 2];
81
- const ext = [bmax[0] - bmin[0], bmax[1] - bmin[1], bmax[2] - bmin[2]];
82
- const R = Math.max(1e-6, Math.hypot(ext[0], ext[1], ext[2]) / 2);
83
- const zoom = Math.max(0.05, Math.min(20, o.zoom ?? 1));
138
+ let R = 1e-6;
139
+ for (let k = 0; k < 8; k++)
140
+ R = Math.max(R, Math.hypot((k & 1 ? bmax[0] : bmin[0]) - c[0], (k & 2 ? bmax[1] : bmin[1]) - c[1], (k & 4 ? bmax[2] : bmin[2]) - c[2]));
141
+ const zoom = zoomOf(o), centred = !!o.target;
142
+ /** half extents and centre of the fit from the image coordinates of the points (x along r, y along u; persp: over depth) */
143
+ const fit = (r, u, f, from) => {
144
+ let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;
145
+ for (let i = 0; i < pts.length; i += 3) {
146
+ const dx = pts[i] - from[0], dy = pts[i + 1] - from[1], dz = pts[i + 2] - from[2];
147
+ const z = f ? Math.max(1e-9, dx * f[0] + dy * f[1] + dz * f[2]) : 1;
148
+ const x = (dx * r[0] + dy * r[1] + dz * r[2]) / z, y = (dx * u[0] + dy * u[1] + dz * u[2]) / z;
149
+ if (!Number.isFinite(x) || !Number.isFinite(y))
150
+ continue;
151
+ if (x < x0)
152
+ x0 = x;
153
+ if (x > x1)
154
+ x1 = x;
155
+ if (y < y0)
156
+ y0 = y;
157
+ if (y > y1)
158
+ y1 = y;
159
+ }
160
+ if (!(x1 >= x0)) {
161
+ x0 = x1 = y0 = y1 = 0;
162
+ }
163
+ // around the look-at point (the view looks from `from` through it, so its image is x = y = 0), else centred
164
+ return centred
165
+ ? { hx: Math.max(Math.abs(x0), Math.abs(x1)), hy: Math.max(Math.abs(y0), Math.abs(y1)), cx: 0, cy: 0 }
166
+ : { hx: (x1 - x0) / 2, hy: (y1 - y0) / 2, cx: (x0 + x1) / 2, cy: (y0 + y1) / 2 };
167
+ };
84
168
  if (kind === 'persp') {
85
169
  const az = ((azDeg ?? o.azimuth ?? 35) * Math.PI) / 180, el = ((o.elevation ?? 25) * Math.PI) / 180;
86
170
  const fov = (32 * Math.PI) / 180;
87
- const dist = (R / Math.sin(fov / 2)) * 1.05 / zoom;
171
+ const dist = (R / Math.sin(fov / 2)) * 1.05;
88
172
  const dir = [Math.cos(el) * Math.sin(az), Math.sin(el), Math.cos(el) * Math.cos(az)];
89
173
  const eye = [c[0] + dir[0] * dist, c[1] + dir[1] * dist, c[2] + dir[2] * dist];
90
174
  const f = norm3([c[0] - eye[0], c[1] - eye[1], c[2] - eye[2]]);
@@ -93,15 +177,65 @@ function makeCam(name, bmin, bmax, W, H, o, kind = name, azDeg, secAxis = 1) {
93
177
  r = [1, 0, 0];
94
178
  r = norm3(r);
95
179
  const u = cross3(r, f);
96
- return { name, persp: true, eye, f, r, u, c, focal: Math.min(W, H) / 2 / Math.tan(fov / 2), scale: 1 };
180
+ const q = fit(r, u, f, eye);
181
+ const lens = Math.min(W, H) / 2 / Math.tan(fov / 2);
182
+ const focal = Math.min(q.hx > 1e-9 ? (W / 2) * FIT_W / q.hx : Infinity, q.hy > 1e-9 ? (H / 2) * FIT_H / q.hy : Infinity, lens * 50) * zoom;
183
+ const fl = Number.isFinite(focal) && focal > 0 ? focal : lens * zoom;
184
+ return { name, persp: true, eye, f, r, u, c, focal: fl, scale: 1, ox: W / 2 - q.cx * fl, oy: H / 2 + q.cy * fl };
97
185
  }
98
186
  const v = kind === 'section' ? SECTION_CAM[secAxis] : ORTHO[name];
99
- const halfW = Math.abs(v.r[0]) * ext[0] / 2 + Math.abs(v.r[1]) * ext[1] / 2 + Math.abs(v.r[2]) * ext[2] / 2;
100
- const halfH = Math.abs(v.u[0]) * ext[0] / 2 + Math.abs(v.u[1]) * ext[1] / 2 + Math.abs(v.u[2]) * ext[2] / 2;
101
- const s = (o.orthoScale && o.orthoScale > 0 ? W / o.orthoScale : Math.min((W / 2) * 0.86 / Math.max(halfW, 1e-6), (H / 2) * 0.82 / Math.max(halfH, 1e-6))) * zoom;
102
- return { name, persp: false, eye: c, f: v.f, r: v.r, u: v.u, c, focal: 0, scale: s };
187
+ if (o.orthoScale && o.orthoScale > 0)
188
+ return { name, persp: false, eye: c, f: v.f, r: v.r, u: v.u, c, focal: 0, scale: (W / o.orthoScale) * zoom, ox: W / 2, oy: H / 2 };
189
+ const q = fit(v.r, v.u, null, c);
190
+ const s0 = Math.min((W / 2) * FIT_W / Math.max(q.hx, 1e-6), (H / 2) * FIT_H / Math.max(q.hy, 1e-6));
191
+ const s = (Number.isFinite(s0) && s0 > 0 ? s0 : 1) * zoom;
192
+ return { name, persp: false, eye: c, f: v.f, r: v.r, u: v.u, c, focal: 0, scale: s, ox: W / 2 - q.cx * s, oy: H / 2 + q.cy * s };
103
193
  }
104
- /** Render the geometry; returns RGBA pixels. */
194
+ /**
195
+ * Render with the asynchronous preparation shading 'pbr' needs (MikkTSpace, texture files through readFile, usually
196
+ * Host.readFile); every other mode renders exactly as renderGeometry does.
197
+ */
198
+ export async function renderGeometryAsync(g, o = {}, readFile) {
199
+ if (o.shading === 'pbr' && !o.pbrTextures)
200
+ o = { ...o, pbrTextures: await preparePBR(g, readFile) };
201
+ if (o.underlay && !o.underlayImage)
202
+ o = { ...o, underlayImage: await readUnderlay(o.underlay, readFile) };
203
+ return renderGeometry(g, o);
204
+ }
205
+ /** A reference image for the underlay option: a PNG read through readFile (errors say what to pass instead). */
206
+ export async function readUnderlay(p, readFile) {
207
+ if (!readFile)
208
+ throw new Error(`render: underlay "${p}": no file access in this render`);
209
+ let bytes;
210
+ try {
211
+ bytes = await readFile(p);
212
+ }
213
+ catch (e) {
214
+ throw new Error(`render: underlay "${p}" cannot be read (${e?.message ?? e})`);
215
+ }
216
+ if (!(bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47))
217
+ throw new Error(`render: underlay "${p}" is not a PNG (only PNG reference images are read; convert it to PNG)`);
218
+ let img;
219
+ try {
220
+ img = decodePNG(bytes);
221
+ }
222
+ catch (e) {
223
+ throw new Error(`render: underlay "${p}" is not a readable PNG (${e?.message ?? e})`);
224
+ }
225
+ // 8-bit RGBA whatever the PNG holds (grey, grey + alpha, RGB, RGBA; 16-bit samples scaled down)
226
+ const n = img.width * img.height, ch = img.channels, rgba = new Uint8Array(n * 4);
227
+ const max = img.maxValue;
228
+ for (let i = 0; i < n; i++) {
229
+ const s = (k) => Math.round((img.data[i * ch + k] / max) * 255);
230
+ const grey = ch <= 2;
231
+ rgba[i * 4] = s(0);
232
+ rgba[i * 4 + 1] = grey ? s(0) : s(1);
233
+ rgba[i * 4 + 2] = grey ? s(0) : s(2);
234
+ rgba[i * 4 + 3] = ch === 2 ? s(1) : ch === 4 ? s(3) : 255;
235
+ }
236
+ return { width: img.width, height: img.height, rgba };
237
+ }
238
+ /** Render the geometry; returns RGBA pixels. Shading 'pbr' needs renderGeometryAsync first (or MikkTSpace loaded). */
105
239
  export function renderGeometry(g, o = {}) {
106
240
  // packed instances are drawn expanded (within a triangle budget), spline curves as polylines, see core/packed.ts
107
241
  if (g.hasPacked() || g.hasSplines()) {
@@ -111,17 +245,49 @@ export function renderGeometry(g, o = {}) {
111
245
  r.notes.unshift(...x.notes);
112
246
  return r;
113
247
  }
114
- g = withHeightfieldPreview(g); // heightfields draw as their (decimated) grid mesh with layers as attributes
248
+ // heightfields draw as their grid mesh with layers as attributes, decimated to heightfieldRes quads per side
249
+ const hfRes = o.heightfieldRes ?? HEIGHTFIELD_RENDER_RES;
250
+ if (!(hfRes >= 1))
251
+ throw new Error(`heightfieldRes must be at least 1 (quads per side) or Infinity (every sample), got ${hfRes}`);
252
+ const hfShown = g.volumes.filter(isHeightfield).map((v) => ({ v, ...heightfieldPreviewStep(v, hfRes) })).filter((x) => x.step > 1);
253
+ const hfLayer = o.heightfieldLayer ?? 'mask', hfNotes = [];
254
+ let hfLegend = '';
255
+ if (o.heightfieldLayer !== undefined && hfLayer !== 'none') {
256
+ // a layer the person chose: said in the legend (with its range when it is not a 0..1 layer), or why it is not shown
257
+ if (!g.volumes.some(isHeightfield))
258
+ hfNotes.push('heightfield_layer: the geometry has no heightfield');
259
+ for (const v of g.volumes.filter(isHeightfield)) {
260
+ const a = v.layers.get(hfLayer), st = layerStats(a);
261
+ if (!st)
262
+ hfNotes.push(`heightfield_layer: heightfield "${v.name}" has no layer "${hfLayer}" (layers: ${[...v.layers.keys()].join(', ') || 'none'})`);
263
+ else if (!hfLegend)
264
+ hfLegend = `HEIGHTFIELD ${hfLayer.toUpperCase()} IN RED${hfLayer === 'mask' || (st.min >= 0 && st.max <= 1) ? '' : ` [${fmtNum(st.min)} .. ${fmtNum(st.max)}]`}`;
265
+ }
266
+ }
267
+ g = withHeightfieldPreview(g, hfRes, hfLayer);
115
268
  g = withSdfGridPreview(g); // sampled SDFs draw through the existing level-set mesher at preview resolution
269
+ // a material output: spheres wearing its materials, with their base colour maps unless textures is set
270
+ const matPreview = withMaterialPreview(g), materialOnly = matPreview !== g;
271
+ if (materialOnly) {
272
+ g = matPreview;
273
+ if (o.textures === undefined)
274
+ o = { ...o, textures: true };
275
+ }
116
276
  const vlist = typeof o.views === 'string' ? parseViews(o.views) : o.views;
117
277
  // images and nothing else to draw in 3D: the texture view (render/texview.ts)
118
278
  const onlyImages = !g.numPoints && g.volumes.length > 0 && g.volumes.every((v) => v.kind === 'image');
119
- const views = vlist?.length ? vlist : onlyImages ? ['texture'] : ['persp', 'front', 'right', 'top'];
279
+ const views = vlist?.length ? vlist : onlyImages ? ['texture'] : materialOnly ? ['persp'] : ['persp', 'front', 'right', 'top'];
120
280
  const ui = Math.max(1, Math.min(4, Math.round(o.scale ?? 1)));
121
- const tile = Math.max(128, Math.min(1600, Math.round(o.size ?? (views.length === 1 ? 800 : 512)))) * ui;
281
+ // tile size: n (square) or [width, height] pixels per view, before scale
282
+ const sz0 = o.size ?? (views.length === 1 ? 800 : 512);
283
+ const [sw, sh] = Array.isArray(sz0) ? sz0 : [sz0, sz0];
284
+ if (!(Number.isFinite(sw) && Number.isFinite(sh)))
285
+ throw new Error(`render: size expects pixels per view, n or [width, height], got ${JSON.stringify(o.size)}`);
286
+ const TW = Math.max(128, Math.min(1600, Math.round(sw))) * ui, TH = Math.max(128, Math.min(1600, Math.round(sh))) * ui;
122
287
  let ss = Math.max(1, Math.min(3, Math.round(o.ssaa ?? 2)));
123
288
  if (ui > 1)
124
- ss = Math.max(1, Math.min(ss, Math.floor(4096 / tile)));
289
+ ss = Math.max(1, Math.min(ss, Math.floor(4096 / Math.max(TW, TH))));
290
+ const transparent = !!o.transparent;
125
291
  const cols = views.length === 1 ? 1 : views.length <= 4 ? 2 : 3;
126
292
  const rows = Math.ceil(views.length / cols);
127
293
  // opt-in overlay options (validated: they arrive from MCP/CLI as free strings)
@@ -135,6 +301,16 @@ export function renderGeometry(g, o = {}) {
135
301
  if (o.shading && !SHADING_MODES.includes(o.shading))
136
302
  throw new Error(`unknown shading "${o.shading}" (use ${SHADING_MODES.join(', ')})`);
137
303
  const shadingMode = o.shading && o.shading !== 'default' ? o.shading : null;
304
+ // reference image behind the 3D views
305
+ const ulFit = o.underlayFit ?? 'bounds';
306
+ if (!UNDERLAY_FITS.includes(ulFit))
307
+ throw new Error(`unknown underlay_fit "${o.underlayFit}" (use ${UNDERLAY_FITS.join(', ')})`);
308
+ const ulOpacity = Math.max(0, Math.min(1, o.underlayOpacity ?? 0.5));
309
+ if (o.underlayOpacity !== undefined && !Number.isFinite(o.underlayOpacity))
310
+ throw new Error(`render: underlay_opacity expects 0..1, got ${o.underlayOpacity}`);
311
+ if (o.underlay && !o.underlayImage)
312
+ throw new Error('render: underlay needs the image read first (renderGeometryAsync reads it)');
313
+ const ul = o.underlayImage && !o.transparent ? o.underlayImage : null;
138
314
  const hasSection = views.includes('section');
139
315
  const secK = AXES.indexOf(o.sectionAxis ?? 'y');
140
316
  if (secK < 0)
@@ -142,38 +318,34 @@ export function renderGeometry(g, o = {}) {
142
318
  const clipK = o.clip ? AXES.indexOf(o.clip.axis) : -1;
143
319
  if (o.clip && clipK < 0)
144
320
  throw new Error(`unknown clip axis "${o.clip.axis}" (use x, y or z)`);
145
- const annotate = o.annotate ?? !!(wireMode || o.pointNumbers || o.primNumbers || hasSection || clipK >= 0 || glyphMode || o.labelGroups || o.labelPieces || o.labelAttrib || o.legend || shadingMode);
146
- const footerH = 22 * ui + (annotate ? 16 * ui : 0);
321
+ const annotate = o.annotate ?? !!(wireMode || o.pointNumbers || o.primNumbers || hasSection || clipK >= 0 || glyphMode || o.labelGroups || o.labelPieces || o.labelAttrib || o.legend || shadingMode || o.sockets);
322
+ // a heightfield drawn at fewer samples than it has: said on the second footer line (unless annotate is false)
323
+ const hfLine = hfShown.map((x) => `HEIGHTFIELD ${hfShown.length > 1 ? x.v.name.toUpperCase() + ' ' : ''}SHOWN AT ${x.shown[0]}×${x.shown[1]} OF ${x.v.width}×${x.v.height}`).join(' · ');
324
+ const hfFooter = !!hfLine && o.annotate !== false;
325
+ const footerH = 22 * ui + (annotate || hfFooter ? 16 * ui : 0);
147
326
  const viewLabels = o.viewLabels ?? true;
148
- const outW = cols * tile + (cols - 1) * 2, outH = rows * tile + (rows - 1) * 2 + footerH;
149
- const notes = [];
327
+ const outW = cols * TW + (cols - 1) * 2, outH = rows * TH + (rows - 1) * 2 + footerH;
328
+ const notes = hfShown.map((x) => `heightfield "${x.v.name}" shown at ${x.shown[0]}×${x.shown[1]} of ${x.v.width}×${x.v.height} samples (1 in ${x.step} per side); heightfield_res "full" (CLI --heightfield-res full) draws every sample`);
329
+ notes.push(...hfNotes);
330
+ if ((o.zoom ?? 1) > 1 && !zoomFramed(o))
331
+ notes.push(`zoom ${fmtNum(o.zoom)}: held at 1, the fit (the views fit the bounds; a zoom above 1 would crop them): add look_at [x, y, z] to zoom into a point`);
332
+ if (o.underlayImage && o.transparent)
333
+ notes.push('underlay: not drawn on a transparent background');
150
334
  // --- scene data shared by all views
151
335
  const Pd = g.P, np = g.numPoints;
152
336
  const bb = g.bbox(true);
153
337
  const bmin = bb.min, bmax = bb.max;
338
+ const fitPts = fitPoints(g, bmin, bmax);
154
339
  const { tris, triPrim } = triangulate(g);
155
340
  const nTri = tris.length / 3;
156
341
  if (nTri > 4e6)
157
342
  notes.push(`large mesh (${nTri} triangles) — render may be slow`);
158
343
  const vnorm = nTri ? resolveVertexNormals(g, 50) : new Float64Array(0);
159
344
  const nrmOf = (v, out) => { out[0] = vnorm[v * 3]; out[1] = vnorm[v * 3 + 1]; out[2] = vnorm[v * 3 + 2]; };
160
- // back faces are only suspicious on closed pieces; open sheets/cards are shaded two-sided
161
- const conn = nTri ? connectivity(g) : null;
162
- const closedPiece = new Uint8Array(conn ? conn.count : 0).fill(1);
163
- let openEdges = 0, nonManifoldEdges = 0;
164
- if (conn && nTri) {
165
- const E0 = buildEdges(g);
166
- for (let e = 0; e < E0.a.length; e++)
167
- if (E0.count[e] !== 2)
168
- closedPiece[conn.primClass[E0.firstPrim[e]]] = 0;
169
- if (annotate)
170
- for (let e = 0; e < E0.a.length; e++) {
171
- if (E0.count[e] === 1 && g.primClosed[E0.firstPrim[e]])
172
- openEdges++;
173
- else if (E0.count[e] > 2)
174
- nonManifoldEdges++;
175
- }
176
- }
345
+ // back faces are only suspicious on closed pieces (closed once the vertex splits of uv / normal seams are welded, as
346
+ // an imported mesh has them); open sheets / cards are shaded two-sided. The pieces are the welded ones (core/report.ts).
347
+ const solid = nTri ? solidReport(g, { tri: { tris, triPrim }, flips: false }) : null;
348
+ const pieceOf = solid ? solid.primPiece : new Int32Array(0), closedPiece = solid ? solid.pieceClosed : new Uint8Array(0);
177
349
  // --- colours per vertex (Cd, colour-by, highlight)
178
350
  const vprim = g.vertexPrims();
179
351
  const BASE = [0.78, 0.74, 0.68];
@@ -268,6 +440,12 @@ export function renderGeometry(g, o = {}) {
268
440
  return c[0] === 1 && c[1] === 1 && c[2] === 1 ? m.baseColor : c;
269
441
  };
270
442
  }
443
+ // the heightfield layer a person chose to see in red
444
+ if (hfLegend) {
445
+ legend = hfLegend;
446
+ if (o.legend)
447
+ cbLegend = [{ color: [0.9, 0.12, 0.1], text: hfLegend.replace(' IN RED', '').toLowerCase() }];
448
+ }
271
449
  }
272
450
  const hl = o.highlight;
273
451
  if (hl) {
@@ -287,19 +465,32 @@ export function renderGeometry(g, o = {}) {
287
465
  cbLegend.push({ color: HC, text: `${hl.label ?? 'GROUP'} (${n} ${hl.cls}s)` });
288
466
  }
289
467
  const colorByActive = !!o.colorBy || !!hl;
468
+ const pbrTint = colorByActive && o.shading === 'pbr';
290
469
  // isolated points + polylines
291
470
  const used = new Uint8Array(np);
292
471
  for (let v = 0; v < g.numVertices; v++)
293
472
  used[g.vertexPoint[v]] = 1;
473
+ // scene empties (sockets: isolated points marked scene_empty 1): drawn by the sockets overlay when asked, and not as
474
+ // loose points in pbr (beauty) renders
475
+ const emptyA = g.points.get(EMPTY_ATTRIB);
476
+ const isEmpty = emptyA && emptyA.type === 'int' && emptyA.size === 1 ? (i) => !used[i] && emptyA.data[i] !== 0 : () => false;
477
+ const hideEmpties = !!o.sockets || o.shading === 'pbr';
294
478
  let isolated = 0;
295
479
  for (let i = 0; i < np; i++)
296
- if (!used[i])
480
+ if (!used[i] && !(hideEmpties && isEmpty(i)))
297
481
  isolated++;
298
482
  const showAllPts = o.points === true;
299
483
  const drawPts = showAllPts || (o.points !== false && isolated > 0);
300
484
  const closedPrims = g.primClosed.reduce((s, c) => s + c, 0);
301
485
  // the classic auto wireframe; the new edge overlays (wireMode) replace it
302
- const wire = !wireMode && o.wireframe !== 'none' && (o.wireframe === true || (o.wireframe !== false && closedPrims > 0 && closedPrims <= 6000));
486
+ // auto (the default): on below 6,000 polygons, but never over a material look (pbr shading or texture maps), where the
487
+ // edges read as a defect of the material; when auto draws them the footer says so
488
+ const autoWire = o.wireframe === undefined || o.wireframe === 'auto';
489
+ const wire = !wireMode && o.wireframe !== 'none' && (o.wireframe === true
490
+ || (autoWire && closedPrims > 0 && closedPrims <= AUTO_WIRE_MAX && o.shading !== 'pbr' && !o.textures));
491
+ const autoEdgesShown = wire && autoWire && views.some((v) => v !== 'uv' && v !== 'texture');
492
+ if (autoEdgesShown)
493
+ notes.push('wireframe auto: polygon edges drawn (wireframe false hides them)');
303
494
  const edges = wire ? buildEdges(g) : null;
304
495
  // triangle-dominant meshes (boolean/remesh output): hide edges between coplanar faces so the
305
496
  // wireframe shows shape, not triangulation slivers
@@ -330,19 +521,27 @@ export function renderGeometry(g, o = {}) {
330
521
  out[i + 1] = 0.12;
331
522
  out[i + 2] = 0.13;
332
523
  }
524
+ // transparent: alpha per output pixel (0 between the views; the footer is opaque)
525
+ const outA = transparent ? new Float32Array(outW * outH) : null;
333
526
  // --- uv data (uv view, checker shading)
334
- const uvd = views.includes('uv') || o.checker || o.textures ? readUV(g) : null;
527
+ const materialNames = primMaterials(g), materialTable = readMaterials(g);
528
+ const hasMasks = Object.values(materialTable).some((m) => m.alphaMode === 'MASK');
529
+ const uvd = views.includes('uv') || o.checker || o.textures || hasMasks ? readUV(g) : null;
335
530
  const checkerOn = !!(o.checker && uvd);
336
531
  if (o.checker && !uvd)
337
532
  notes.push('checker: no uv attribute (run uv_project, uv_unwrap or uv_flatten first)');
338
533
  // base colour maps (image textures) on the mesh: texture × Cd (as glTF multiplies COLOR_0), off under checker / colour-by
339
- const texS = o.textures && uvd && !checkerOn && !o.colorBy && !o.highlight ? textureSampler(g, notes) : null;
534
+ const showTextureColor = !!(o.textures && !checkerOn && !o.colorBy && !o.highlight);
535
+ const texS = uvd && (showTextureColor || hasMasks) ? textureSampler(g, notes) : null;
340
536
  if (o.textures && !uvd && nTri)
341
537
  notes.push('textures: no uv attribute, maps not shown');
342
538
  else if (o.textures && uvd && !texS && !checkerOn)
343
539
  notes.push('textures: no material with an image base colour (texture_to_material)');
344
540
  const texCd = !!(texS && g.findAttrib('Cd', ['vertex', 'point', 'prim', 'detail']));
345
- const texRGB = [0, 0, 0];
541
+ const texRGB = [0, 0, 0, 1];
542
+ const alphaAttr = resolveAttr('Alpha');
543
+ const alphaOf = (v) => alphaAttr && alphaAttr.attr.type !== 'string' && !alphaAttr.attr.isArray
544
+ ? alphaAttr.attr.data[elemIndex(alphaAttr.cls, v) * alphaAttr.attr.size] : 1;
346
545
  // ---------------------------------------------------------------- opt-in overlays, shared by all views
347
546
  const ovDesc = []; // footer line 2: what is switched on
348
547
  if (pscale)
@@ -376,7 +575,18 @@ export function renderGeometry(g, o = {}) {
376
575
  // shading
377
576
  const flatN = shadingMode === 'flat' && nTri ? primNormals(g) : null;
378
577
  const matcap = shadingMode === 'matcap';
379
- if (shadingMode)
578
+ let pbrS = null;
579
+ if (shadingMode === 'pbr' && nTri) {
580
+ const ev = o.exposure ?? 0;
581
+ if (!Number.isFinite(ev))
582
+ throw new Error(`render: exposure expects a number of stops, got ${o.exposure}`);
583
+ pbrS = pbrScene(g, tris, triPrim, o.pbrTextures, ev, notes);
584
+ // color_by and highlight tint the shaded material (their colour, lit by its brightness); the checker is not shown
585
+ if (o.checker)
586
+ notes.push('pbr: checker is not shown under shading "pbr" (color_by and highlight tint the material)');
587
+ ovDesc.push(`SHADING PBR STUDIO EV ${fmtNum(ev)} (${pbrS.summary.toUpperCase()})`);
588
+ }
589
+ else if (shadingMode)
380
590
  ovDesc.push(`SHADING ${shadingMode.toUpperCase()}`);
381
591
  // section / clip planes
382
592
  const planeAt = (k, off, abs) => (abs ? off ?? 0 : bmin[k] + (bmax[k] - bmin[k]) * (off ?? 0.5));
@@ -388,7 +598,7 @@ export function renderGeometry(g, o = {}) {
388
598
  const key = `${k}:${c}`;
389
599
  let s = slices.get(key);
390
600
  if (!s) {
391
- s = nTri && conn ? sliceTriangles(Pd, g.vertexPoint, tris, (t) => conn.primClass[triPrim[t]], k, c) : { n: 0, seg: new Float64Array(0), piece: new Int32Array(0) };
601
+ s = nTri && solid ? sliceTriangles(Pd, g.vertexPoint, tris, (t) => pieceOf[triPrim[t]], k, c) : { n: 0, seg: new Float64Array(0), piece: new Int32Array(0) };
392
602
  slices.set(key, s);
393
603
  }
394
604
  return s;
@@ -601,7 +811,7 @@ export function renderGeometry(g, o = {}) {
601
811
  }
602
812
  }
603
813
  if (o.labelPieces && np) {
604
- const cn = conn ?? connectivity(g);
814
+ const cn = connectivity(g);
605
815
  const n = Math.min(cn.count, maxLabels);
606
816
  const idx = Array.from({ length: n }, () => []);
607
817
  for (let i = 0; i < np; i++)
@@ -629,8 +839,32 @@ export function renderGeometry(g, o = {}) {
629
839
  notes.push(`point numbers: first ${maxLabels} of ${np} points (max_labels)`);
630
840
  ovDesc.push('POINT NUMBERS');
631
841
  }
842
+ // sockets: a dot, the name and short orient axes per scene empty, drawn through surfaces (sockets often sit inside)
843
+ const sockets = [];
844
+ if (o.sockets) {
845
+ const ori = g.points.get('orient'), nameA = g.points.get('name');
846
+ const L = Math.max(1e-6, diag * 0.045);
847
+ for (let i = 0; i < np; i++) {
848
+ if (!isEmpty(i))
849
+ continue;
850
+ const q = ori && ori.type === 'float' && ori.size === 4 ? qNormalize(ori.get(i)) : [0, 0, 0, 1];
851
+ const axes = [];
852
+ for (let ax = 0; ax < 3; ax++) {
853
+ const d = qRotate(q, [ax === 0 ? 1 : 0, ax === 1 ? 1 : 0, ax === 2 ? 1 : 0]);
854
+ axes.push(d[0] * L, d[1] * L, d[2] * L);
855
+ }
856
+ sockets.push({ p: i, axes });
857
+ const nm = nameA && nameA.type === 'string' ? String(nameA.get(i) ?? '') : '';
858
+ wl.push({ x: Pd[i * 3], y: Pd[i * 3 + 1], z: Pd[i * 3 + 2], text: nm || `empty ${i}`, c: SOCKET_C, kind: 0 });
859
+ }
860
+ if (!sockets.length)
861
+ notes.push('sockets: the geometry has no scene empties (scene_null)');
862
+ else
863
+ legendItems.push({ color: SOCKET_C, text: `SOCKETS (${sockets.length})` });
864
+ ovDesc.push(`SOCKETS ${sockets.length}`);
865
+ }
632
866
  const bigLabels = wl.filter((l) => l.kind === 0).length;
633
- const nameFs = tile >= 400 * ui && bigLabels <= 40 ? 2 * ui : ui;
867
+ const nameFs = Math.min(TW, TH) >= 400 * ui && bigLabels <= 40 ? 2 * ui : ui;
634
868
  // glyphs: world segments (start = anchor) with a base and a tip colour
635
869
  const glSeg = [], glCol = [];
636
870
  const glPal = [];
@@ -729,37 +963,72 @@ export function renderGeometry(g, o = {}) {
729
963
  }
730
964
  if (o.legend && !cbLegend.length)
731
965
  notes.push('legend: nothing to explain (use with color_by or highlight)');
732
- const hasOverlay = oeA.length > 0 || dotPts.length > 0 || wl.length > 0 || glCol.length > 0 || legendItems.length > 0 || hasSection || clipK >= 0;
966
+ const hasOverlay = sockets.length > 0 || oeA.length > 0 || dotPts.length > 0 || wl.length > 0 || glCol.length > 0 || legendItems.length > 0 || hasSection || clipK >= 0;
733
967
  const legendView = views.findIndex((v) => v !== 'uv' && v !== 'texture');
734
- const backView = annotate ? views.findIndex((v) => v !== 'uv' && v !== 'texture' && v !== 'section' && !(clipK >= 0 && v.startsWith('persp'))) : -1;
968
+ const backView = annotate ? views.findIndex((v) => v !== 'uv' && v !== 'texture' && v !== 'section' && !(clipK >= 0 && isPerspView(v))) : -1;
735
969
  let backPix = 0, shadedPix = 0;
970
+ /** the prims whose back faces show (blue), by pixel count, in the view that counts them */
971
+ const backPrims = new Map();
736
972
  let labelsSkipped = 0;
737
973
  views.forEach((vname, vi) => {
738
- const W = tile * ss, H = tile * ss;
974
+ const W = TW * ss, H = TH * ss;
739
975
  const col = new Float32Array(W * H * 3);
740
- const tx = (vi % cols) * (tile + 2), ty = Math.floor(vi / cols) * (tile + 2);
741
- // downsample a finished tile into the output, draw the output-resolution overlays (post), label it
742
- const blit = (label, post) => {
976
+ const tx = (vi % cols) * (TW + 2), ty = Math.floor(vi / cols) * (TH + 2);
977
+ // downsample a finished tile into the output, draw the output-resolution overlays (post), label it. Transparent
978
+ // 3D views (zb given): alpha = the covered fraction of each pixel's samples and the colour of those samples alone;
979
+ // whatever post and the label draw is opaque
980
+ const blit = (label, post, zb) => {
743
981
  const inv = 1 / (ss * ss);
744
- for (let y = 0; y < tile; y++)
745
- for (let x = 0; x < tile; x++) {
746
- let r = 0, gg = 0, b = 0;
982
+ const cover = !!(outA && zb);
983
+ for (let y = 0; y < TH; y++)
984
+ for (let x = 0; x < TW; x++) {
985
+ let r = 0, gg = 0, b = 0, n = 0, cr = 0, cg = 0, cb = 0;
747
986
  for (let j = 0; j < ss; j++)
748
987
  for (let i = 0; i < ss; i++) {
749
- const k = ((y * ss + j) * W + x * ss + i) * 3;
988
+ const zi = (y * ss + j) * W + x * ss + i, k = zi * 3;
750
989
  r += col[k];
751
990
  gg += col[k + 1];
752
991
  b += col[k + 2];
992
+ if (cover && zb[zi] > -Infinity) {
993
+ n++;
994
+ cr += col[k];
995
+ cg += col[k + 1];
996
+ cb += col[k + 2];
997
+ }
753
998
  }
754
- const k = ((ty + y) * outW + tx + x) * 3;
755
- out[k] = r * inv;
756
- out[k + 1] = gg * inv;
757
- out[k + 2] = b * inv;
999
+ const o1 = (ty + y) * outW + tx + x, k = o1 * 3;
1000
+ if (!cover) {
1001
+ out[k] = r * inv;
1002
+ out[k + 1] = gg * inv;
1003
+ out[k + 2] = b * inv;
1004
+ if (outA)
1005
+ outA[o1] = 1;
1006
+ continue;
1007
+ }
1008
+ if (n) {
1009
+ out[k] = cr / n;
1010
+ out[k + 1] = cg / n;
1011
+ out[k + 2] = cb / n;
1012
+ }
1013
+ else {
1014
+ out[k] = r * inv;
1015
+ out[k + 1] = gg * inv;
1016
+ out[k + 2] = b * inv;
1017
+ }
1018
+ outA[o1] = n * inv;
758
1019
  }
1020
+ const snap = cover ? out.slice(ty * outW * 3, (ty + TH) * outW * 3) : null;
759
1021
  if (post)
760
1022
  post();
761
1023
  if (viewLabels)
762
1024
  drawText(out, outW, outH, tx + 6 * ui, ty + 6 * ui, label, [1, 1, 1], 2 * ui);
1025
+ if (snap)
1026
+ for (let y = 0; y < TH; y++)
1027
+ for (let x = 0; x < TW; x++) {
1028
+ const o1 = (ty + y) * outW + tx + x, k = o1 * 3, q = (y * outW + tx + x) * 3;
1029
+ if (out[k] !== snap[q] || out[k + 1] !== snap[q + 1] || out[k + 2] !== snap[q + 2])
1030
+ outA[o1] = 1;
1031
+ }
763
1032
  };
764
1033
  if (vname === 'uv') {
765
1034
  blit(drawUVView(g, col, W, H, ss * ui, uvd, tris, colorOf, colorByActive, notes));
@@ -769,8 +1038,8 @@ export function renderGeometry(g, o = {}) {
769
1038
  blit(drawTextureView(g, col, W, H, ss * ui, o.texture ?? '', notes));
770
1039
  return;
771
1040
  }
772
- const kind = vname.startsWith('persp') ? 'persp' : vname;
773
- const azDeg = vname.startsWith('persp@') ? Number(vname.slice(6)) : undefined;
1041
+ const kind = isPerspView(vname) ? 'persp' : vname;
1042
+ const azDeg = vname.startsWith('persp@') ? Number(vname.slice(6)) : NAMED_VIEWS[vname];
774
1043
  const zb = new Float32Array(W * H).fill(-Infinity);
775
1044
  for (let y = 0; y < H; y++) {
776
1045
  const t = y / H;
@@ -782,7 +1051,9 @@ export function renderGeometry(g, o = {}) {
782
1051
  col[i + 2] = b;
783
1052
  }
784
1053
  }
785
- const cam = makeCam(vname, bmin, bmax, W, H, o, kind, azDeg, secK);
1054
+ const cam = makeCam(vname, bmin, bmax, W, H, o, kind, azDeg, secK, fitPts);
1055
+ if (pbrS)
1056
+ pbrS.camera(cam.r, cam.u, cam.f);
786
1057
  // project points
787
1058
  const sx = new Float32Array(np), sy = new Float32Array(np), cz = new Float32Array(np), vz = new Float32Array(np);
788
1059
  const project = (x, y, z, outp) => {
@@ -791,14 +1062,14 @@ export function renderGeometry(g, o = {}) {
791
1062
  const Y = dx * cam.u[0] + dy * cam.u[1] + dz * cam.u[2];
792
1063
  const Z = dx * cam.f[0] + dy * cam.f[1] + dz * cam.f[2];
793
1064
  if (cam.persp) {
794
- outp[0] = W / 2 + (X / Z) * cam.focal;
795
- outp[1] = H / 2 - (Y / Z) * cam.focal;
1065
+ outp[0] = cam.ox + (X / Z) * cam.focal;
1066
+ outp[1] = cam.oy - (Y / Z) * cam.focal;
796
1067
  outp[2] = Z > 1e-6 ? 1 / Z : -Infinity;
797
1068
  outp[3] = Z;
798
1069
  }
799
1070
  else {
800
- outp[0] = W / 2 + X * cam.scale;
801
- outp[1] = H / 2 - Y * cam.scale;
1071
+ outp[0] = cam.ox + X * cam.scale;
1072
+ outp[1] = cam.oy - Y * cam.scale;
802
1073
  outp[2] = -Z;
803
1074
  outp[3] = Z;
804
1075
  }
@@ -844,8 +1115,29 @@ export function renderGeometry(g, o = {}) {
844
1115
  return !(cam.persp && (q0[3] < 1e-4 || q1[3] < 1e-4));
845
1116
  };
846
1117
  const keptPt = (i) => !clipOn || (Pd[i * 3 + cK] - cC) * cS <= 0;
1118
+ // reference image behind the view, placed by underlayFit against the rectangle the bounds cover in this view
1119
+ if (ul && kind !== 'section') {
1120
+ let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;
1121
+ const q = [0, 0, 0, 0];
1122
+ for (let k = 0; k < 8; k++) {
1123
+ project(k & 1 ? bmax[0] : bmin[0], k & 2 ? bmax[1] : bmin[1], k & 4 ? bmax[2] : bmin[2], q);
1124
+ x0 = Math.min(x0, q[0]);
1125
+ x1 = Math.max(x1, q[0]);
1126
+ y0 = Math.min(y0, q[1]);
1127
+ y1 = Math.max(y1, q[1]);
1128
+ }
1129
+ if (ulFit === 'view' || !(x1 > x0) || !(y1 > y0)) {
1130
+ x0 = 0;
1131
+ x1 = W;
1132
+ y0 = 0;
1133
+ y1 = H;
1134
+ }
1135
+ const bw = x1 - x0, bh = y1 - y0, ia = ul.width / ul.height;
1136
+ const w = ulFit === 'width' ? bw : ulFit === 'height' ? bh * ia : Math.min(bw, bh * ia), h = w / ia;
1137
+ drawUnderlay(col, W, H, ul, (x0 + x1) / 2 - w / 2, (y0 + y1) / 2 - h / 2, w, h, ulOpacity);
1138
+ }
847
1139
  // ground grid (persp only), drawn first without depth
848
- if (kind === 'persp' && o.grid !== false) {
1140
+ if (kind === 'persp' && (o.grid ?? !transparent)) {
849
1141
  const step = Math.pow(10, Math.floor(Math.log10(sceneR * 0.5)));
850
1142
  const ext = Math.ceil((sceneR * 1.6) / step) * step;
851
1143
  const cx = Math.round(cam.c[0] / step) * step, czz = Math.round(cam.c[2] / step) * step;
@@ -873,7 +1165,8 @@ export function renderGeometry(g, o = {}) {
873
1165
  const na = [0, 0, 0], nb = [0, 0, 0], nc = [0, 0, 0];
874
1166
  const tn = [0, 0, 0];
875
1167
  const chk = [0, 0, 0];
876
- const bf = vi === backView ? new Uint8Array(W * H) : null;
1168
+ const pbrUV0 = [0, 0], pbrUV1 = [0, 0], pbrUV2 = [0, 0], pbrV = [0, 0, 0], pbrRGB = [0, 0, 0];
1169
+ const bf = vi === backView ? new Uint8Array(W * H) : null, bfPrim = bf ? new Int32Array(W * H) : null;
877
1170
  for (let t = 0; t < nTri; t++) {
878
1171
  const va = tris[t * 3], vb = tris[t * 3 + 1], vc = tris[t * 3 + 2];
879
1172
  const a = g.vertexPoint[va], b = g.vertexPoint[vb], c = g.vertexPoint[vc];
@@ -903,7 +1196,9 @@ export function renderGeometry(g, o = {}) {
903
1196
  const fnw = cross3(e1, e2);
904
1197
  const toCam = cam.persp ? [cam.eye[0] - Pd[a * 3], cam.eye[1] - Pd[a * 3 + 1], cam.eye[2] - Pd[a * 3 + 2]] : [-cam.f[0], -cam.f[1], -cam.f[2]];
905
1198
  const back = dot3(fnw, toCam) < 0;
906
- const suspicious = back && conn !== null && closedPiece[conn.primClass[triPrim[t]]] === 1;
1199
+ const material = materialNames ? materialTable[materialNames[triPrim[t]]] : undefined;
1200
+ const alphaMask = material?.alphaMode === 'MASK';
1201
+ const suspicious = back && !material?.doubleSided && solid !== null && closedPiece[pieceOf[triPrim[t]]] === 1;
907
1202
  if (flatN) {
908
1203
  const p = triPrim[t] * 3;
909
1204
  na[0] = nb[0] = nc[0] = flatN[p];
@@ -922,6 +1217,7 @@ export function renderGeometry(g, o = {}) {
922
1217
  toCamSpace(nb, cb);
923
1218
  toCamSpace(nc, cc);
924
1219
  let colA = colorOf(va), colB = colorOf(vb), colC = colorOf(vc);
1220
+ const tA = colA, tB = colB, tC = colC; // before the back-face tint: the pbr colour tint
925
1221
  if (suspicious) {
926
1222
  const tint = (q) => [q[0] * 0.35 + 0.12, q[1] * 0.35 + 0.22, q[2] * 0.35 + 0.6];
927
1223
  colA = tint(colA);
@@ -930,6 +1226,8 @@ export function renderGeometry(g, o = {}) {
930
1226
  }
931
1227
  const za = cz[a], zb2 = cz[b], zc = cz[c];
932
1228
  const inv = 1 / area;
1229
+ // shading 'pbr': screen-space gradients of the affine weights (uv derivatives for the texture level of detail)
1230
+ const g0x = (by - cy) * inv, g0y = (cx - bx) * inv, g1x = (cy - ay) * inv, g1y = (ax - cx) * inv;
933
1231
  // base colour map: mip level from the triangle's texels per screen pixel (render/texview.ts)
934
1232
  const texP = texS && texS.has(triPrim[t]) ? triPrim[t] : -1;
935
1233
  let texLod = 0;
@@ -962,15 +1260,77 @@ export function renderGeometry(g, o = {}) {
962
1260
  if ((p0 * qa + p1 * qb + p2 * qc - cC) * cS > 0)
963
1261
  continue;
964
1262
  }
965
- zb[zi] = depth;
966
- if (bf)
967
- bf[zi] = suspicious ? 1 : 0;
1263
+ const aw0 = w0, aw1 = w1;
968
1264
  if (cam.persp) {
969
1265
  const s = w0 * za + w1 * zb2 + w2 * zc;
970
1266
  w0 = (w0 * za) / s;
971
1267
  w1 = (w1 * zb2) / s;
972
1268
  w2 = 1 - w0 - w1;
973
1269
  }
1270
+ if (alphaMask) {
1271
+ let alpha = material.alpha * (alphaOf(va) * w0 + alphaOf(vb) * w1 + alphaOf(vc) * w2);
1272
+ if (texP >= 0) {
1273
+ texS.sample(texP, uvd[va * 2] * w0 + uvd[vb * 2] * w1 + uvd[vc * 2] * w2, uvd[va * 2 + 1] * w0 + uvd[vb * 2 + 1] * w1 + uvd[vc * 2 + 1] * w2, texLod, texRGB);
1274
+ alpha *= texRGB[3];
1275
+ }
1276
+ if (alpha < (material.alphaCutoff ?? 0.5))
1277
+ continue;
1278
+ }
1279
+ zb[zi] = depth;
1280
+ if (bf) {
1281
+ bf[zi] = suspicious ? 1 : 0;
1282
+ bfPrim[zi] = triPrim[t];
1283
+ }
1284
+ if (pbrS) {
1285
+ let dudx = 0, dvdx = 0, dudy = 0, dvdy = 0;
1286
+ if (pbrS.hasUV) {
1287
+ const at = (q0, q1, out) => {
1288
+ let p0 = q0, p1 = q1;
1289
+ if (cam.persp) {
1290
+ const s = q0 * za + q1 * zb2 + (1 - q0 - q1) * zc;
1291
+ p0 = (q0 * za) / s;
1292
+ p1 = (q1 * zb2) / s;
1293
+ }
1294
+ pbrS.uvAt(t, p0, p1, 1 - p0 - p1, out);
1295
+ };
1296
+ at(aw0, aw1, pbrUV0);
1297
+ at(aw0 + g0x, aw1 + g1x, pbrUV1);
1298
+ at(aw0 + g0y, aw1 + g1y, pbrUV2);
1299
+ dudx = pbrUV1[0] - pbrUV0[0];
1300
+ dvdx = pbrUV1[1] - pbrUV0[1];
1301
+ dudy = pbrUV2[0] - pbrUV0[0];
1302
+ dvdy = pbrUV2[1] - pbrUV0[1];
1303
+ }
1304
+ if (cam.persp) {
1305
+ const px3 = Pd[a * 3] * w0 + Pd[b * 3] * w1 + Pd[c * 3] * w2, py3 = Pd[a * 3 + 1] * w0 + Pd[b * 3 + 1] * w1 + Pd[c * 3 + 1] * w2, pz3 = Pd[a * 3 + 2] * w0 + Pd[b * 3 + 2] * w1 + Pd[c * 3 + 2] * w2;
1306
+ const vx = cam.eye[0] - px3, vy = cam.eye[1] - py3, vz2 = cam.eye[2] - pz3, vl = Math.hypot(vx, vy, vz2) || 1;
1307
+ pbrV[0] = vx / vl;
1308
+ pbrV[1] = vy / vl;
1309
+ pbrV[2] = vz2 / vl;
1310
+ }
1311
+ else {
1312
+ pbrV[0] = -cam.f[0];
1313
+ pbrV[1] = -cam.f[1];
1314
+ pbrV[2] = -cam.f[2];
1315
+ }
1316
+ pbrS.shade(t, w0, w1, w2, dudx, dvdx, dudy, dvdy, pbrV, back, pbrRGB);
1317
+ const ci = zi * 3;
1318
+ if (pbrTint) {
1319
+ // the attribute colour lit by the material's brightness, over a third of the material itself
1320
+ const lum = Math.min(1.2, 0.12 + 1.5 * (0.2126 * pbrRGB[0] + 0.7152 * pbrRGB[1] + 0.0722 * pbrRGB[2]));
1321
+ for (let k = 0; k < 3; k++)
1322
+ pbrRGB[k] = pbrRGB[k] * 0.35 + (tA[k] * w0 + tB[k] * w1 + tC[k] * w2) * lum * 0.65;
1323
+ }
1324
+ if (suspicious) {
1325
+ pbrRGB[0] = pbrRGB[0] * 0.35 + 0.12;
1326
+ pbrRGB[1] = pbrRGB[1] * 0.35 + 0.22;
1327
+ pbrRGB[2] = pbrRGB[2] * 0.35 + 0.6;
1328
+ }
1329
+ col[ci] = pbrRGB[0];
1330
+ col[ci + 1] = pbrRGB[1];
1331
+ col[ci + 2] = pbrRGB[2];
1332
+ continue;
1333
+ }
974
1334
  tn[0] = ca[0] * w0 + cb[0] * w1 + cc[0] * w2;
975
1335
  tn[1] = ca[1] * w0 + cb[1] * w1 + cc[1] * w2;
976
1336
  tn[2] = ca[2] * w0 + cb[2] * w1 + cc[2] * w2;
@@ -1011,7 +1371,7 @@ export function renderGeometry(g, o = {}) {
1011
1371
  fb = fb * 0.35 + 0.6;
1012
1372
  }
1013
1373
  }
1014
- else if (texP >= 0) {
1374
+ else if (texP >= 0 && showTextureColor) {
1015
1375
  texS.sample(texP, uvd[va * 2] * w0 + uvd[vb * 2] * w1 + uvd[vc * 2] * w2, uvd[va * 2 + 1] * w0 + uvd[vb * 2 + 1] * w1 + uvd[vc * 2 + 1] * w2, texLod, texRGB);
1016
1376
  if (texCd) {
1017
1377
  fr *= texRGB[0];
@@ -1040,12 +1400,14 @@ export function renderGeometry(g, o = {}) {
1040
1400
  if (zb[i] > -Infinity) {
1041
1401
  shadedPix++;
1042
1402
  backPix += bf[i];
1403
+ if (bf[i])
1404
+ backPrims.set(bfPrim[i], (backPrims.get(bfPrim[i]) ?? 0) + 1);
1043
1405
  }
1044
1406
  // screen-space ambient occlusion on the shaded surface (before lines and points, which stay crisp)
1045
1407
  if (shadingMode === 'ao' && nTri) {
1046
- const T = tile, lin = new Float32Array(T * T);
1047
- for (let y = 0; y < T; y++)
1048
- for (let x = 0; x < T; x++) {
1408
+ const lin = new Float32Array(TW * TH);
1409
+ for (let y = 0; y < TH; y++)
1410
+ for (let x = 0; x < TW; x++) {
1049
1411
  let m = -Infinity;
1050
1412
  for (let j = 0; j < ss; j++)
1051
1413
  for (let i = 0; i < ss; i++) {
@@ -1053,15 +1415,15 @@ export function renderGeometry(g, o = {}) {
1053
1415
  if (z > m)
1054
1416
  m = z;
1055
1417
  }
1056
- lin[y * T + x] = m === -Infinity ? Infinity : cam.persp ? 1 / m : -m;
1418
+ lin[y * TW + x] = m === -Infinity ? Infinity : cam.persp ? 1 / m : -m;
1057
1419
  }
1058
- const aoF = ambientOcclusion(lin, T, T, (o.aoRadius ?? 10) * ui, cam.persp ? (z) => (z * ss) / cam.focal : () => ss / cam.scale);
1420
+ const aoF = ambientOcclusion(lin, TW, TH, (o.aoRadius ?? 10) * ui, cam.persp ? (z) => (z * ss) / cam.focal : () => ss / cam.scale);
1059
1421
  for (let y = 0; y < H; y++)
1060
1422
  for (let x = 0; x < W; x++) {
1061
1423
  const zi = y * W + x;
1062
1424
  if (zb[zi] === -Infinity)
1063
1425
  continue;
1064
- const f = aoF[Math.floor(y / ss) * T + Math.floor(x / ss)];
1426
+ const f = aoF[Math.floor(y / ss) * TW + Math.floor(x / ss)];
1065
1427
  col[zi * 3] *= f;
1066
1428
  col[zi * 3 + 1] *= f;
1067
1429
  col[zi * 3 + 2] *= f;
@@ -1108,6 +1470,8 @@ export function renderGeometry(g, o = {}) {
1108
1470
  for (let i = 0; i < np; i++) {
1109
1471
  if (!showAllPts && used[i])
1110
1472
  continue;
1473
+ if (hideEmpties && isEmpty(i))
1474
+ continue;
1111
1475
  if (cam.persp && vz[i] < 1e-4)
1112
1476
  continue;
1113
1477
  if (clipOn && !keptPt(i))
@@ -1216,9 +1580,9 @@ export function renderGeometry(g, o = {}) {
1216
1580
  const grid = windingGrid(seg2, m, gx, gy);
1217
1581
  const e = cam.eye, f = cam.f, r = cam.r, u = cam.u;
1218
1582
  for (let py = 0; py < H; py++) {
1219
- const dy = (H / 2 - (py + 0.5)) / cam.focal;
1583
+ const dy = (cam.oy - (py + 0.5)) / cam.focal;
1220
1584
  for (let px = 0; px < W; px++) {
1221
- const dx = (px + 0.5 - W / 2) / cam.focal;
1585
+ const dx = (px + 0.5 - cam.ox) / cam.focal;
1222
1586
  const dk = f[cK] + r[cK] * dx + u[cK] * dy;
1223
1587
  const t = (cC - e[cK]) / dk;
1224
1588
  if (!(t > 1e-6))
@@ -1241,7 +1605,7 @@ export function renderGeometry(g, o = {}) {
1241
1605
  }
1242
1606
  }
1243
1607
  // axis gizmo
1244
- if (kind === 'persp' && viewLabels) {
1608
+ if (kind === 'persp' && viewLabels && !transparent) {
1245
1609
  const ox = 34 * ss * ui, oy = H - 34 * ss * ui, len = 22 * ss * ui;
1246
1610
  for (const [ax, colr, lab] of [[[1, 0, 0], [0.95, 0.3, 0.3], 'X'], [[0, 1, 0], [0.4, 0.9, 0.4], 'Y'], [[0, 0, 1], [0.4, 0.6, 1], 'Z']]) {
1247
1611
  const ex = ox + dot3(ax, cam.r) * len, ey = oy - dot3(ax, cam.u) * len;
@@ -1249,15 +1613,15 @@ export function renderGeometry(g, o = {}) {
1249
1613
  drawText(col, W, H, Math.round(ex + 2 * ss * ui), Math.round(ey - 4 * ss * ui), lab, colr, ss * ui, true);
1250
1614
  }
1251
1615
  }
1252
- const viewLabel = (kind === 'persp' ? `PERSP AZ ${Math.round(azDeg ?? o.azimuth ?? 35)} EL ${Math.round(o.elevation ?? 25)}`
1616
+ const viewLabel = (kind === 'persp' ? `${NAMED_VIEWS[vname] !== undefined ? vname.toUpperCase().replace('_', ' ') : 'PERSP'} AZ ${Math.round(azDeg ?? o.azimuth ?? 35)} EL ${Math.round(o.elevation ?? 25)}`
1253
1617
  : kind === 'section' ? `SECTION ${planeDesc(secK, secC)} ${SECTION_CAM[secK].label.split(' ')[1]}`
1254
1618
  : ORTHO[vname].label) + (checkerOn ? ' CHECKER' : '') + (clipOn && kind === 'persp' ? ` CLIP ${planeDesc(cK, cC)}` : '');
1255
1619
  // output-resolution overlays: crisp 1 px lines, glyphs, cut outlines, labels, legend
1256
1620
  const post = !hasOverlay ? undefined : () => {
1257
- const T = tile, inv = 1 / ss;
1258
- const zt = new Float32Array(T * T); // nearest depth per output pixel
1259
- for (let y = 0; y < T; y++)
1260
- for (let x = 0; x < T; x++) {
1621
+ const inv = 1 / ss;
1622
+ const zt = new Float32Array(TW * TH); // nearest depth per output pixel
1623
+ for (let y = 0; y < TH; y++)
1624
+ for (let x = 0; x < TW; x++) {
1261
1625
  let m = -Infinity;
1262
1626
  for (let j = 0; j < ss; j++)
1263
1627
  for (let i = 0; i < ss; i++) {
@@ -1265,17 +1629,17 @@ export function renderGeometry(g, o = {}) {
1265
1629
  if (z > m)
1266
1630
  m = z;
1267
1631
  }
1268
- zt[y * T + x] = m;
1632
+ zt[y * TW + x] = m;
1269
1633
  }
1270
- const tb = new Float32Array(T * T * 3);
1271
- for (let y = 0; y < T; y++)
1272
- tb.set(out.subarray(((ty + y) * outW + tx) * 3, ((ty + y) * outW + tx + T) * 3), y * T * 3);
1634
+ const tb = new Float32Array(TW * TH * 3);
1635
+ for (let y = 0; y < TH; y++)
1636
+ tb.set(out.subarray(((ty + y) * outW + tx) * 3, ((ty + y) * outW + tx + TW) * 3), y * TW * 3);
1273
1637
  const dtol = cam.persp ? { abs: 1e-7, rel: 0.006 } : { abs: sceneR * 0.006, rel: 0 };
1274
1638
  const hidden = (z, x, y) => {
1275
1639
  const xi = Math.floor(x), yi = Math.floor(y);
1276
- if (xi < 0 || yi < 0 || xi >= T || yi >= T)
1640
+ if (xi < 0 || yi < 0 || xi >= TW || yi >= TH)
1277
1641
  return true;
1278
- return z < zt[yi * T + xi] - 2 * (dtol.abs + Math.abs(z) * dtol.rel);
1642
+ return z < zt[yi * TW + xi] - 2 * (dtol.abs + Math.abs(z) * dtol.rel);
1279
1643
  };
1280
1644
  const dim = kind === 'section' ? 0.45 : 1;
1281
1645
  // edge overlays (wireframe modes, group borders)
@@ -1286,12 +1650,12 @@ export function renderGeometry(g, o = {}) {
1286
1650
  const st = styles[oeS[e]];
1287
1651
  if (clipOn) {
1288
1652
  if (clipProj(Pd[a * 3], Pd[a * 3 + 1], Pd[a * 3 + 2], Pd[b * 3], Pd[b * 3 + 1], Pd[b * 3 + 2]))
1289
- lineOv(tb, T, T, q0[0] * inv, q0[1] * inv, q0[2], q1[0] * inv, q1[1] * inv, q1[2], st.c, st.a * dim, ui, zt, dtol);
1653
+ lineOv(tb, TW, TH, q0[0] * inv, q0[1] * inv, q0[2], q1[0] * inv, q1[1] * inv, q1[2], st.c, st.a * dim, ui, zt, dtol);
1290
1654
  continue;
1291
1655
  }
1292
1656
  if (cam.persp && (vz[a] < 1e-4 || vz[b] < 1e-4))
1293
1657
  continue;
1294
- lineOv(tb, T, T, sx[a] * inv, sy[a] * inv, cz[a], sx[b] * inv, sy[b] * inv, cz[b], st.c, st.a * dim, ui, zt, dtol);
1658
+ lineOv(tb, TW, TH, sx[a] * inv, sy[a] * inv, cz[a], sx[b] * inv, sy[b] * inv, cz[b], st.c, st.a * dim, ui, zt, dtol);
1295
1659
  }
1296
1660
  // point-group members and glyphs (not in the section view, where they would float over the cut)
1297
1661
  const flat2d = kind === 'section';
@@ -1299,7 +1663,7 @@ export function renderGeometry(g, o = {}) {
1299
1663
  const i = dotPts[k];
1300
1664
  if (!keptPt(i) || (cam.persp && vz[i] < 1e-4) || hidden(cz[i], sx[i] * inv, sy[i] * inv))
1301
1665
  continue;
1302
- dotOv(tb, T, T, sx[i] * inv, sy[i] * inv, 2 * ui, styles[dotSt[k]].c);
1666
+ dotOv(tb, TW, TH, sx[i] * inv, sy[i] * inv, 2 * ui, styles[dotSt[k]].c);
1303
1667
  }
1304
1668
  // glyphs: anchored on visible surface points, parts behind the surface dimmed, brighter tip
1305
1669
  const m3 = [0, 0, 0, 0];
@@ -1313,9 +1677,23 @@ export function renderGeometry(g, o = {}) {
1313
1677
  const pal = glPal[glCol[k]];
1314
1678
  const mx = x0 + (x1 - x0) * 0.62, my = y0 + (y1 - y0) * 0.62, mz = z0 + (z1 - z0) * 0.62;
1315
1679
  if (clipProj(x0, y0, z0, mx, my, mz))
1316
- lineOv(tb, T, T, q0[0] * inv, q0[1] * inv, q0[2], q1[0] * inv, q1[1] * inv, q1[2], pal[0], 0.95 * dim, ui, zt, dtol, 0.3 * dim);
1680
+ lineOv(tb, TW, TH, q0[0] * inv, q0[1] * inv, q0[2], q1[0] * inv, q1[1] * inv, q1[2], pal[0], 0.95 * dim, ui, zt, dtol, 0.3 * dim);
1317
1681
  if (clipProj(mx, my, mz, x1, y1, z1))
1318
- lineOv(tb, T, T, q0[0] * inv, q0[1] * inv, q0[2], q1[0] * inv, q1[1] * inv, q1[2], pal[1], dim, ui, zt, dtol, 0.35 * dim);
1682
+ lineOv(tb, TW, TH, q0[0] * inv, q0[1] * inv, q0[2], q1[0] * inv, q1[1] * inv, q1[2], pal[1], dim, ui, zt, dtol, 0.35 * dim);
1683
+ }
1684
+ // sockets: orient axes and a dot, through surfaces (dimmer where hidden)
1685
+ for (const sk of (flat2d ? [] : sockets)) {
1686
+ const i = sk.p;
1687
+ if (!keptPt(i) || (cam.persp && vz[i] < 1e-4))
1688
+ continue;
1689
+ const x = sx[i] * inv, y = sy[i] * inv, hid = hidden(cz[i], x, y);
1690
+ for (let ax = 0; ax < 3; ax++) {
1691
+ project(Pd[i * 3] + sk.axes[ax * 3], Pd[i * 3 + 1] + sk.axes[ax * 3 + 1], Pd[i * 3 + 2] + sk.axes[ax * 3 + 2], m3);
1692
+ if (cam.persp && m3[3] < 1e-4)
1693
+ continue;
1694
+ lineOv(tb, TW, TH, x, y, 0, m3[0] * inv, m3[1] * inv, 0, glAxisC[ax], hid ? 0.55 : 1, ui, null, dtol);
1695
+ }
1696
+ dotOv(tb, TW, TH, x, y, 5 * ui, hid ? [SOCKET_C[0] * 0.6, SOCKET_C[1] * 0.6, SOCKET_C[2] * 0.6] : SOCKET_C);
1319
1697
  }
1320
1698
  // cut outlines: solid pieces dark, open sheets (no cap) yellow
1321
1699
  if (cut)
@@ -1326,16 +1704,16 @@ export function renderGeometry(g, o = {}) {
1326
1704
  if (cam.persp && (q0[3] < 1e-4 || q1[3] < 1e-4))
1327
1705
  continue;
1328
1706
  const solid = closedPiece[cut.piece[s]] === 1;
1329
- lineOv(tb, T, T, q0[0] * inv, q0[1] * inv, 0, q1[0] * inv, q1[1] * inv, 0, solid ? [0.1, 0.02, 0.02] : [1, 0.85, 0.3], solid ? 0.9 : 1, ui, null, dtol);
1707
+ lineOv(tb, TW, TH, q0[0] * inv, q0[1] * inv, 0, q1[0] * inv, q1[1] * inv, 0, solid ? [0.1, 0.02, 0.02] : [1, 0.85, 0.3], solid ? 0.9 : 1, ui, null, dtol);
1330
1708
  }
1331
1709
  // legend, then labels placed around it and around the view label / axis gizmo
1332
- const pl = new LabelPlacer(T, T);
1710
+ const pl = new LabelPlacer(TW, TH);
1333
1711
  const vlRight = 6 * ui + textWidth(viewLabel, 2 * ui) + 4 * ui;
1334
1712
  pl.reserve(0, 0, vlRight, 22 * ui);
1335
1713
  if (kind === 'persp')
1336
- pl.reserve(0, T - 64 * ui, 64 * ui, T);
1714
+ pl.reserve(0, TH - 64 * ui, 64 * ui, TH);
1337
1715
  if (vi === legendView && legendItems.length)
1338
- drawLegend(tb, T, T, legendItems, T >= 700 * ui ? 2 * ui : ui, pl, 6 * ui, [vlRight, 22 * ui]);
1716
+ drawLegend(tb, TW, TH, legendItems, Math.min(TW, TH) >= 700 * ui ? 2 * ui : ui, pl, 6 * ui, [vlRight, 22 * ui]);
1339
1717
  if (kind !== 'section') {
1340
1718
  const m4 = [0, 0, 0, 0];
1341
1719
  const clipped = (x, y, z) => clipOn && ((cK === 0 ? x : cK === 1 ? y : z) - cC) * cS > 0;
@@ -1376,22 +1754,23 @@ export function renderGeometry(g, o = {}) {
1376
1754
  if (lb.kind === 1 && hidden(m4[2], ax, ay))
1377
1755
  continue;
1378
1756
  }
1379
- if (ax < 0 || ay < 0 || ax >= T || ay >= T)
1757
+ if (ax < 0 || ay < 0 || ax >= TW || ay >= TH)
1380
1758
  continue;
1381
- drawLabel(tb, T, T, pl, ax, ay, lb.text, lb.c, lb.kind === 0 ? nameFs : ui);
1759
+ drawLabel(tb, TW, TH, pl, ax, ay, lb.text, lb.c, lb.kind === 0 ? nameFs : ui);
1382
1760
  }
1383
1761
  if (vi === legendView)
1384
1762
  labelsSkipped = pl.skipped;
1385
1763
  }
1386
- for (let y = 0; y < T; y++)
1387
- out.set(tb.subarray(y * T * 3, (y + 1) * T * 3), ((ty + y) * outW + tx) * 3);
1764
+ for (let y = 0; y < TH; y++)
1765
+ out.set(tb.subarray(y * TW * 3, (y + 1) * TW * 3), ((ty + y) * outW + tx) * 3);
1388
1766
  };
1389
- blit(viewLabel, post);
1767
+ blit(viewLabel, post, zb);
1390
1768
  });
1391
1769
  // footer
1392
1770
  const fy = outH - footerH + 4 * ui;
1393
1771
  const ext = [bmax[0] - bmin[0], bmax[1] - bmin[1], bmax[2] - bmin[2]];
1394
- const stats = `${np} PTS ${g.numPrims} PRIMS BBOX ${fmtNum(ext[0])}×${fmtNum(ext[1])}×${fmtNum(ext[2])} CENTER ${fmtNum((bmin[0] + bmax[0]) / 2)},${fmtNum((bmin[1] + bmax[1]) / 2)},${fmtNum((bmin[2] + bmax[2]) / 2)}`;
1772
+ // EDGES AUTO early on the line, so a long title cannot push it off the image
1773
+ const stats = `${np} PTS ${g.numPrims} PRIMS${autoEdgesShown ? ' EDGES AUTO' : ''} BBOX ${fmtNum(ext[0])}×${fmtNum(ext[1])}×${fmtNum(ext[2])} CENTER ${fmtNum((bmin[0] + bmax[0]) / 2)},${fmtNum((bmin[1] + bmax[1]) / 2)},${fmtNum((bmin[2] + bmax[2]) / 2)}`;
1395
1774
  drawText(out, outW, outH, 6 * ui, fy, (o.title ? o.title.toUpperCase() + ' ' : '') + stats, [0.85, 0.85, 0.85], 2 * ui, false);
1396
1775
  if (legend) {
1397
1776
  const lx = outW - textWidth(legend, 2 * ui) - 8 * ui;
@@ -1401,27 +1780,41 @@ export function renderGeometry(g, o = {}) {
1401
1780
  }
1402
1781
  if (labelsSkipped)
1403
1782
  notes.push(`labels: ${labelsSkipped} not drawn to avoid overlaps (raise size, zoom in, or lower max_labels)`);
1404
- if (annotate) {
1405
- // second line: active overlays, then up to three geometry notes
1783
+ if (annotate || hfFooter) {
1784
+ // second line: a decimated heightfield, then the active overlays and up to three geometry notes
1406
1785
  const gn = [];
1407
- if (np) {
1408
- const pieces = conn ? conn.count : connectivity(g).count;
1409
- gn.push(`${pieces} PIECE${pieces === 1 ? '' : 'S'}`);
1410
- }
1411
- if (closedPrims)
1412
- gn.push(openEdges ? `${openEdges} OPEN EDGES` : nonManifoldEdges ? `${nonManifoldEdges} NON-MANIFOLD EDGES` : 'NO OPEN EDGES');
1413
- const capAll = capCells + capFlipCells;
1414
- const bp = shadedPix ? (backPix / shadedPix) * 100 : 0;
1415
- if (capFlipCells && capAll) {
1416
- const pct = (capFlipCells / capAll) * 100;
1417
- gn.push(`CUT ${pct.toFixed(1)}% INSIDE-OUT`);
1418
- notes.push(`section: ${pct.toFixed(1)}% of the cut area is inside-out (blue): flipped normals`);
1786
+ if (annotate) {
1787
+ if (np) {
1788
+ const pieces = solid ? solid.pieces : connectivity(g).count;
1789
+ gn.push(`${pieces} PIECE${pieces === 1 ? '' : 'S'}`);
1790
+ }
1791
+ if (closedPrims && solid) {
1792
+ // open edges after welding seam splits (an imported mesh's uv / normal seams are not holes), with where
1793
+ const welded = solid.seamEdges ? ' (SEAM SPLITS WELDED)' : '';
1794
+ gn.push(solid.openEdges ? `${solid.openEdges} OPEN EDGES${welded}` : solid.nonManifoldEdges ? `${solid.nonManifoldEdges} NON-MANIFOLD EDGES` : `NO OPEN EDGES${welded}`);
1795
+ if (solid.openEdges)
1796
+ notes.push(`${openEdgesText(solid)}, first ${solid.firstOpen}`);
1797
+ if (solid.nonManifoldEdges)
1798
+ notes.push(`${solid.nonManifoldEdges} non-manifold edge(s), first ${solid.firstNonManifold}`);
1799
+ }
1800
+ const capAll = capCells + capFlipCells;
1801
+ const bp = shadedPix ? (backPix / shadedPix) * 100 : 0;
1802
+ if (capFlipCells && capAll) {
1803
+ const pct = (capFlipCells / capAll) * 100;
1804
+ gn.push(`CUT ${pct.toFixed(1)}% INSIDE-OUT`);
1805
+ notes.push(`section: ${pct.toFixed(1)}% of the cut area is inside-out (blue): flipped normals`);
1806
+ }
1807
+ else if (bp >= 0.05)
1808
+ gn.push(`BACK-FACING ${bp.toFixed(1)}% OF PIXELS`);
1809
+ if (bp >= 0.05) {
1810
+ // which parts, and where the most visible one is
1811
+ const top = [...backPrims].sort((x, y) => y[1] - x[1] || x[0] - y[0]);
1812
+ const parts = partsOf(g, top.map(([p]) => p));
1813
+ notes.push(`${bp.toFixed(1)}% of the shaded pixels in the ${views[backView]} view are back faces of closed pieces (blue): flipped normals? ${top.length ? `First ${primWhere(g, top[0][0])}${parts ? `; parts: ${parts} prims` : ''}; ` : ''}reverse those faces or clean fix_winding`);
1814
+ }
1419
1815
  }
1420
- else if (bp >= 0.05)
1421
- gn.push(`BACK-FACING ${bp.toFixed(1)}% OF PIXELS`);
1422
- if (bp >= 0.05)
1423
- notes.push(`${bp.toFixed(1)}% of the shaded pixels in the ${views[backView]} view are back faces of closed pieces (blue): flipped normals?`);
1424
- const line = [...ovDesc, ...gn.slice(0, 3)].join(' · ');
1816
+ const overlays = [...ovDesc, ...gn.slice(0, 3)].join(' · ');
1817
+ const line = [hfFooter ? hfLine : '', annotate ? overlays : ''].filter(Boolean).join(' · ');
1425
1818
  const maxW = outW - 12 * ui;
1426
1819
  let fs2 = 2 * ui, txt = line;
1427
1820
  if (textWidth(txt, fs2) > maxW)
@@ -1429,14 +1822,17 @@ export function renderGeometry(g, o = {}) {
1429
1822
  while (txt.length > 4 && textWidth(txt, fs2) > maxW)
1430
1823
  txt = txt.slice(0, -4) + '..';
1431
1824
  drawText(out, outW, outH, 6 * ui, fy + 18 * ui + (fs2 < 2 * ui ? 3 * ui : 0), txt, [0.62, 0.84, 1], fs2, false);
1432
- notes.push('overlays: ' + line.toLowerCase());
1825
+ if (annotate)
1826
+ notes.push('overlays: ' + overlays.toLowerCase());
1433
1827
  }
1434
1828
  const rgba = new Uint8Array(outW * outH * 4);
1829
+ if (outA)
1830
+ outA.fill(1, (outH - footerH) * outW); // the footer stays opaque
1435
1831
  for (let i = 0, j = 0; i < out.length; i += 3, j += 4) {
1436
1832
  rgba[j] = toSRGB(out[i]);
1437
1833
  rgba[j + 1] = toSRGB(out[i + 1]);
1438
1834
  rgba[j + 2] = toSRGB(out[i + 2]);
1439
- rgba[j + 3] = 255;
1835
+ rgba[j + 3] = outA ? toSRGB(outA[j >> 2]) : 255;
1440
1836
  }
1441
1837
  if (legend)
1442
1838
  notes.push(legend.toLowerCase());
@@ -1519,6 +1915,32 @@ function drawDisc(col, zb, W, H, x, y, z, r, c, tol) {
1519
1915
  col[i + 2] = c[2] * edge;
1520
1916
  }
1521
1917
  }
1918
+ /** Blend an image into col over the rectangle (x, y, w, h) in pixels, bilinear, by opacity × the image's alpha. */
1919
+ function drawUnderlay(col, W, H, img, x, y, w, h, opacity) {
1920
+ const xa = Math.max(0, Math.floor(x)), xb = Math.min(W, Math.ceil(x + w)), ya = Math.max(0, Math.floor(y)), yb = Math.min(H, Math.ceil(y + h));
1921
+ const d = img.rgba, iw = img.width, ih = img.height;
1922
+ for (let py = ya; py < yb; py++) {
1923
+ const v = ((py + 0.5 - y) / h) * ih - 0.5;
1924
+ if (v < -0.5 || v > ih - 0.5)
1925
+ continue;
1926
+ const j0 = Math.max(0, Math.min(ih - 1, Math.floor(v))), j1 = Math.min(ih - 1, j0 + 1), fv = Math.max(0, Math.min(1, v - j0));
1927
+ for (let px = xa; px < xb; px++) {
1928
+ const u = ((px + 0.5 - x) / w) * iw - 0.5;
1929
+ if (u < -0.5 || u > iw - 0.5)
1930
+ continue;
1931
+ const i0 = Math.max(0, Math.min(iw - 1, Math.floor(u))), i1 = Math.min(iw - 1, i0 + 1), fu = Math.max(0, Math.min(1, u - i0));
1932
+ const at = (i, j, c) => d[(j * iw + i) * 4 + c];
1933
+ const s = (c) => (at(i0, j0, c) * (1 - fu) + at(i1, j0, c) * fu) * (1 - fv) + (at(i0, j1, c) * (1 - fu) + at(i1, j1, c) * fu) * fv;
1934
+ const a = (s(3) / 255) * opacity;
1935
+ if (!(a > 0))
1936
+ continue;
1937
+ const k = (py * W + px) * 3;
1938
+ col[k] += (s(0) / 255 - col[k]) * a;
1939
+ col[k + 1] += (s(1) / 255 - col[k + 1]) * a;
1940
+ col[k + 2] += (s(2) / 255 - col[k + 2]) * a;
1941
+ }
1942
+ }
1943
+ }
1522
1944
  /** Procedural 8×8 uv checker; light cells are tinted by the position inside the tile (red = u, green = v). */
1523
1945
  function checkerColor(u, v, out) {
1524
1946
  if (!Number.isFinite(u) || !Number.isFinite(v)) {
@@ -1622,9 +2044,23 @@ function drawUVView(g, col, W, H, ss, uv, tris, colorOf, useColorOf, notes) {
1622
2044
  const chartOf = !useColorOf && chartA && chartA.type === 'int' && chartA.size === 1 ? chartA.data : null;
1623
2045
  const owner = new Int32Array(W * H).fill(-1);
1624
2046
  const cnt = new Uint8Array(W * H);
2047
+ // overlap kinds (core/uvreport.ts): between atlas charts (red), or expected: a tiling chart (one that runs across
2048
+ // tile borders) or prims of different LODs (amber)
2049
+ const nt = tris.length / 3, U = new Float64Array(nt * 6);
2050
+ for (let c = 0; c < nt * 3; c++) {
2051
+ U[c * 2] = uv[tris[c] * 2];
2052
+ U[c * 2 + 1] = uv[tris[c] * 2 + 1];
2053
+ }
2054
+ const kinds = chartKinds(U, nt, chartRoots(g.vertexPoint, tris, U, nt)), lods = primLods(g);
2055
+ const first = new Int32Array(W * H).fill(-1), firstKind = new Uint8Array(W * H), flag = new Uint8Array(W * H);
2056
+ let tilingTris = 0;
2057
+ for (let t = 0; t < nt; t++)
2058
+ if (kinds[t] === 2)
2059
+ tilingTris++;
2060
+ const pairFlag = (pa, ka, pb, kb) => (ka === 2 || kb === 2 || (lods && lods[pa] >= 0 && lods[pb] >= 0 && lods[pa] !== lods[pb]) ? 2 : 1);
1625
2061
  for (let t = 0; t < tris.length; t += 3) {
1626
2062
  const va = tris[t], vb = tris[t + 1], vc = tris[t + 2];
1627
- const prim = vprim[va];
2063
+ const prim = vprim[va], kind = kinds[t / 3];
1628
2064
  const ax = X(uv[va * 2]), ay = Y(uv[va * 2 + 1]), bx = X(uv[vb * 2]), by = Y(uv[vb * 2 + 1]), cx = X(uv[vc * 2]), cy = Y(uv[vc * 2 + 1]);
1629
2065
  if (![ax, ay, bx, by, cx, cy].every(Number.isFinite))
1630
2066
  continue;
@@ -1652,6 +2088,12 @@ function drawUVView(g, col, W, H, ss, uv, tris, colorOf, useColorOf, notes) {
1652
2088
  const zi = py * W + px;
1653
2089
  if (owner[zi] === prim)
1654
2090
  continue;
2091
+ if (first[zi] < 0) {
2092
+ first[zi] = prim;
2093
+ firstKind[zi] = kind;
2094
+ }
2095
+ else if (first[zi] !== prim)
2096
+ flag[zi] |= pairFlag(first[zi], firstKind[zi], prim, kind);
1655
2097
  owner[zi] = prim;
1656
2098
  if (cnt[zi] < 255)
1657
2099
  cnt[zi]++;
@@ -1662,17 +2104,26 @@ function drawUVView(g, col, W, H, ss, uv, tris, colorOf, useColorOf, notes) {
1662
2104
  }
1663
2105
  }
1664
2106
  }
1665
- let covered = 0, overlap = 0;
2107
+ let covered = 0, overlap = 0, expected = 0;
1666
2108
  for (let i = 0; i < cnt.length; i++) {
1667
2109
  if (!cnt[i])
1668
2110
  continue;
1669
2111
  covered++;
1670
2112
  if (cnt[i] < 2)
1671
2113
  continue;
1672
- overlap++;
1673
- col[i * 3] += (1 - col[i * 3]) * 0.8;
1674
- col[i * 3 + 1] += (0.12 - col[i * 3 + 1]) * 0.8;
1675
- col[i * 3 + 2] += (0.12 - col[i * 3 + 2]) * 0.8;
2114
+ if (flag[i] & 1) {
2115
+ overlap++;
2116
+ col[i * 3] += (1 - col[i * 3]) * 0.8;
2117
+ col[i * 3 + 1] += (0.12 - col[i * 3 + 1]) * 0.8;
2118
+ col[i * 3 + 2] += (0.12 - col[i * 3 + 2]) * 0.8;
2119
+ }
2120
+ else {
2121
+ // expected overlap (tiling, LODs): a light amber wash, not the red of a real overlap
2122
+ expected++;
2123
+ col[i * 3] += (0.95 - col[i * 3]) * 0.35;
2124
+ col[i * 3 + 1] += (0.7 - col[i * 3 + 1]) * 0.35;
2125
+ col[i * 3 + 2] += (0.25 - col[i * 3 + 2]) * 0.35;
2126
+ }
1676
2127
  }
1677
2128
  // polygon edges, then island borders (uv seams and open borders) on top
1678
2129
  if (g.numPrims <= 60000) {
@@ -1700,8 +2151,12 @@ function drawUVView(g, col, W, H, ss, uv, tris, colorOf, useColorOf, notes) {
1700
2151
  edge(S.bv[i], S.bw[i]);
1701
2152
  tileLabels();
1702
2153
  const tiles = span === 1 && u0 === 0 && v0 === 0 ? '0..1' : `${span}×${span} TILES FROM ${u0},${v0}`;
1703
- const ov = covered ? (overlap / covered) * 100 : 0;
2154
+ const ov = covered ? (overlap / covered) * 100 : 0, ex = covered ? (expected / covered) * 100 : 0;
1704
2155
  if (ov >= 0.05)
1705
- notes.push(`uv view: ${ov.toFixed(1)}% of the covered uv area overlaps (red)`);
1706
- return `UV ${tiles}${ov >= 0.05 ? ` OVERLAP ${ov.toFixed(1)}%` : ''}`;
2156
+ notes.push(`uv view: ${ov.toFixed(1)}% of the covered uv area overlaps (red; inspect detail "uv" names the parts and where)`);
2157
+ if (tilingTris)
2158
+ notes.push(`uv view: tiling uv: ${tilingTris} triangles lie in charts that run across tile borders (a repeating texture, not an atlas); their overlap is expected (amber)`);
2159
+ if (ex >= 0.05 && lods)
2160
+ notes.push('uv view: LODs share the uv space; their overlap is expected (amber)');
2161
+ return `UV ${tiles}${ov >= 0.05 ? ` OVERLAP ${ov.toFixed(1)}%` : ''}${tilingTris ? ' TILING' : ''}${ex >= 0.05 && !tilingTris ? ' LOD OVERLAP OK' : ''}`;
1707
2162
  }