morphogen 1.0.0__py3-none-any.whl

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 (381) hide show
  1. morphogen/__init__.py +60 -0
  2. morphogen/__main__.py +7 -0
  3. morphogen/_platform.py +55 -0
  4. morphogen/_public.py +153 -0
  5. morphogen/_utils.py +80 -0
  6. morphogen/_version.py +1 -0
  7. morphogen/analysis/__init__.py +174 -0
  8. morphogen/analysis/anisotropy.py +135 -0
  9. morphogen/analysis/basic.py +38 -0
  10. morphogen/analysis/cells.py +54 -0
  11. morphogen/analysis/connectivity.py +156 -0
  12. morphogen/analysis/correlation.py +195 -0
  13. morphogen/analysis/covariance.py +80 -0
  14. morphogen/analysis/fractal.py +54 -0
  15. morphogen/analysis/measures.py +188 -0
  16. morphogen/analysis/morphology.py +265 -0
  17. morphogen/analysis/particles.py +160 -0
  18. morphogen/analysis/percolation.py +2034 -0
  19. morphogen/analysis/power_laws.py +143 -0
  20. morphogen/analysis/random_sets.py +351 -0
  21. morphogen/analysis/stereology.py +289 -0
  22. morphogen/analysis/surface.py +107 -0
  23. morphogen/analysis/topology.py +92 -0
  24. morphogen/automata/__init__.py +74 -0
  25. morphogen/automata/engine.py +211 -0
  26. morphogen/automata/growth.py +686 -0
  27. morphogen/automata/lattice.py +143 -0
  28. morphogen/automata/reaction.py +255 -0
  29. morphogen/automata/rules.py +353 -0
  30. morphogen/automata/tilings.py +1715 -0
  31. morphogen/cli.py +3526 -0
  32. morphogen/config.py +2167 -0
  33. morphogen/contact/__init__.py +113 -0
  34. morphogen/contact/experiments.py +368 -0
  35. morphogen/contact/hertz.py +104 -0
  36. morphogen/contact/kernels.py +827 -0
  37. morphogen/contact/periodic.py +278 -0
  38. morphogen/contact/problem.py +578 -0
  39. morphogen/contact/surfaces.py +310 -0
  40. morphogen/coupling/__init__.py +43 -0
  41. morphogen/coupling/ageing.py +143 -0
  42. morphogen/coupling/diffusion.py +226 -0
  43. morphogen/coupling/fenicsx.py +484 -0
  44. morphogen/coupling/oxidation.py +447 -0
  45. morphogen/coupling/plates.py +247 -0
  46. morphogen/design/__init__.py +51 -0
  47. morphogen/design/csp.py +616 -0
  48. morphogen/design/frames.py +277 -0
  49. morphogen/design/search.py +287 -0
  50. morphogen/design/tiles.py +336 -0
  51. morphogen/distributions.py +312 -0
  52. morphogen/domain.py +203 -0
  53. morphogen/dynamics/__init__.py +179 -0
  54. morphogen/dynamics/model.py +638 -0
  55. morphogen/dynamics/openradioss.py +643 -0
  56. morphogen/dynamics/results.py +515 -0
  57. morphogen/fracture/__init__.py +170 -0
  58. morphogen/fracture/bulk.py +349 -0
  59. morphogen/fracture/cohesive.py +1614 -0
  60. morphogen/fracture/ductile.py +557 -0
  61. morphogen/fracture/lefm.py +1168 -0
  62. morphogen/fracture/mixed.py +1178 -0
  63. morphogen/fracture/periodic.py +733 -0
  64. morphogen/fracture/phasefield.py +714 -0
  65. morphogen/fracture/phasefield_finite.py +368 -0
  66. morphogen/fracture/surface.py +572 -0
  67. morphogen/fracture/toughness.py +566 -0
  68. morphogen/gpu.py +108 -0
  69. morphogen/gui/__init__.py +8 -0
  70. morphogen/gui/api.py +1927 -0
  71. morphogen/gui/desktop.py +387 -0
  72. morphogen/gui/icon.png +0 -0
  73. morphogen/gui/index.html +1909 -0
  74. morphogen/gui/server.py +229 -0
  75. morphogen/gui/tools/__init__.py +629 -0
  76. morphogen/gui/tools/compare.py +149 -0
  77. morphogen/gui/tools/contact.py +391 -0
  78. morphogen/gui/tools/couplings.py +1085 -0
  79. morphogen/gui/tools/crackfront.py +245 -0
  80. morphogen/gui/tools/design.py +224 -0
  81. morphogen/gui/tools/dynamics.py +824 -0
  82. morphogen/gui/tools/fracture.py +2586 -0
  83. morphogen/gui/tools/interop.py +1654 -0
  84. morphogen/gui/tools/learning.py +595 -0
  85. morphogen/gui/tools/mechanics.py +3881 -0
  86. morphogen/gui/tools/nonlocal_damage.py +1321 -0
  87. morphogen/gui/tools/phasefield.py +215 -0
  88. morphogen/gui/tools/physics.py +597 -0
  89. morphogen/gui/tools/stability.py +1756 -0
  90. morphogen/gui/tools/statistics.py +1408 -0
  91. morphogen/gui/viewer.js +1100 -0
  92. morphogen/homogenization/__init__.py +210 -0
  93. morphogen/homogenization/acoustics.py +566 -0
  94. morphogen/homogenization/amg.py +1005 -0
  95. morphogen/homogenization/apparent.py +1046 -0
  96. morphogen/homogenization/behaviours.cu +2285 -0
  97. morphogen/homogenization/behaviours.py +944 -0
  98. morphogen/homogenization/beremin.py +263 -0
  99. morphogen/homogenization/bifurcation.py +1085 -0
  100. morphogen/homogenization/bloch.py +507 -0
  101. morphogen/homogenization/bounds.py +226 -0
  102. morphogen/homogenization/core.py +458 -0
  103. morphogen/homogenization/coupled.py +1135 -0
  104. morphogen/homogenization/crystal.py +2967 -0
  105. morphogen/homogenization/dilatation.py +454 -0
  106. morphogen/homogenization/elements.py +157 -0
  107. morphogen/homogenization/fatigue.py +768 -0
  108. morphogen/homogenization/fe.py +1739 -0
  109. morphogen/homogenization/fenicsx.py +307 -0
  110. morphogen/homogenization/fft.py +499 -0
  111. morphogen/homogenization/fft_nonlinear.py +391 -0
  112. morphogen/homogenization/finite.py +613 -0
  113. morphogen/homogenization/flow.py +361 -0
  114. morphogen/homogenization/frames.py +1125 -0
  115. morphogen/homogenization/gpu.py +1241 -0
  116. morphogen/homogenization/harmonic.py +427 -0
  117. morphogen/homogenization/identification.py +579 -0
  118. morphogen/homogenization/kernels.py +760 -0
  119. morphogen/homogenization/laws.py +2061 -0
  120. morphogen/homogenization/materials.py +1080 -0
  121. morphogen/homogenization/mfront.py +589 -0
  122. morphogen/homogenization/networks.py +880 -0
  123. morphogen/homogenization/nonlinear.py +2612 -0
  124. morphogen/homogenization/ntfa.py +577 -0
  125. morphogen/homogenization/paths.py +476 -0
  126. morphogen/homogenization/photonic.py +467 -0
  127. morphogen/homogenization/poroelastic.py +212 -0
  128. morphogen/homogenization/porous.py +1120 -0
  129. morphogen/homogenization/postprocess.py +290 -0
  130. morphogen/homogenization/solvers.py +1140 -0
  131. morphogen/homogenization/tensors.py +240 -0
  132. morphogen/homogenization/voxel_fe.py +457 -0
  133. morphogen/homogenization/xfem.py +1016 -0
  134. morphogen/homogenization/zmat.py +1258 -0
  135. morphogen/iga/__init__.py +48 -0
  136. morphogen/iga/analysis.py +508 -0
  137. morphogen/iga/basis.py +214 -0
  138. morphogen/iga/geometry.py +501 -0
  139. morphogen/iga/homogenization.py +219 -0
  140. morphogen/iga/optimization.py +700 -0
  141. morphogen/iga/shapes.py +331 -0
  142. morphogen/image.py +128 -0
  143. morphogen/io/__init__.py +246 -0
  144. morphogen/io/amitex.py +741 -0
  145. morphogen/io/ebsd.py +881 -0
  146. morphogen/io/export.py +196 -0
  147. morphogen/io/geometry.py +158 -0
  148. morphogen/io/medit.py +147 -0
  149. morphogen/io/meshes.py +844 -0
  150. morphogen/io/metaimage.py +97 -0
  151. morphogen/io/mfront.py +1104 -0
  152. morphogen/io/native.py +57 -0
  153. morphogen/io/radioss.py +764 -0
  154. morphogen/io/solvers.py +371 -0
  155. morphogen/io/tables.py +278 -0
  156. morphogen/io/tiff.py +66 -0
  157. morphogen/io/vtk.py +701 -0
  158. morphogen/io/xdmf.py +200 -0
  159. morphogen/kernels/__init__.py +5 -0
  160. morphogen/kernels/annealing.py +192 -0
  161. morphogen/kernels/cells.py +69 -0
  162. morphogen/kernels/collective.py +87 -0
  163. morphogen/kernels/force_biased.py +595 -0
  164. morphogen/kernels/implicit.py +145 -0
  165. morphogen/kernels/leaves.py +132 -0
  166. morphogen/kernels/packing.py +304 -0
  167. morphogen/kernels/raster.py +279 -0
  168. morphogen/kernels/rsa.py +371 -0
  169. morphogen/kernels/union.py +135 -0
  170. morphogen/kernels/watershed.py +190 -0
  171. morphogen/laser/__init__.py +234 -0
  172. morphogen/laser/architectures.py +375 -0
  173. morphogen/laser/bending.py +216 -0
  174. morphogen/laser/cells.py +1694 -0
  175. morphogen/laser/design.py +940 -0
  176. morphogen/laser/figures.py +227 -0
  177. morphogen/laser/heat.py +804 -0
  178. morphogen/laser/materials.py +691 -0
  179. morphogen/laser/mechanics.py +1670 -0
  180. morphogen/laser/metallurgy.py +615 -0
  181. morphogen/laser/patterns.py +828 -0
  182. morphogen/laser/periodic.py +392 -0
  183. morphogen/laser/process.py +362 -0
  184. morphogen/laser/run.py +534 -0
  185. morphogen/laser/solid.py +216 -0
  186. morphogen/laser/specimen.py +200 -0
  187. morphogen/laser/structures.py +708 -0
  188. morphogen/learning/__init__.py +81 -0
  189. morphogen/learning/behaviour.py +398 -0
  190. morphogen/learning/data.py +328 -0
  191. morphogen/learning/learned.cpp +668 -0
  192. morphogen/learning/logarithmic.py +202 -0
  193. morphogen/learning/mfront.py +409 -0
  194. morphogen/learning/networks.py +767 -0
  195. morphogen/learning/run.py +212 -0
  196. morphogen/learning/standard.py +814 -0
  197. morphogen/learning/training.py +235 -0
  198. morphogen/mesh/__init__.py +29 -0
  199. morphogen/mesh/conforming.py +1423 -0
  200. morphogen/mesh/curved.py +600 -0
  201. morphogen/mesh/exact.py +1717 -0
  202. morphogen/mesh/octree.py +350 -0
  203. morphogen/mesh/polycrystal.py +1041 -0
  204. morphogen/mesh/polyhedra.py +677 -0
  205. morphogen/mesh/regularize.py +570 -0
  206. morphogen/mesh/surface.py +97 -0
  207. morphogen/mesh/tetra.py +512 -0
  208. morphogen/mesh/voxel.py +124 -0
  209. morphogen/micromorphic/__init__.py +31 -0
  210. morphogen/micromorphic/damage.py +359 -0
  211. morphogen/micromorphic/ductile.py +534 -0
  212. morphogen/micromorphic/finite.py +220 -0
  213. morphogen/micromorphic/microfoam.py +787 -0
  214. morphogen/micromorphic/space.py +341 -0
  215. morphogen/models/__init__.py +195 -0
  216. morphogen/models/affine.py +384 -0
  217. morphogen/models/automata.py +592 -0
  218. morphogen/models/base.py +500 -0
  219. morphogen/models/boolean.py +310 -0
  220. morphogen/models/bouligand.py +331 -0
  221. morphogen/models/branching.py +241 -0
  222. morphogen/models/combination.py +430 -0
  223. morphogen/models/deadleaves.py +766 -0
  224. morphogen/models/design.py +289 -0
  225. morphogen/models/ebsd.py +206 -0
  226. morphogen/models/fibers.py +1476 -0
  227. morphogen/models/foam.py +594 -0
  228. morphogen/models/gaussian.py +314 -0
  229. morphogen/models/growth.py +459 -0
  230. morphogen/models/hardcore.py +317 -0
  231. morphogen/models/hierarchical.py +269 -0
  232. morphogen/models/honeycomb.py +749 -0
  233. morphogen/models/implicit.py +177 -0
  234. morphogen/models/laminate.py +470 -0
  235. morphogen/models/lattice.py +351 -0
  236. morphogen/models/lattice_field.py +345 -0
  237. morphogen/models/levelset_foam.py +563 -0
  238. morphogen/models/nacre.py +411 -0
  239. morphogen/models/nested.py +924 -0
  240. morphogen/models/osteons.py +374 -0
  241. morphogen/models/pieces.py +167 -0
  242. morphogen/models/planar.py +126 -0
  243. morphogen/models/reconstruction.py +203 -0
  244. morphogen/models/scale_rich.py +1409 -0
  245. morphogen/models/scale_rich_3d.py +1616 -0
  246. morphogen/models/tessellation.py +735 -0
  247. morphogen/models/tiling_field.py +302 -0
  248. morphogen/models/tpms.py +197 -0
  249. morphogen/models/transparent.py +406 -0
  250. morphogen/models/union.py +141 -0
  251. morphogen/optimization/__init__.py +43 -0
  252. morphogen/optimization/cell.py +295 -0
  253. morphogen/optimization/filters.py +115 -0
  254. morphogen/optimization/mma.py +226 -0
  255. morphogen/optimization/run.py +219 -0
  256. morphogen/optimization/topology.py +632 -0
  257. morphogen/orientations.py +568 -0
  258. morphogen/parallel.py +599 -0
  259. morphogen/pipeline.py +978 -0
  260. morphogen/primitives.py +188 -0
  261. morphogen/results.py +564 -0
  262. morphogen/rve/__init__.py +73 -0
  263. morphogen/rve/report.py +627 -0
  264. morphogen/rve/scaling.py +363 -0
  265. morphogen/rve/study.py +1054 -0
  266. morphogen/rve/windows.py +345 -0
  267. morphogen/seeding.py +51 -0
  268. morphogen/settings.py +118 -0
  269. morphogen/stopping.py +48 -0
  270. morphogen/symmetry.py +384 -0
  271. morphogen/templates/activator_inhibitor.yaml +22 -0
  272. morphogen/templates/aggregation.yaml +23 -0
  273. morphogen/templates/boolean_cylinders.yaml +20 -0
  274. morphogen/templates/boolean_spheres.yaml +22 -0
  275. morphogen/templates/bouligand.yaml +28 -0
  276. morphogen/templates/cellular_automaton.yaml +25 -0
  277. morphogen/templates/coated_spheres.yaml +26 -0
  278. morphogen/templates/contact_fibers.yaml +27 -0
  279. morphogen/templates/cox_nanocomposite.yaml +22 -0
  280. morphogen/templates/cross_linked_fibers.yaml +26 -0
  281. morphogen/templates/curved_arcs.yaml +28 -0
  282. morphogen/templates/curved_fibers.yaml +24 -0
  283. morphogen/templates/dead_leaves.yaml +22 -0
  284. morphogen/templates/delaunay_network.yaml +22 -0
  285. morphogen/templates/dense_packing.yaml +22 -0
  286. morphogen/templates/diffusion.yaml +33 -0
  287. morphogen/templates/ebsd.yaml +34 -0
  288. morphogen/templates/ebsd_map.ctf +3087 -0
  289. morphogen/templates/fracture_composite.yaml +42 -0
  290. morphogen/templates/fracture_rubber.yaml +47 -0
  291. morphogen/templates/gaussian_excursion.yaml +17 -0
  292. morphogen/templates/graded_lattice.yaml +24 -0
  293. morphogen/templates/hardcore_fibers.yaml +22 -0
  294. morphogen/templates/hardcore_spheres.yaml +22 -0
  295. morphogen/templates/hierarchical_lattice.yaml +22 -0
  296. morphogen/templates/homogenization_acoustic_foam.yaml +36 -0
  297. morphogen/templates/homogenization_beremin.yaml +50 -0
  298. morphogen/templates/homogenization_cleavage.yaml +51 -0
  299. morphogen/templates/homogenization_cleavage_band.yaml +55 -0
  300. morphogen/templates/homogenization_contact.yaml +43 -0
  301. morphogen/templates/homogenization_crack_closure.yaml +49 -0
  302. morphogen/templates/homogenization_crystal_plasticity.yaml +50 -0
  303. morphogen/templates/homogenization_crystal_plasticity_fft.yaml +52 -0
  304. morphogen/templates/homogenization_crystallization.yaml +30 -0
  305. morphogen/templates/homogenization_debonding.yaml +43 -0
  306. morphogen/templates/homogenization_detwinning.yaml +58 -0
  307. morphogen/templates/homogenization_ductile_damage.yaml +47 -0
  308. morphogen/templates/homogenization_fatigue.yaml +40 -0
  309. morphogen/templates/homogenization_grain_fracture.yaml +56 -0
  310. morphogen/templates/homogenization_gyroid.yaml +30 -0
  311. morphogen/templates/homogenization_intergranular.yaml +43 -0
  312. morphogen/templates/homogenization_interphase.yaml +42 -0
  313. morphogen/templates/homogenization_mixed_loading.yaml +33 -0
  314. morphogen/templates/homogenization_ntfa.yaml +56 -0
  315. morphogen/templates/homogenization_piezoelectric.yaml +27 -0
  316. morphogen/templates/homogenization_polycrystal.yaml +30 -0
  317. morphogen/templates/homogenization_polycrystal_inclusions.yaml +30 -0
  318. morphogen/templates/homogenization_poroelastic.yaml +26 -0
  319. morphogen/templates/homogenization_rubber.yaml +40 -0
  320. morphogen/templates/homogenization_slip_cleavage.yaml +50 -0
  321. morphogen/templates/homogenization_spheres.yaml +31 -0
  322. morphogen/templates/homogenization_transport.yaml +29 -0
  323. morphogen/templates/homogenization_twinning.yaml +54 -0
  324. morphogen/templates/homogenization_viscoelastic.yaml +34 -0
  325. morphogen/templates/homogenization_viscoplastic.yaml +42 -0
  326. morphogen/templates/homogenization_voronoi.yaml +26 -0
  327. morphogen/templates/homogenization_xfem.yaml +23 -0
  328. morphogen/templates/hyperuniform_cells.yaml +24 -0
  329. morphogen/templates/laguerre.yaml +18 -0
  330. morphogen/templates/laser_bending.yaml +35 -0
  331. morphogen/templates/laser_cells.yaml +38 -0
  332. morphogen/templates/laser_corrugated.yaml +36 -0
  333. morphogen/templates/level_set_foam.yaml +29 -0
  334. morphogen/templates/menger_sponge.yaml +17 -0
  335. morphogen/templates/nacre.yaml +25 -0
  336. morphogen/templates/nucleation_growth.yaml +25 -0
  337. morphogen/templates/optimize_auxetic.yaml +29 -0
  338. morphogen/templates/optimize_auxetic_3d.yaml +27 -0
  339. morphogen/templates/optimize_bulk.yaml +23 -0
  340. morphogen/templates/optimize_conductivity.yaml +20 -0
  341. morphogen/templates/osteons.yaml +28 -0
  342. morphogen/templates/penetrable_spheres.yaml +21 -0
  343. morphogen/templates/poisson_fibers.yaml +21 -0
  344. morphogen/templates/random_laminate.yaml +26 -0
  345. morphogen/templates/random_lattice.yaml +27 -0
  346. morphogen/templates/random_walk_fibers.yaml +26 -0
  347. morphogen/templates/reaction_diffusion.yaml +22 -0
  348. morphogen/templates/reconstruction.yaml +22 -0
  349. morphogen/templates/rve_cellular_automaton.yaml +23 -0
  350. morphogen/templates/rve_crystal_plasticity_fft.yaml +51 -0
  351. morphogen/templates/rve_multiphysics.yaml +43 -0
  352. morphogen/templates/rve_poisson_fibers.yaml +22 -0
  353. morphogen/templates/rve_poisson_fibers_fe.yaml +33 -0
  354. morphogen/templates/rve_voronoi_windows.yaml +20 -0
  355. morphogen/templates/scale_rich_network.yaml +29 -0
  356. morphogen/templates/scale_rich_plates.yaml +30 -0
  357. morphogen/templates/sequential_dead_leaves.yaml +25 -0
  358. morphogen/templates/strut_lattice.yaml +21 -0
  359. morphogen/templates/tile_assembly.yaml +28 -0
  360. morphogen/templates/tpms.yaml +19 -0
  361. morphogen/templates/trabecular_bone.yaml +29 -0
  362. morphogen/templates/transparent_dead_leaves.yaml +23 -0
  363. morphogen/templates/vascular_tree.yaml +23 -0
  364. morphogen/templates/voronoi.yaml +20 -0
  365. morphogen/templates/wood.yaml +34 -0
  366. morphogen/templates/workflow.yaml +56 -0
  367. morphogen/texture.py +665 -0
  368. morphogen/theory.py +162 -0
  369. morphogen/viz/__init__.py +12 -0
  370. morphogen/viz/export.py +244 -0
  371. morphogen/viz/figures.py +707 -0
  372. morphogen/viz/png.py +148 -0
  373. morphogen/viz/sections.py +696 -0
  374. morphogen/viz/surfaces.py +1352 -0
  375. morphogen/viz/video.py +904 -0
  376. morphogen/viz/workflow.py +488 -0
  377. morphogen-1.0.0.dist-info/METADATA +2316 -0
  378. morphogen-1.0.0.dist-info/RECORD +381 -0
  379. morphogen-1.0.0.dist-info/WHEEL +4 -0
  380. morphogen-1.0.0.dist-info/entry_points.txt +5 -0
  381. morphogen-1.0.0.dist-info/licenses/LICENSE +674 -0
@@ -0,0 +1,1100 @@
1
+ /* morphoGen: the 3D view of the items of the workspace, drawn with WebGL 2 (no library,
2
+ * no network: the page works offline).
3
+ *
4
+ * MorphoViewer.slot(key, options) is the HTML of a place for the view of an item; the
5
+ * view opens there (as soon as it shows with options.auto, else by its button) and draws
6
+ * the surface of /api/surface (morphogen/viz/surfaces.py): triangles in groups between
7
+ * two regions (phases, or cells with their phases), the inside one behind them (their
8
+ * normals point out of it), the outside one in front (-1: beyond the box). A fragment
9
+ * shows the region that a ray entering through it meets: the inside from the front, the
10
+ * outside from the back, the inside again behind the faces of the box (its shell seen
11
+ * from within, through a section); hidden regions let the rays through. The volumes of
12
+ * the surface (level set, regions, field of the voxels) colour the faces of the box and
13
+ * the section plane, as the sections of the page.
14
+ *
15
+ * Mouse: drag to turn, shift-drag or right-drag to move, wheel to zoom; touch: one finger
16
+ * turns, two zoom and move. Lighting: two-sided Lambert with some ambient light, from the
17
+ * eye. The view is drawn on demand, in one call for all its triangles.
18
+ *
19
+ * The pure functions (matrices, section planes, colour maps, decoding) are exported for
20
+ * Node, which tests them (tests/test_surfaces.py).
21
+ */
22
+ (function () {
23
+ "use strict";
24
+
25
+ // -- vectors and matrices (column-major Float32Array(16), as WebGL takes them) ----------
26
+ const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
27
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
28
+ const cross = (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]];
29
+ function normalize(a) {
30
+ const n = Math.hypot(a[0], a[1], a[2]) || 1;
31
+ return [a[0] / n, a[1] / n, a[2] / n];
32
+ }
33
+ function identity() {
34
+ const m = new Float32Array(16);
35
+ m[0] = m[5] = m[10] = m[15] = 1;
36
+ return m;
37
+ }
38
+ function multiply(a, b) { // the product a b
39
+ const out = new Float32Array(16);
40
+ for (let c = 0; c < 4; c++) {
41
+ for (let r = 0; r < 4; r++) {
42
+ let s = 0;
43
+ for (let k = 0; k < 4; k++) s += a[k * 4 + r] * b[c * 4 + k];
44
+ out[c * 4 + r] = s;
45
+ }
46
+ }
47
+ return out;
48
+ }
49
+ function perspective(fovy, aspect, near, far) { // as gluPerspective
50
+ const f = 1 / Math.tan(fovy / 2), nf = 1 / (near - far);
51
+ const m = new Float32Array(16);
52
+ m[0] = f / aspect;
53
+ m[5] = f;
54
+ m[10] = (far + near) * nf;
55
+ m[11] = -1;
56
+ m[14] = 2 * far * near * nf;
57
+ return m;
58
+ }
59
+ function lookAt(eye, target, up) { // the view from eye to target, up upwards
60
+ const z = normalize(sub(eye, target)), x = normalize(cross(up, z)), y = cross(z, x);
61
+ const m = identity();
62
+ m[0] = x[0]; m[4] = x[1]; m[8] = x[2];
63
+ m[1] = y[0]; m[5] = y[1]; m[9] = y[2];
64
+ m[2] = z[0]; m[6] = z[1]; m[10] = z[2];
65
+ m[12] = -dot(x, eye); m[13] = -dot(y, eye); m[14] = -dot(z, eye);
66
+ return m;
67
+ }
68
+ function transform(m, p) { // m [p, 1]: homogeneous coordinates
69
+ const out = [0, 0, 0, 0];
70
+ for (let r = 0; r < 4; r++) out[r] = m[r] * p[0] + m[4 + r] * p[1] + m[8 + r] * p[2] + m[12 + r];
71
+ return out;
72
+ }
73
+ function project(m, p, width, height) { // pixels (from the top left) and depth; null behind
74
+ const q = transform(m, p);
75
+ if (q[3] <= 0) return null;
76
+ return [(q[0] / q[3] + 1) * width / 2, (1 - q[1] / q[3]) * height / 2, q[2] / q[3]];
77
+ }
78
+ function orbitEye(target, distance, yaw, pitch) { // z up; yaw from +x towards +y
79
+ const c = Math.cos(pitch);
80
+ return [target[0] + distance * c * Math.cos(yaw), target[1] + distance * c * Math.sin(yaw),
81
+ target[2] + distance * Math.sin(pitch)];
82
+ }
83
+ function fit(lower, upper, fovy, aspect) { // the target and distance that frame a box
84
+ const target = [0, 1, 2].map((a) => (lower[a] + upper[a]) / 2);
85
+ const radius = Math.hypot(upper[0] - lower[0], upper[1] - lower[1], upper[2] - lower[2]) / 2 || 1;
86
+ // the narrower of the two angles of view: that across a view taller than wide
87
+ const half = Math.min(fovy / 2, Math.atan((aspect || 1) * Math.tan(fovy / 2)));
88
+ return {target, radius, distance: 1.08 * radius / Math.sin(half)};
89
+ }
90
+
91
+ // -- the section plane --------------------------------------------------------------------
92
+ const AXES = {x: 0, y: 1, z: 2};
93
+ function axisOf(axis) {
94
+ if (typeof axis === "number") return axis >= 0 && axis <= 2 ? axis : -1;
95
+ return axis in AXES ? AXES[axis] : -1;
96
+ }
97
+ // [a, b, c, d]: the points kept by a section normal to axis (x, y, z or 0-2) at fraction
98
+ // of the box, a x + b y + c z + d >= 0: beyond the plane, or before it when flipped;
99
+ // [0, 0, 0, 1] keeps everything (no section)
100
+ function clipPlane(axis, fraction, lower, upper, flip) {
101
+ const a = axisOf(axis);
102
+ if (a < 0) return [0, 0, 0, 1];
103
+ const at = lower[a] + Math.min(Math.max(fraction, 0), 1) * (upper[a] - lower[a]);
104
+ const s = flip ? -1 : 1, plane = [0, 0, 0, 0];
105
+ plane[a] = s;
106
+ plane[3] = -s * at;
107
+ return plane;
108
+ }
109
+ function sectionQuad(axis, fraction, lower, upper) { // the corners of the cut of the box
110
+ const a = axisOf(axis);
111
+ if (a < 0) return null;
112
+ const u = (a + 1) % 3, v = (a + 2) % 3;
113
+ const at = lower[a] + Math.min(Math.max(fraction, 0), 1) * (upper[a] - lower[a]);
114
+ return [[lower[u], lower[v]], [upper[u], lower[v]], [upper[u], upper[v]], [lower[u], upper[v]]].map(([pu, pv]) => {
115
+ const p = [0, 0, 0];
116
+ p[a] = at; p[u] = pu; p[v] = pv;
117
+ return p;
118
+ });
119
+ }
120
+ function boxFaces(lower, upper) { // the six faces of a box: corners counter-clockwise from outside
121
+ const out = [];
122
+ for (let a = 0; a < 3; a++) {
123
+ for (const side of [0, 1]) {
124
+ const u = (a + 1) % 3, v = (a + 2) % 3, at = side ? upper[a] : lower[a];
125
+ let corners = [[lower[u], lower[v]], [upper[u], lower[v]], [upper[u], upper[v]], [lower[u], upper[v]]];
126
+ if (!side) corners = corners.reverse();
127
+ const normal = [0, 0, 0];
128
+ normal[a] = side ? 1 : -1;
129
+ out.push({normal, corners: corners.map(([pu, pv]) => {
130
+ const p = [0, 0, 0];
131
+ p[a] = at; p[u] = pu; p[v] = pv;
132
+ return p;
133
+ })});
134
+ }
135
+ }
136
+ return out;
137
+ }
138
+
139
+ // -- colour maps (those of the server, from matplotlib, at 33 stops) -----------------------
140
+ const COLORMAPS = {
141
+ viridis: "440154470d6048186a482374472d7b4537814240863e49893b528b375b8d33638d2f6b8e2c728e297a8e26828e23898e21918c1f988b1fa08822a78528ae8032b67a3fbc734ec36b5ec96270cf5784d44b98d83eaddc30c2df23d8e219ece51bfde725",
142
+ plasma: "0d08872206903105973f049c4c02a15901a56600a77201a87e03a88a09a59511a1a01a9caa2395b32c8ebc3587c43e7fcc4778d35171da5a6ae06363e66c5ceb7655f0804ef58b47f89540fba139fdac33feb82cfdc527fcd225f8df25f4ed27f0f921",
143
+ inferno: "0000040403120b0724150b37210c4a2f0a5b3d09654a0c6b57106e64156e71196e7d1e6d8a226a972766a32c61b0315bbc3754c73e4cd24644db503be45a31eb6628f1731df68013f98e09fb9d07fcac11fbbc21f9cb35f5db4cf2ea69f3f68afcffa4",
144
+ magma: "0000040303120a0822130d341d114729115a36106b440f7651127c5d177f6a1c81762181832681902a819c2e7faa337db73779c43c75d0416fdc4869e75263ef5d5ef56b5cf9795dfc8961fd9869fea772feb67cfec488fed395fde2a3fcf0b2fcfdbf",
145
+ cividis: "00224e00285b002e6a0533711a386f273e6e32436d3b496c434e6c4b546c535a6d5a5f6e61656f686a716f70737676767d7c788482798c8878938e789b9476a39a74aba072b4a76fbcae6cc4b468cdbb63d5c25edec958e7d150f0d846f9e03afee838",
146
+ turbo: "30123b392a734040a24456c7466be34680f64294ff37a8fa28bceb1ccdd818ddc21fe9af32f2984ef97d6dfe628bff4ba4fc3cb9f635cdec34dfdf37eecf3af8be39fdac34fe962bfb7e21f46617eb500edf3f08d02f05be2102a91601920b017a0403",
147
+ coolwarm: "3b4cc0445acc4e68d85875e16282ea6c8ff1779af782a6fb8db0fe98b9ffa3c2feaec9fcb9d0f9c3d5f4ccd9edd5dbe5dddcdce5d8d1ecd3c5f1ccb8f5c4acf7ba9ff7b093f6a586f4987af08b6eeb7d62e46e56dd5f4bd44e41ca3b37be242eb40426",
148
+ RdBu_r: "0530610e41791752901f63a82a71b23480b93f8ec0529dc86bacd184bcd99bc9e0aed3e6c2ddecd4e6f1e0ecf3ecf2f5f7f6f6f9eee7fbe5d8fddcc9fbccb4f8bb9ef5aa89ee9677e48066db6b55d05548c53e3dba2832ab162a930e267c072267001f",
149
+ jet: "0000800000a40000c80000ed0000ff0020ff0040ff0060ff0080ff00a0ff00c0ff00e0fb16ffe130ffc749ffad63ff947dff7a97ff60b1ff46caff2ce4ff13feed00ffd000ffb200ff9400ff7700ff5900ff3b00ff1e00e80000c400009f0000800000",
150
+ gray: "000000080808101010181818202020282828303030383838404040484848505050585858606060686868707070787878808080888888909090989898a0a0a0a8a8a8b0b0b0b8b8b8c0c0c0c8c8c8d0d0d0d8d8d8e0e0e0e8e8e8f0f0f0f8f8f8ffffff",
151
+ };
152
+ const DIVERGING = ["coolwarm", "RdBu_r"]; // centred on zero for values of both signs
153
+ const STOPS = {};
154
+ function stopsOf(name) {
155
+ const key = name in COLORMAPS ? name : "viridis";
156
+ if (!STOPS[key]) {
157
+ const hex = COLORMAPS[key], out = [];
158
+ for (let i = 0; i < hex.length; i += 6) {
159
+ out.push([0, 2, 4].map((k) => parseInt(hex.slice(i + k, i + k + 2), 16)));
160
+ }
161
+ STOPS[key] = out;
162
+ }
163
+ return STOPS[key];
164
+ }
165
+ function colormap(name, t) { // [r, g, b] (0-255) of t in [0, 1], interpolated linearly
166
+ const stops = stopsOf(name), n = stops.length - 1;
167
+ const x = Math.min(Math.max(Number.isFinite(t) ? t : 0, 0), 1) * n;
168
+ const i = Math.min(Math.floor(x), n - 1), f = x - i;
169
+ return [0, 1, 2].map((c) => Math.round(stops[i][c] + f * (stops[i + 1][c] - stops[i][c])));
170
+ }
171
+ function colormapTable(name, size) { // RGBA bytes of size colours, for a texture
172
+ const n = size || 256, out = new Uint8Array(4 * n);
173
+ for (let k = 0; k < n; k++) {
174
+ const [r, g, b] = colormap(name, k / (n - 1));
175
+ out.set([r, g, b, 255], 4 * k);
176
+ }
177
+ return out;
178
+ }
179
+ function gradient(name) { // a CSS gradient of a colour map, from left to right
180
+ const stops = [];
181
+ for (let k = 0; k <= 16; k++) {
182
+ const [r, g, b] = colormap(name, k / 16);
183
+ stops.push(`rgb(${r},${g},${b}) ${(100 * k / 16).toFixed(2)}%`);
184
+ }
185
+ return `linear-gradient(to right, ${stops.join(", ")})`;
186
+ }
187
+ // the scale of a field: its range, from zero when it nearly starts there, centred on zero
188
+ // for the diverging maps when the values change sign (as morphogen.viz.video), widened
189
+ // when it collapses
190
+ function defaultRange(lo, hi, cmap) {
191
+ if (!Number.isFinite(lo) || !Number.isFinite(hi)) return [0, 1];
192
+ if (lo > hi) [lo, hi] = [hi, lo];
193
+ if (Math.abs(lo) < 1e-9 * Math.abs(hi)) lo = 0;
194
+ if (DIVERGING.includes(cmap) && lo < 0 && hi > 0) {
195
+ const m = Math.max(-lo, hi);
196
+ lo = -m;
197
+ hi = m;
198
+ }
199
+ if (hi <= lo) {
200
+ const pad = Math.abs(lo) * 0.05 || 0.5;
201
+ lo -= pad;
202
+ hi += pad;
203
+ }
204
+ return [lo, hi];
205
+ }
206
+
207
+ // -- the data of /api/surface ---------------------------------------------------------------
208
+ function decode(text, Type) { // a typed array of base64 bytes (little-endian, as every browser)
209
+ if (!text) return null;
210
+ const bin = atob(text), n = bin.length, bytes = new Uint8Array(n);
211
+ for (let i = 0; i < n; i++) bytes[i] = bin.charCodeAt(i);
212
+ return new Type(bytes.buffer, 0, n / Type.BYTES_PER_ELEMENT);
213
+ }
214
+ // the arrays of the vertices: positions and normals (of voxel faces, from their nodes and
215
+ // directions), regions (inside, outside), field values (front, back), displacement
216
+ function surfaceArrays(data) {
217
+ const n = data.vertices;
218
+ let positions, normals;
219
+ if (data.lattice) {
220
+ const node = decode(data.lattice.node, Uint32Array), dir = decode(data.lattice.direction, Uint8Array);
221
+ const [, ny, nz] = data.lattice.nodes;
222
+ const h = [0, 1, 2].map((a) => (data.upper[a] - data.lower[a]) / (data.lattice.nodes[a] - 1));
223
+ positions = new Float32Array(3 * n);
224
+ normals = new Float32Array(3 * n);
225
+ for (let v = 0; v < n; v++) {
226
+ const id = node[v], k = id % nz, j = Math.floor(id / nz) % ny, i = Math.floor(id / (ny * nz));
227
+ positions[3 * v] = data.lower[0] + i * h[0];
228
+ positions[3 * v + 1] = data.lower[1] + j * h[1];
229
+ positions[3 * v + 2] = data.lower[2] + k * h[2];
230
+ normals[3 * v + (dir[v] >> 1)] = dir[v] & 1 ? -1 : 1;
231
+ }
232
+ } else {
233
+ positions = decode(data.positions, Float32Array) || new Float32Array(0);
234
+ normals = decode(data.normals, Float32Array) || new Float32Array(0);
235
+ }
236
+ const regions = new Int32Array(2 * n);
237
+ for (const [inside, outside, first, count] of data.groups) {
238
+ for (let v = first; v < first + count; v++) {
239
+ regions[2 * v] = inside;
240
+ regions[2 * v + 1] = outside;
241
+ }
242
+ }
243
+ const field = data.field || {};
244
+ return {
245
+ positions, normals, regions,
246
+ indices: decode(data.indices, Uint32Array) || new Uint32Array(0),
247
+ values: field.values ? decode(field.values, Float32Array) : null,
248
+ displacement: data.displacement ? decode(data.displacement, Float32Array) : null,
249
+ };
250
+ }
251
+ function volumeArray(volume) {
252
+ if (!volume) return null;
253
+ const Type = {uint8: Uint8Array, uint16: Uint16Array, uint32: Uint32Array}[volume.dtype];
254
+ return decode(volume.data, Type);
255
+ }
256
+ function hexColor(hex) {
257
+ const h = String(hex || "#888888").replace("#", "");
258
+ return [0, 2, 4].map((k) => parseInt(h.slice(k, k + 2), 16) || 0);
259
+ }
260
+ function fmt(v) {
261
+ return Number.isFinite(v) ? String(+Number(v).toPrecision(4)) : "";
262
+ }
263
+
264
+ // -- WebGL ----------------------------------------------------------------------------------
265
+ const HEAD = `#version 300 es
266
+ precision highp float;
267
+ precision highp int;
268
+ precision highp sampler3D;
269
+ precision highp usampler3D;
270
+ `;
271
+ const SURFACE_VS = HEAD + `
272
+ in vec3 aPos;
273
+ in vec3 aNormal;
274
+ in ivec2 aRegion;
275
+ in vec2 aValue;
276
+ in vec3 aDisp;
277
+ uniform mat4 uProj;
278
+ uniform mat4 uView;
279
+ uniform float uMag;
280
+ uniform vec4 uClip;
281
+ out vec3 vNormal;
282
+ out vec3 vModelNormal;
283
+ out vec3 vPos;
284
+ out float vClip;
285
+ out vec2 vValue;
286
+ flat out ivec2 vRegion;
287
+ void main() {
288
+ vec3 p = aPos + uMag * aDisp;
289
+ vPos = aPos;
290
+ vClip = dot(uClip.xyz, p) + uClip.w;
291
+ vNormal = mat3(uView) * aNormal;
292
+ vModelNormal = aNormal;
293
+ vValue = aValue;
294
+ vRegion = aRegion;
295
+ gl_Position = uProj * uView * vec4(p, 1.0);
296
+ }`;
297
+ const COMMON_FS = HEAD + `
298
+ uniform sampler2D uRegions;
299
+ uniform sampler2D uCmap;
300
+ uniform usampler3D uField;
301
+ uniform vec2 uRange;
302
+ uniform vec2 uFieldRange;
303
+ uniform vec3 uLower;
304
+ uniform vec3 uUpper;
305
+ uniform ivec3 uCells;
306
+ uniform vec3 uLight;
307
+ uniform float uAmbient;
308
+ uniform float uEps;
309
+ out vec4 color;
310
+ vec4 region(int id) {
311
+ ivec2 size = textureSize(uRegions, 0);
312
+ return texelFetch(uRegions, ivec2(id % size.x, id / size.x), 0);
313
+ }
314
+ vec3 cmap(float v) {
315
+ float span = uRange.y - uRange.x;
316
+ float t = span > 0.0 ? clamp((v - uRange.x) / span, 0.0, 1.0) : 0.5;
317
+ return texture(uCmap, vec2(t, 0.5)).rgb;
318
+ }
319
+ ivec3 cellOf(vec3 p) {
320
+ ivec3 c = ivec3(floor((p - uLower) / (uUpper - uLower) * vec3(uCells)));
321
+ return clamp(c, ivec3(0), uCells - 1);
322
+ }
323
+ float voxel(vec3 p) {
324
+ float q = float(texelFetch(uField, cellOf(p), 0).r) / 65535.0;
325
+ return uFieldRange.x + q * (uFieldRange.y - uFieldRange.x);
326
+ }
327
+ vec4 lit(vec3 base, vec3 normal) {
328
+ vec3 n = normalize(normal);
329
+ if (!gl_FrontFacing) n = -n;
330
+ return vec4(base * (uAmbient + (1.0 - uAmbient) * max(dot(n, uLight), 0.0)), 1.0);
331
+ }
332
+ `;
333
+ const SURFACE_FS = COMMON_FS + `
334
+ uniform int uMode; // 0 colours of the regions, 1 field at the vertices, 2 field of the voxels
335
+ in vec3 vNormal;
336
+ in vec3 vModelNormal;
337
+ in vec3 vPos;
338
+ in float vClip;
339
+ in vec2 vValue;
340
+ flat in ivec2 vRegion;
341
+ void main() {
342
+ if (vClip < uEps) discard;
343
+ bool near = gl_FrontFacing || vRegion.y < 0; // the inside; behind the faces of the box too
344
+ vec4 r = region(near ? vRegion.x : vRegion.y);
345
+ if (r.a < 0.5) discard;
346
+ vec3 base = r.rgb;
347
+ if (uMode == 1) {
348
+ base = cmap(near ? vValue.x : vValue.y);
349
+ } else if (uMode == 2) { // the voxel behind the face, or in front of it
350
+ vec3 h = (uUpper - uLower) / vec3(uCells);
351
+ base = cmap(voxel(vPos + (near ? -0.5 : 0.5) * h * vModelNormal));
352
+ }
353
+ color = lit(base, vNormal);
354
+ }`;
355
+ const CAP_VS = HEAD + `
356
+ in vec3 aPos;
357
+ uniform mat4 uProj;
358
+ uniform mat4 uView;
359
+ uniform vec4 uClip;
360
+ out vec3 vPos;
361
+ out float vClip;
362
+ void main() {
363
+ vPos = aPos;
364
+ vClip = dot(uClip.xyz, aPos) + uClip.w;
365
+ gl_Position = uProj * uView * vec4(aPos, 1.0);
366
+ }`;
367
+ const CAP_FS = COMMON_FS + `
368
+ uniform int uMode; // 0 colours of the regions, 2 field of the voxels
369
+ uniform int uVolume; // 1 level set (two phases), 2 regions of the cells
370
+ uniform bool uClipped; // the faces of the box, cut by the section (not the section)
371
+ uniform sampler3D uLevel;
372
+ uniform usampler3D uRegionVolume;
373
+ uniform vec3 uNormal;
374
+ in vec3 vPos;
375
+ in float vClip;
376
+ void main() {
377
+ if (uClipped && vClip < -uEps) discard;
378
+ int id;
379
+ if (uVolume == 1) {
380
+ id = texture(uLevel, (vPos - uLower) / (uUpper - uLower)).r < 127.5 / 255.0 ? 1 : 0;
381
+ } else {
382
+ id = int(texelFetch(uRegionVolume, cellOf(vPos), 0).r);
383
+ }
384
+ vec4 r = region(id);
385
+ if (r.a < 0.5) discard;
386
+ color = lit(uMode == 2 ? cmap(voxel(vPos)) : r.rgb, uNormal);
387
+ }`;
388
+ const LINE_VS = HEAD + `
389
+ in vec3 aPos;
390
+ uniform mat4 uProj;
391
+ uniform mat4 uView;
392
+ void main() { gl_Position = uProj * uView * vec4(aPos, 1.0); }`;
393
+ const LINE_FS = HEAD + `
394
+ uniform vec3 uColor;
395
+ out vec4 color;
396
+ void main() { color = vec4(uColor, 1.0); }`;
397
+
398
+ function compile(gl, vs, fs) {
399
+ const program = gl.createProgram();
400
+ for (const [type, source] of [[gl.VERTEX_SHADER, vs], [gl.FRAGMENT_SHADER, fs]]) {
401
+ const shader = gl.createShader(type);
402
+ gl.shaderSource(shader, source);
403
+ gl.compileShader(shader);
404
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
405
+ throw new Error("shader: " + gl.getShaderInfoLog(shader));
406
+ }
407
+ gl.attachShader(program, shader);
408
+ }
409
+ gl.linkProgram(program);
410
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) throw new Error("program: " + gl.getProgramInfoLog(program));
411
+ const uniforms = {};
412
+ const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
413
+ for (let i = 0; i < n; i++) {
414
+ const name = gl.getActiveUniform(program, i).name;
415
+ uniforms[name] = gl.getUniformLocation(program, name);
416
+ }
417
+ return {program, uniforms, attribute: (name) => gl.getAttribLocation(program, name)};
418
+ }
419
+ const UNITS = {uRegions: 0, uCmap: 1, uLevel: 2, uRegionVolume: 3, uField: 4};
420
+
421
+ // -- the view ---------------------------------------------------------------------------------
422
+ const FOV = 30 * Math.PI / 180;
423
+ const VIEW = {yaw: -1.0, pitch: 0.45};
424
+ const VIEWERS = new Set();
425
+ let STYLED = false;
426
+ const CSS = `
427
+ .v3d-slot { margin: 10px 0; }
428
+ .v3d { border: 1px solid var(--line); border-radius: 8px; background: var(--panel); padding: 8px;
429
+ max-width: 980px; }
430
+ .v3d-stage { position: relative; height: min(520px, 70vh); border-radius: 6px; overflow: hidden;
431
+ background: var(--surface); touch-action: none; }
432
+ .v3d-stage canvas { width: 100%; height: 100%; display: block; cursor: grab; outline: none; }
433
+ .v3d-stage canvas:active { cursor: grabbing; }
434
+ .v3d-msg { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
435
+ padding: 20px; text-align: center; color: var(--muted); font-size: 13px; pointer-events: none; }
436
+ .v3d-msg.error { color: var(--warn); }
437
+ .v3d-label { position: absolute; font: 600 11px system-ui, sans-serif; pointer-events: none;
438
+ transform: translate(-50%, -50%); }
439
+ .v3d-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 14px; margin: 8px 2px 0;
440
+ font-size: 12px; }
441
+ .v3d label { display: inline-flex; align-items: center; gap: 5px; margin: 0; font-weight: 400;
442
+ font-size: 12px; }
443
+ .v3d input, .v3d select { width: auto; padding: 3px 6px; font-size: 12px; }
444
+ .v3d input[type=checkbox] { margin: 0; }
445
+ .v3d input[type=range] { width: 130px; padding: 0; }
446
+ .v3d input.num { width: 76px; }
447
+ .v3d button.plain { margin: 0; padding: 4px 9px; font-size: 12px; }
448
+ .v3d-swatch { display: inline-block; width: 12px; height: 12px; border-radius: 3px;
449
+ border: 1px solid var(--line); }
450
+ .v3d-ramp { display: inline-block; width: 150px; height: 12px; border-radius: 3px;
451
+ border: 1px solid var(--line); }
452
+ .v3d-info { color: var(--muted); font-size: 12px; }
453
+ `;
454
+ function style() {
455
+ if (STYLED || typeof document === "undefined") return;
456
+ const el = document.createElement("style");
457
+ el.id = "v3d-style";
458
+ el.textContent = CSS;
459
+ document.head.appendChild(el);
460
+ STYLED = true;
461
+ }
462
+ function cssColor(el, name, fallback) { // a colour variable of the page, as [r, g, b] in 0-1
463
+ const value = getComputedStyle(el).getPropertyValue(name).trim();
464
+ const m = /^#([0-9a-f]{6})$/i.exec(value);
465
+ return (m ? hexColor(m[1]) : fallback).map((c) => c / 255);
466
+ }
467
+ function esc(s) {
468
+ return String(s).replace(/[&<>"]/g, (c) => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;"}[c]));
469
+ }
470
+
471
+ class Viewer {
472
+ constructor(slot, options) {
473
+ style();
474
+ for (const v of [...VIEWERS]) if (!v.canvas.isConnected) v.dispose();
475
+ VIEWERS.add(this);
476
+ this.slot = slot;
477
+ this.options = options;
478
+ this.key = options.key;
479
+ this.camera = null;
480
+ this.data = null;
481
+ this.mode = 0;
482
+ slot.innerHTML = `<div class="v3d">
483
+ <div class="v3d-stage"><canvas tabindex="0" aria-label="3D view"></canvas><div class="v3d-msg">Drawing the surface…</div></div>
484
+ <div class="v3d-bar">
485
+ <button class="plain" data-v="reset" title="the first view">Reset view</button>
486
+ <label title="the edges and axes of the cell"><input type="checkbox" data-v="box" checked>box</label>
487
+ <label title="a plane cutting the structure, to see inside">Section <select data-v="axis">
488
+ <option value="none">none</option><option value="x">normal to x</option><option value="y">normal to y</option><option value="z">normal to z</option></select></label>
489
+ <input type="range" data-v="cut" min="0.005" max="0.995" step="0.005" value="0.5" title="position of the section">
490
+ <label title="keep the other side of the section"><input type="checkbox" data-v="flip">other side</label>
491
+ <label>Colours <select data-v="colour"></select></label>
492
+ </div>
493
+ <div class="v3d-bar" data-v="phases"></div>
494
+ <div class="v3d-bar" data-v="fieldbar" hidden>
495
+ <label>Field <select data-v="field"></select></label>
496
+ <label>Colormap <select data-v="cmap"></select></label>
497
+ <input class="num" data-v="lo" title="smallest value of the scale">
498
+ <span class="v3d-ramp" data-v="ramp"></span>
499
+ <input class="num" data-v="hi" title="largest value of the scale">
500
+ <span data-v="deform" hidden><label title="displacement drawn: magnification times the displacement">Magnification
501
+ <input class="num" data-v="mag"></label> <input type="range" data-v="magr" min="0" max="3" step="0.02" value="1" title="0 to 3 times the automatic magnification"></span>
502
+ </div>
503
+ <div class="v3d-bar">
504
+ <span data-v="resrow"><label title="cells along the longest edge of the grid of the surface">Resolution
505
+ <input type="number" class="num" data-v="res" min="8" max="256" value="${options.resolution || 96}"></label>
506
+ <button class="plain" data-v="redraw">Redraw</button></span>
507
+ <span class="v3d-info" data-v="info"></span>
508
+ <span class="v3d-info" data-v="hint" hidden>(the section is filled on the undeformed mesh: magnification 0)</span>
509
+ </div>
510
+ <div class="v3d-bar v3d-info">drag: turn · shift-drag or right-drag: move · wheel: zoom</div>
511
+ </div>`;
512
+ this.el = (name) => slot.querySelector(`[data-v="${name}"]`);
513
+ this.canvas = slot.querySelector("canvas");
514
+ this.message = slot.querySelector(".v3d-msg");
515
+ this.stage = slot.querySelector(".v3d-stage");
516
+ this.el("cmap").innerHTML = Object.keys(COLORMAPS).map((c) => `<option>${c}</option>`).join("");
517
+ this.el("cmap").value = options.cmap && options.cmap in COLORMAPS ? options.cmap : "viridis";
518
+ this.gl = this.canvas.getContext("webgl2", {antialias: true, alpha: false});
519
+ if (!this.gl) {
520
+ this.fail("The 3D view needs WebGL 2, which this browser does not offer (or has turned off). The sections and views above show the item.");
521
+ return;
522
+ }
523
+ try {
524
+ this.setup();
525
+ } catch (e) {
526
+ this.gl = null;
527
+ this.fail("The 3D view cannot start here: " + e.message);
528
+ return;
529
+ }
530
+ this.bind();
531
+ this.load({field: options.field});
532
+ }
533
+
534
+ fail(text) {
535
+ this.message.textContent = text;
536
+ this.message.classList.add("error");
537
+ this.message.hidden = false;
538
+ }
539
+
540
+ setup() {
541
+ const gl = this.gl;
542
+ this.programs = {
543
+ surface: compile(gl, SURFACE_VS, SURFACE_FS),
544
+ cap: compile(gl, CAP_VS, CAP_FS),
545
+ line: compile(gl, LINE_VS, LINE_FS),
546
+ };
547
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
548
+ this.textures = {};
549
+ const make = (target, unit) => {
550
+ const t = gl.createTexture();
551
+ gl.activeTexture(gl.TEXTURE0 + unit);
552
+ gl.bindTexture(target, t);
553
+ return t;
554
+ };
555
+ // a texture of each kind bound to its unit, so that every sampler finds its type
556
+ this.textures.regions = make(gl.TEXTURE_2D, UNITS.uRegions);
557
+ this.texture2D(this.textures.regions, UNITS.uRegions, 1, 1, new Uint8Array([128, 128, 128, 255]), false);
558
+ this.textures.cmap = make(gl.TEXTURE_2D, UNITS.uCmap);
559
+ this.textures.level = make(gl.TEXTURE_3D, UNITS.uLevel);
560
+ this.texture3D(this.textures.level, UNITS.uLevel, [1, 1, 1], gl.R8, gl.RED, gl.UNSIGNED_BYTE, new Uint8Array([255]), gl.LINEAR, false);
561
+ this.textures.regionVolume = make(gl.TEXTURE_3D, UNITS.uRegionVolume);
562
+ this.texture3D(this.textures.regionVolume, UNITS.uRegionVolume, [1, 1, 1], gl.R8UI, gl.RED_INTEGER, gl.UNSIGNED_BYTE, new Uint8Array([0]), gl.NEAREST, false);
563
+ this.textures.field = make(gl.TEXTURE_3D, UNITS.uField);
564
+ this.texture3D(this.textures.field, UNITS.uField, [1, 1, 1], gl.R16UI, gl.RED_INTEGER, gl.UNSIGNED_SHORT, new Uint16Array([0]), gl.NEAREST, false);
565
+ this.setColormap();
566
+ this.surfaceVao = null;
567
+ this.buffers = [];
568
+ this.lines = gl.createBuffer();
569
+ this.quads = gl.createBuffer();
570
+ this.canvas.addEventListener("webglcontextlost", (e) => {
571
+ e.preventDefault();
572
+ this.lost = true;
573
+ this.fail("The 3D view lost its graphics context (too many views open?): open it again.");
574
+ });
575
+ }
576
+
577
+ texture2D(texture, unit, width, height, data, linear) {
578
+ const gl = this.gl;
579
+ gl.activeTexture(gl.TEXTURE0 + unit);
580
+ gl.bindTexture(gl.TEXTURE_2D, texture);
581
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
582
+ const filter = linear ? gl.LINEAR : gl.NEAREST;
583
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter);
584
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);
585
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
586
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
587
+ }
588
+
589
+ texture3D(texture, unit, shape, internal, format, type, data, filter, wrap) {
590
+ const gl = this.gl;
591
+ gl.activeTexture(gl.TEXTURE0 + unit);
592
+ gl.bindTexture(gl.TEXTURE_3D, texture);
593
+ gl.texImage3D(gl.TEXTURE_3D, 0, internal, shape[0], shape[1], shape[2], 0, format, type, data);
594
+ gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MIN_FILTER, filter);
595
+ gl.texParameteri(gl.TEXTURE_3D, gl.TEXTURE_MAG_FILTER, filter);
596
+ const w = wrap ? gl.REPEAT : gl.CLAMP_TO_EDGE;
597
+ for (const p of [gl.TEXTURE_WRAP_S, gl.TEXTURE_WRAP_T, gl.TEXTURE_WRAP_R]) gl.texParameteri(gl.TEXTURE_3D, p, w);
598
+ }
599
+
600
+ setColormap() {
601
+ this.texture2D(this.textures.cmap, UNITS.uCmap, 256, 1, colormapTable(this.el("cmap").value, 256), true);
602
+ this.el("ramp").style.background = gradient(this.el("cmap").value);
603
+ }
604
+
605
+ bind() { // the controls and the mouse
606
+ const on = (name, event, fn) => this.el(name).addEventListener(event, fn);
607
+ on("reset", "click", () => { this.camera = this.home(); this.draw(); });
608
+ for (const name of ["box", "axis", "cut", "flip"]) on(name, "input", () => this.draw());
609
+ on("axis", "change", () => this.draw());
610
+ on("colour", "change", () => { this.updateMode(); this.updateRegions(); this.draw(); });
611
+ on("cmap", "change", () => { this.setColormap(); this.resetRange(); this.draw(); });
612
+ for (const name of ["lo", "hi"]) on(name, "change", () => this.draw());
613
+ on("field", "change", () => this.load({field: this.el("field").value}));
614
+ on("redraw", "click", () => this.load({field: this.el("field").value}));
615
+ on("res", "keydown", (e) => { if (e.key === "Enter") this.load({field: this.el("field").value}); });
616
+ on("mag", "change", () => {
617
+ const auto = this.autoMag || 1, v = Number(this.el("mag").value);
618
+ if (Number.isFinite(v)) this.el("magr").value = String(Math.min(3, Math.max(0, v / auto)));
619
+ this.draw();
620
+ });
621
+ on("magr", "input", () => {
622
+ this.el("mag").value = fmt(Number(this.el("magr").value) * (this.autoMag || 0));
623
+ this.draw();
624
+ });
625
+ const canvas = this.canvas, pointers = new Map();
626
+ let drag = null;
627
+ canvas.addEventListener("contextmenu", (e) => e.preventDefault());
628
+ canvas.addEventListener("pointerdown", (e) => {
629
+ try {
630
+ canvas.setPointerCapture(e.pointerId); // the drag goes on beyond the canvas
631
+ } catch {
632
+ // a pointer that cannot be captured: dragged within the canvas only
633
+ }
634
+ pointers.set(e.pointerId, [e.clientX, e.clientY]);
635
+ drag = {pan: e.button === 2 || e.button === 1 || e.shiftKey, x: e.clientX, y: e.clientY};
636
+ });
637
+ canvas.addEventListener("pointermove", (e) => {
638
+ if (!pointers.has(e.pointerId) || !this.camera) return;
639
+ const before = [...pointers.values()];
640
+ pointers.set(e.pointerId, [e.clientX, e.clientY]);
641
+ if (pointers.size === 2) { // pinch: zoom and move
642
+ const after = [...pointers.values()];
643
+ const span = (p) => Math.hypot(p[0][0] - p[1][0], p[0][1] - p[1][1]) || 1;
644
+ const mid = (p) => [(p[0][0] + p[1][0]) / 2, (p[0][1] + p[1][1]) / 2];
645
+ this.zoom(span(before) / span(after));
646
+ const [x0, y0] = mid(before), [x1, y1] = mid(after);
647
+ this.pan(x1 - x0, y1 - y0);
648
+ } else if (drag) {
649
+ const dx = e.clientX - drag.x, dy = e.clientY - drag.y;
650
+ drag.x = e.clientX;
651
+ drag.y = e.clientY;
652
+ if (drag.pan || e.shiftKey) this.pan(dx, dy);
653
+ else {
654
+ this.camera.yaw -= dx * 0.008;
655
+ this.camera.pitch = Math.min(1.55, Math.max(-1.55, this.camera.pitch + dy * 0.008));
656
+ }
657
+ }
658
+ this.draw();
659
+ });
660
+ const up = (e) => {
661
+ pointers.delete(e.pointerId);
662
+ if (!pointers.size) drag = null;
663
+ else {
664
+ const [x, y] = [...pointers.values()][0];
665
+ drag = {pan: false, x, y};
666
+ }
667
+ };
668
+ canvas.addEventListener("pointerup", up);
669
+ canvas.addEventListener("pointercancel", up);
670
+ canvas.addEventListener("wheel", (e) => {
671
+ if (!this.camera) return;
672
+ e.preventDefault();
673
+ const step = e.deltaMode === 1 ? 33 : (e.deltaMode === 2 ? 400 : 1);
674
+ this.zoom(Math.exp(e.deltaY * step * 0.0015));
675
+ this.draw();
676
+ }, {passive: false});
677
+ canvas.addEventListener("dblclick", () => { this.camera = this.home(); this.draw(); });
678
+ if (typeof ResizeObserver !== "undefined") {
679
+ this.resizer = new ResizeObserver(() => this.draw());
680
+ this.resizer.observe(this.stage);
681
+ }
682
+ if (typeof matchMedia !== "undefined") {
683
+ this.scheme = matchMedia("(prefers-color-scheme: dark)");
684
+ this.onScheme = () => this.draw();
685
+ this.scheme.addEventListener("change", this.onScheme);
686
+ }
687
+ }
688
+
689
+ home() {
690
+ const aspect = this.stage.clientWidth / Math.max(this.stage.clientHeight, 1) || 1;
691
+ const box = fit(this.data.lower, this.data.upper, FOV, aspect);
692
+ return {target: box.target, distance: box.distance, radius: box.radius, yaw: VIEW.yaw, pitch: VIEW.pitch};
693
+ }
694
+ zoom(factor) {
695
+ const c = this.camera;
696
+ c.distance = Math.min(40 * c.radius, Math.max(0.05 * c.radius, c.distance * factor));
697
+ }
698
+ pan(dx, dy) {
699
+ const c = this.camera, view = this.viewMatrix();
700
+ const scale = 2 * c.distance * Math.tan(FOV / 2) / Math.max(this.stage.clientHeight, 1);
701
+ const right = [view[0], view[4], view[8]], up = [view[1], view[5], view[9]];
702
+ for (let a = 0; a < 3; a++) c.target[a] += (-dx * right[a] + dy * up[a]) * scale;
703
+ }
704
+ viewMatrix() {
705
+ const c = this.camera;
706
+ return lookAt(orbitEye(c.target, c.distance, c.yaw, c.pitch), c.target, [0, 0, 1]);
707
+ }
708
+
709
+ async load(params) {
710
+ const q = new URLSearchParams({key: this.key});
711
+ const res = Number(this.el("res").value);
712
+ if (res) q.set("resolution", String(res));
713
+ if (params.field) q.set("field", params.field);
714
+ this.message.textContent = "Drawing the surface…";
715
+ this.message.classList.remove("error");
716
+ this.message.hidden = false;
717
+ let data;
718
+ try {
719
+ const reply = await fetch("/api/surface?" + q);
720
+ data = await reply.json();
721
+ if (!reply.ok || data.error) {
722
+ // a field of the form that this simulation has not: its first field instead
723
+ if (params.field && /^field/.test(data.error || "")) return this.load({});
724
+ throw new Error(data.error || reply.statusText);
725
+ }
726
+ } catch (e) {
727
+ this.fail(e.message);
728
+ return;
729
+ }
730
+ if (!this.gl || this.lost) return;
731
+ this.setData(data);
732
+ }
733
+
734
+ setData(data) {
735
+ const gl = this.gl, arrays = surfaceArrays(data);
736
+ const first = !this.data;
737
+ this.data = data;
738
+ this.arrays = arrays;
739
+ for (const b of this.buffers) gl.deleteBuffer(b);
740
+ this.buffers = [];
741
+ if (this.surfaceVao) gl.deleteVertexArray(this.surfaceVao);
742
+ const program = this.programs.surface;
743
+ this.surfaceVao = gl.createVertexArray();
744
+ gl.bindVertexArray(this.surfaceVao);
745
+ const attribute = (name, array, size, integer) => {
746
+ const loc = program.attribute(name);
747
+ if (loc < 0) return;
748
+ if (!array) {
749
+ gl.disableVertexAttribArray(loc);
750
+ return;
751
+ }
752
+ const buffer = gl.createBuffer();
753
+ this.buffers.push(buffer);
754
+ gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
755
+ gl.bufferData(gl.ARRAY_BUFFER, array, gl.STATIC_DRAW);
756
+ gl.enableVertexAttribArray(loc);
757
+ if (integer) gl.vertexAttribIPointer(loc, size, gl.INT, 0, 0);
758
+ else gl.vertexAttribPointer(loc, size, gl.FLOAT, false, 0, 0);
759
+ };
760
+ attribute("aPos", arrays.positions, 3);
761
+ attribute("aNormal", arrays.normals, 3);
762
+ attribute("aRegion", arrays.regions, 2, true);
763
+ attribute("aValue", arrays.values, 2);
764
+ attribute("aDisp", arrays.displacement, 3);
765
+ const index = gl.createBuffer();
766
+ this.buffers.push(index);
767
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index);
768
+ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, arrays.indices, gl.STATIC_DRAW);
769
+ gl.bindVertexArray(null);
770
+ // the volumes: level set or regions of the cells, field of the voxels
771
+ const volume = data.volume, values = volumeArray(volume);
772
+ this.volume = volume ? volume.kind : null;
773
+ if (volume && volume.kind === "level_set") {
774
+ this.texture3D(this.textures.level, UNITS.uLevel, volume.shape, gl.R8, gl.RED, gl.UNSIGNED_BYTE, values, gl.LINEAR, !!volume.periodic);
775
+ } else if (volume) {
776
+ const [internal, type] = {uint8: [gl.R8UI, gl.UNSIGNED_BYTE], uint16: [gl.R16UI, gl.UNSIGNED_SHORT], uint32: [gl.R32UI, gl.UNSIGNED_INT]}[volume.dtype];
777
+ this.texture3D(this.textures.regionVolume, UNITS.uRegionVolume, volume.shape, internal, gl.RED_INTEGER, type, values, gl.NEAREST, false);
778
+ }
779
+ this.cells = volume ? volume.shape : [1, 1, 1];
780
+ const fieldVolume = data.field && data.field.volume;
781
+ if (fieldVolume) {
782
+ this.texture3D(this.textures.field, UNITS.uField, fieldVolume.shape, gl.R16UI, gl.RED_INTEGER, gl.UNSIGNED_SHORT, volumeArray(fieldVolume), gl.NEAREST, false);
783
+ this.cells = fieldVolume.shape;
784
+ }
785
+ this.fieldRange = fieldVolume ? fieldVolume.range : [0, 1];
786
+ this.controls(first);
787
+ if (first || !this.camera) this.camera = this.home();
788
+ this.message.hidden = true;
789
+ this.draw();
790
+ }
791
+
792
+ controls(first) { // the controls of the data: colours, phases, field, magnification, info
793
+ const data = this.data, regions = data.regions;
794
+ const colour = this.el("colour"), keep = colour.value;
795
+ const modes = [];
796
+ if (data.field) modes.push(["field", data.field.name]);
797
+ modes.push(["phase", "phases"]);
798
+ if (regions.label) modes.push(["label", data.kind === "simulation" ? "grains" : "cells"]);
799
+ colour.innerHTML = modes.map(([v, t]) => `<option value="${v}">${esc(t)}</option>`).join("");
800
+ const labelled = regions.label && regions.label.some((k) => k >= 0);
801
+ colour.value = modes.some(([v]) => v === keep) ? keep : (data.field ? "field" : (labelled && data.method === "cells" ? "label" : "phase"));
802
+ colour.closest("label").hidden = modes.length < 2;
803
+ // the phases, each shown or hidden
804
+ const phases = [...new Set(regions.phase)].sort((a, b) => a - b);
805
+ this.visible = this.visible || {};
806
+ const colorOf = {};
807
+ regions.phase.forEach((p, r) => { if (!(p in colorOf)) colorOf[p] = regions.color[r]; });
808
+ this.el("phases").innerHTML = "Phases " + phases.map((p) => {
809
+ const name = (data.phases || {})[String(p)];
810
+ const on = this.visible[p] !== false;
811
+ return `<label><input type="checkbox" data-phase="${p}" ${on ? "checked" : ""}><span class="v3d-swatch" style="background:${colorOf[p]}"></span>${esc(p)}${name ? ": " + esc(name) : ""}</label>`;
812
+ }).join("");
813
+ for (const box of this.el("phases").querySelectorAll("input[data-phase]")) {
814
+ box.addEventListener("change", () => {
815
+ this.visible[box.dataset.phase] = box.checked;
816
+ this.updateRegions();
817
+ this.draw();
818
+ });
819
+ }
820
+ // the field: its name, scale and the magnification of the displacement
821
+ const field = data.field;
822
+ this.el("fieldbar").hidden = !field;
823
+ if (field) {
824
+ this.el("field").innerHTML = field.names.map((n) => `<option>${esc(n)}</option>`).join("");
825
+ this.el("field").value = field.name;
826
+ this.resetRange();
827
+ }
828
+ this.autoMag = data.magnification;
829
+ this.el("deform").hidden = !data.displacement;
830
+ if (data.displacement && (first || this.el("mag").value === "")) {
831
+ this.el("mag").value = fmt(this.autoMag);
832
+ this.el("magr").value = "1";
833
+ }
834
+ this.el("resrow").hidden = data.kind !== "morphology";
835
+ if (data.kind === "morphology" && data.resolution) this.el("res").value = String(data.requested || data.resolution);
836
+ const how = {"marching cubes": "marching cubes of the level set", cells: "exact cells", voxels: "faces of the voxels", mesh: "faces of the mesh"}[data.method] || data.method;
837
+ const grid = data.resolution ? `, ${data.resolution} cells per edge` : "";
838
+ const fewer = data.reduced ? ` (coarser to stay within ${data.budget.toLocaleString("en")} triangles)` : "";
839
+ this.el("info").textContent = `${data.triangles.toLocaleString("en")} triangles: ${how}${grid}${fewer}, ${data.time_s} s`;
840
+ this.updateMode();
841
+ this.updateRegions();
842
+ }
843
+
844
+ resetRange() {
845
+ const field = this.data && this.data.field;
846
+ if (!field) return;
847
+ const shown = field.shown || field.range; // the percentiles 1 to 99: a singular peak stays bright
848
+ const [lo, hi] = defaultRange(shown[0], shown[1], this.el("cmap").value);
849
+ this.el("lo").value = fmt(lo);
850
+ this.el("hi").value = fmt(hi);
851
+ }
852
+
853
+ updateMode() { // the colours of the surface, and of the faces of the box and sections
854
+ const data = this.data, field = this.el("colour").value === "field" && data.field;
855
+ this.mode = field ? (field.values ? 1 : (field.volume ? 2 : 0)) : 0;
856
+ this.capField = !!(field && field.volume);
857
+ }
858
+
859
+ updateRegions() { // the colour and visibility of each region, in a texture
860
+ // (one more region, transparent: that of the cells of no region, e.g. pores of a mesh)
861
+ const regions = this.data.regions, n = regions.phase.length + 1;
862
+ const width = Math.min(n, 1024), height = Math.ceil(n / width);
863
+ const bytes = new Uint8Array(4 * width * height);
864
+ const labels = this.el("colour").value === "label" && regions.label_color;
865
+ regions.phase.forEach((p, r) => {
866
+ const rgb = hexColor(labels ? regions.label_color[r] : regions.color[r]);
867
+ bytes.set([...rgb, this.visible[p] === false ? 0 : 255], 4 * r);
868
+ });
869
+ this.texture2D(this.textures.regions, UNITS.uRegions, width, height, bytes, false);
870
+ }
871
+
872
+ draw() {
873
+ if (this.pending || !this.gl || !this.data || this.lost) return;
874
+ this.pending = true;
875
+ requestAnimationFrame(() => {
876
+ this.pending = false;
877
+ if (this.canvas.isConnected) this.render();
878
+ });
879
+ }
880
+
881
+ render() {
882
+ const gl = this.gl, data = this.data, canvas = this.canvas;
883
+ const ratio = Math.min(window.devicePixelRatio || 1, 2);
884
+ const width = Math.max(1, Math.round(canvas.clientWidth * ratio));
885
+ const height = Math.max(1, Math.round(canvas.clientHeight * ratio));
886
+ if (canvas.width !== width || canvas.height !== height) {
887
+ canvas.width = width;
888
+ canvas.height = height;
889
+ }
890
+ gl.viewport(0, 0, width, height);
891
+ const background = cssColor(this.stage, "--surface", [252, 252, 251]);
892
+ gl.clearColor(background[0], background[1], background[2], 1);
893
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
894
+ gl.enable(gl.DEPTH_TEST);
895
+ gl.disable(gl.CULL_FACE);
896
+ const c = this.camera;
897
+ const near = Math.max(c.distance - 2.5 * c.radius, c.distance * 0.01);
898
+ const proj = perspective(FOV, width / height, near, c.distance + 2.5 * c.radius);
899
+ const view = this.viewMatrix();
900
+ const light = normalize([0.3, 0.45, 0.85]); // from the eye, a little above and right
901
+ const clip = clipPlane(this.el("axis").value, Number(this.el("cut").value), data.lower, data.upper, this.el("flip").checked);
902
+ const size = Math.max(...[0, 1, 2].map((a) => data.upper[a] - data.lower[a])) || 1;
903
+ const [lo, hi] = [Number(this.el("lo").value), Number(this.el("hi").value)];
904
+ const shared = (u) => {
905
+ gl.uniformMatrix4fv(u.uProj, false, proj);
906
+ gl.uniformMatrix4fv(u.uView, false, view);
907
+ if (u.uClip) gl.uniform4fv(u.uClip, clip);
908
+ if (u.uRegions) {
909
+ for (const [name, unit] of Object.entries(UNITS)) if (u[name]) gl.uniform1i(u[name], unit);
910
+ gl.uniform2f(u.uRange, Number.isFinite(lo) ? lo : 0, Number.isFinite(hi) ? hi : 1);
911
+ gl.uniform2f(u.uFieldRange, this.fieldRange[0], this.fieldRange[1]);
912
+ gl.uniform3fv(u.uLower, data.lower);
913
+ gl.uniform3fv(u.uUpper, data.upper);
914
+ gl.uniform3i(u.uCells, this.cells[0], this.cells[1], this.cells[2]);
915
+ gl.uniform3fv(u.uLight, light);
916
+ gl.uniform1f(u.uAmbient, 0.32);
917
+ gl.uniform1f(u.uEps, 1e-5 * size);
918
+ }
919
+ };
920
+ gl.enable(gl.POLYGON_OFFSET_FILL); // the edges of the box drawn over the faces
921
+ gl.polygonOffset(1, 1);
922
+ if (this.arrays.indices.length) {
923
+ const p = this.programs.surface;
924
+ gl.useProgram(p.program);
925
+ shared(p.uniforms);
926
+ gl.uniform1i(p.uniforms.uMode, this.mode);
927
+ const mag = this.arrays.displacement ? Number(this.el("mag").value) || 0 : 0;
928
+ gl.uniform1f(p.uniforms.uMag, mag);
929
+ gl.bindVertexArray(this.surfaceVao);
930
+ const loc = p.attribute("aValue");
931
+ if (!this.arrays.values && loc >= 0) gl.vertexAttrib2f(loc, 0, 0);
932
+ const disp = p.attribute("aDisp");
933
+ if (!this.arrays.displacement && disp >= 0) gl.vertexAttrib3f(disp, 0, 0, 0);
934
+ gl.drawElements(gl.TRIANGLES, this.arrays.indices.length, gl.UNSIGNED_INT, 0);
935
+ gl.bindVertexArray(null);
936
+ }
937
+ if (this.volume) this.caps(shared, clip, view);
938
+ else this.el("hint").hidden = true;
939
+ gl.disable(gl.POLYGON_OFFSET_FILL);
940
+ this.outline(proj, view, width, height);
941
+ }
942
+
943
+ caps(shared, clip, view) { // the faces of the box and the section, from the volumes
944
+ const gl = this.gl, data = this.data, p = this.programs.cap;
945
+ const quads = [];
946
+ if (data.volume.box) for (const f of boxFaces(data.lower, data.upper)) quads.push({corners: f.corners, normal: f.normal, clipped: true});
947
+ const axis = axisOf(this.el("axis").value);
948
+ // the volume of a mesh is that of its undeformed elements: no filled section on it
949
+ const deformed = !!this.arrays.displacement && (Number(this.el("mag").value) || 0) !== 0;
950
+ this.el("hint").hidden = !(axis >= 0 && deformed);
951
+ if (axis >= 0 && !deformed) {
952
+ const normal = [0, 0, 0];
953
+ normal[axis] = 1; // that of its corners (counter-clockwise around +axis)
954
+ quads.push({corners: sectionQuad(axis, Number(this.el("cut").value), data.lower, data.upper), normal, clipped: false});
955
+ }
956
+ if (!quads.length) return;
957
+ gl.useProgram(p.program);
958
+ shared(p.uniforms);
959
+ gl.uniform1i(p.uniforms.uMode, this.capField ? 2 : 0);
960
+ gl.uniform1i(p.uniforms.uVolume, this.volume === "level_set" ? 1 : 2);
961
+ const loc = p.attribute("aPos");
962
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.quads);
963
+ gl.enableVertexAttribArray(loc);
964
+ gl.vertexAttribPointer(loc, 3, gl.FLOAT, false, 0, 0);
965
+ for (const q of quads) {
966
+ const [a, b, c2, d] = q.corners;
967
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([...a, ...b, ...c2, ...a, ...c2, ...d]), gl.STREAM_DRAW);
968
+ const n = transform(view, [q.normal[0], q.normal[1], q.normal[2]]);
969
+ const t = [n[0] - view[12], n[1] - view[13], n[2] - view[14]]; // the rotation alone
970
+ gl.uniform3fv(p.uniforms.uNormal, normalize(t));
971
+ gl.uniform1i(p.uniforms.uClipped, q.clipped ? 1 : 0);
972
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
973
+ }
974
+ gl.disableVertexAttribArray(loc);
975
+ }
976
+
977
+ outline(proj, view, width, height) { // the edges of the box, its axes and their names
978
+ const gl = this.gl, data = this.data, p = this.programs.line;
979
+ for (const el of this.stage.querySelectorAll(".v3d-label")) el.remove();
980
+ if (!this.el("box").checked) return;
981
+ const [x0, y0, z0] = data.lower, [x1, y1, z1] = data.upper;
982
+ const corners = [[x0, y0, z0], [x1, y0, z0], [x1, y1, z0], [x0, y1, z0], [x0, y0, z1], [x1, y0, z1], [x1, y1, z1], [x0, y1, z1]];
983
+ const edges = [[0, 1], [1, 2], [2, 3], [3, 0], [4, 5], [5, 6], [6, 7], [7, 4], [0, 4], [1, 5], [2, 6], [3, 7]];
984
+ const segments = edges.flatMap(([a, b]) => [...corners[a], ...corners[b]]);
985
+ gl.useProgram(p.program);
986
+ gl.uniformMatrix4fv(p.uniforms.uProj, false, proj);
987
+ gl.uniformMatrix4fv(p.uniforms.uView, false, view);
988
+ const loc = p.attribute("aPos");
989
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.lines);
990
+ gl.enableVertexAttribArray(loc);
991
+ gl.vertexAttribPointer(loc, 3, gl.FLOAT, false, 0, 0);
992
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(segments), gl.STREAM_DRAW);
993
+ gl.uniform3fv(p.uniforms.uColor, cssColor(this.stage, "--c-muted", [137, 135, 129]));
994
+ gl.drawArrays(gl.LINES, 0, 24);
995
+ // the axes from the lower corner, coloured as the series of the charts
996
+ const length = 0.22 * Math.max(x1 - x0, y1 - y0, z1 - z0);
997
+ const colours = [["--series-2", [235, 104, 52]], ["--series-3", [27, 175, 122]], ["--series-1", [42, 120, 214]]];
998
+ const both = multiply(proj, view);
999
+ gl.disable(gl.DEPTH_TEST);
1000
+ for (let a = 0; a < 3; a++) {
1001
+ const end = [x0, y0, z0];
1002
+ end[a] += length;
1003
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([x0, y0, z0, ...end]), gl.STREAM_DRAW);
1004
+ const rgb = cssColor(this.stage, colours[a][0], colours[a][1]);
1005
+ gl.uniform3fv(p.uniforms.uColor, rgb);
1006
+ gl.drawArrays(gl.LINES, 0, 2);
1007
+ const at = project(both, end, width, height);
1008
+ if (at) {
1009
+ const label = document.createElement("span");
1010
+ label.className = "v3d-label";
1011
+ label.textContent = "xyz"[a];
1012
+ label.style.color = `rgb(${rgb.map((v) => Math.round(255 * v)).join(",")})`;
1013
+ const ratio = width / Math.max(this.canvas.clientWidth, 1);
1014
+ label.style.left = `${at[0] / ratio + 8}px`;
1015
+ label.style.top = `${at[1] / ratio - 8}px`;
1016
+ this.stage.appendChild(label);
1017
+ }
1018
+ }
1019
+ gl.enable(gl.DEPTH_TEST);
1020
+ gl.disableVertexAttribArray(loc);
1021
+ }
1022
+
1023
+ dispose() {
1024
+ VIEWERS.delete(this);
1025
+ if (this.resizer) this.resizer.disconnect();
1026
+ if (this.scheme) this.scheme.removeEventListener("change", this.onScheme);
1027
+ const gl = this.gl;
1028
+ this.gl = null;
1029
+ if (gl) {
1030
+ const ext = gl.getExtension("WEBGL_lose_context");
1031
+ if (ext) ext.loseContext();
1032
+ }
1033
+ }
1034
+ }
1035
+
1036
+ // -- places of the view in the page ---------------------------------------------------------
1037
+ function slot(key, options) { // the HTML of a place for the view of an item of the workspace
1038
+ const o = options || {};
1039
+ const data = [`data-key="${esc(key)}"`];
1040
+ for (const name of ["field", "cmap", "resolution"]) if (o[name]) data.push(`data-${name}="${esc(o[name])}"`);
1041
+ if (o.auto) data.push('data-auto="1"');
1042
+ const title = o.title === undefined ? "3D view" : o.title;
1043
+ const head = title ? `<h3>${esc(title)}</h3>` : "";
1044
+ const button = o.auto ? "" : `<button class="plain v3d-open">${esc(o.label || "View in 3D")}</button>`;
1045
+ return `<div class="v3d-slot" ${data.join(" ")}>${o.auto ? head : ""}${button}<div class="v3d-place"></div></div>`;
1046
+ }
1047
+ function open(element) { // the view of the item of a place (an element made by slot)
1048
+ if (element.dataset.ready) return element.viewer;
1049
+ element.dataset.ready = "1";
1050
+ const button = element.querySelector(".v3d-open");
1051
+ if (button) button.remove();
1052
+ const d = element.dataset;
1053
+ element.viewer = new Viewer(element.querySelector(".v3d-place"), {
1054
+ key: d.key, field: d.field, cmap: d.cmap, resolution: Number(d.resolution) || 0,
1055
+ });
1056
+ return element.viewer;
1057
+ }
1058
+ function install() { // buttons of the places, and the places that open as they show
1059
+ if (typeof document === "undefined") return;
1060
+ document.addEventListener("click", (e) => {
1061
+ const button = e.target.closest && e.target.closest(".v3d-open");
1062
+ if (button) open(button.closest(".v3d-slot"));
1063
+ });
1064
+ const seen = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver((entries) => {
1065
+ for (const entry of entries) {
1066
+ if (entry.isIntersecting) {
1067
+ seen.unobserve(entry.target);
1068
+ open(entry.target);
1069
+ }
1070
+ }
1071
+ });
1072
+ const scan = () => {
1073
+ for (const el of document.querySelectorAll(".v3d-slot[data-auto]:not([data-ready]):not([data-watched])")) {
1074
+ el.dataset.watched = "1";
1075
+ if (seen) seen.observe(el);
1076
+ else open(el);
1077
+ }
1078
+ };
1079
+ const start = () => {
1080
+ scan();
1081
+ new MutationObserver(scan).observe(document.body, {childList: true, subtree: true});
1082
+ };
1083
+ if (document.body) start();
1084
+ else document.addEventListener("DOMContentLoaded", start);
1085
+ }
1086
+
1087
+ const api = {
1088
+ // pure functions, tested by Node
1089
+ identity, multiply, perspective, lookAt, transform, project, orbitEye, fit,
1090
+ clipPlane, sectionQuad, boxFaces, colormap, colormapTable, defaultRange, gradient,
1091
+ decode, surfaceArrays, COLORMAPS, DIVERGING,
1092
+ // the page
1093
+ slot, open, Viewer,
1094
+ };
1095
+ if (typeof module === "object" && module.exports) module.exports = api;
1096
+ if (typeof window !== "undefined") {
1097
+ window.MorphoViewer = api;
1098
+ install();
1099
+ }
1100
+ })();