webgpu-trees 0.0.0-stage → 0.1.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 (322) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1541 -2
  3. package/assets/SOURCES.md +255 -0
  4. package/assets/bark/alder.albedo.avif +0 -0
  5. package/assets/bark/alder.normal.avif +0 -0
  6. package/assets/bark/aleppoPine.albedo.avif +0 -0
  7. package/assets/bark/aleppoPine.normal.avif +0 -0
  8. package/assets/bark/ash.albedo.avif +0 -0
  9. package/assets/bark/ash.normal.avif +0 -0
  10. package/assets/bark/aspen.albedo.avif +0 -0
  11. package/assets/bark/aspen.normal.avif +0 -0
  12. package/assets/bark/beech.albedo.avif +0 -0
  13. package/assets/bark/beech.normal.avif +0 -0
  14. package/assets/bark/birch.albedo.avif +0 -0
  15. package/assets/bark/birch.normal.avif +0 -0
  16. package/assets/bark/birchFoot.albedo.avif +0 -0
  17. package/assets/bark/birchFoot.normal.avif +0 -0
  18. package/assets/bark/corsicanPine.albedo.avif +0 -0
  19. package/assets/bark/corsicanPine.normal.avif +0 -0
  20. package/assets/bark/cypress.albedo.avif +0 -0
  21. package/assets/bark/cypress.normal.avif +0 -0
  22. package/assets/bark/douglas.albedo.avif +0 -0
  23. package/assets/bark/douglas.normal.avif +0 -0
  24. package/assets/bark/eucalyptus.albedo.avif +0 -0
  25. package/assets/bark/eucalyptus.normal.avif +0 -0
  26. package/assets/bark/eucalyptusUpper.albedo.avif +0 -0
  27. package/assets/bark/eucalyptusUpper.normal.avif +0 -0
  28. package/assets/bark/fibrous.albedo.avif +0 -0
  29. package/assets/bark/fibrous.normal.avif +0 -0
  30. package/assets/bark/hemlock.albedo.avif +0 -0
  31. package/assets/bark/hemlock.normal.avif +0 -0
  32. package/assets/bark/hornbeam.albedo.avif +0 -0
  33. package/assets/bark/hornbeam.normal.avif +0 -0
  34. package/assets/bark/larch.albedo.avif +0 -0
  35. package/assets/bark/larch.normal.avif +0 -0
  36. package/assets/bark/lime.albedo.avif +0 -0
  37. package/assets/bark/lime.normal.avif +0 -0
  38. package/assets/bark/liveOak.albedo.avif +0 -0
  39. package/assets/bark/liveOak.normal.avif +0 -0
  40. package/assets/bark/maple.albedo.avif +0 -0
  41. package/assets/bark/maple.normal.avif +0 -0
  42. package/assets/bark/montereyPine.albedo.avif +0 -0
  43. package/assets/bark/montereyPine.normal.avif +0 -0
  44. package/assets/bark/norMaple.albedo.avif +0 -0
  45. package/assets/bark/norMaple.normal.avif +0 -0
  46. package/assets/bark/oak.albedo.avif +0 -0
  47. package/assets/bark/oak.normal.avif +0 -0
  48. package/assets/bark/palmLattice.albedo.avif +0 -0
  49. package/assets/bark/palmLattice.normal.avif +0 -0
  50. package/assets/bark/palmPineapple.albedo.avif +0 -0
  51. package/assets/bark/palmPineapple.normal.avif +0 -0
  52. package/assets/bark/palmRings.albedo.avif +0 -0
  53. package/assets/bark/palmRings.normal.avif +0 -0
  54. package/assets/bark/pine.albedo.avif +0 -0
  55. package/assets/bark/pine.normal.avif +0 -0
  56. package/assets/bark/pineFlakes.albedo.avif +0 -0
  57. package/assets/bark/pineFlakes.normal.avif +0 -0
  58. package/assets/bark/plane.albedo.avif +0 -0
  59. package/assets/bark/plane.normal.avif +0 -0
  60. package/assets/bark/poplar.albedo.avif +0 -0
  61. package/assets/bark/poplar.normal.avif +0 -0
  62. package/assets/bark/redAlder.albedo.avif +0 -0
  63. package/assets/bark/redAlder.normal.avif +0 -0
  64. package/assets/bark/redOak.albedo.avif +0 -0
  65. package/assets/bark/redOak.normal.avif +0 -0
  66. package/assets/bark/ridged.albedo.avif +0 -0
  67. package/assets/bark/ridged.normal.avif +0 -0
  68. package/assets/bark/sitkaSpruce.albedo.avif +0 -0
  69. package/assets/bark/sitkaSpruce.normal.avif +0 -0
  70. package/assets/bark/spruce.albedo.avif +0 -0
  71. package/assets/bark/spruce.normal.avif +0 -0
  72. package/assets/bark/stonePine.albedo.avif +0 -0
  73. package/assets/bark/stonePine.normal.avif +0 -0
  74. package/assets/bark/sycMaple.albedo.avif +0 -0
  75. package/assets/bark/sycMaple.normal.avif +0 -0
  76. package/assets/bark/torreyPine.albedo.avif +0 -0
  77. package/assets/bark/torreyPine.normal.avif +0 -0
  78. package/assets/bark/whitePine.albedo.avif +0 -0
  79. package/assets/bark/whitePine.normal.avif +0 -0
  80. package/assets/bark/whiteSpruce.albedo.avif +0 -0
  81. package/assets/bark/whiteSpruce.normal.avif +0 -0
  82. package/assets/bark/whiteWillow.albedo.avif +0 -0
  83. package/assets/bark/whiteWillow.normal.avif +0 -0
  84. package/assets/bark/willow.albedo.avif +0 -0
  85. package/assets/bark/willow.normal.avif +0 -0
  86. package/assets/leaves/alder.albedo.avif +0 -0
  87. package/assets/leaves/alder.normal.avif +0 -0
  88. package/assets/leaves/ash.albedo.avif +0 -0
  89. package/assets/leaves/ash.normal.avif +0 -0
  90. package/assets/leaves/aspen.albedo.avif +0 -0
  91. package/assets/leaves/aspen.normal.avif +0 -0
  92. package/assets/leaves/beech.albedo.avif +0 -0
  93. package/assets/leaves/beech.normal.avif +0 -0
  94. package/assets/leaves/birch.albedo.avif +0 -0
  95. package/assets/leaves/birch.normal.avif +0 -0
  96. package/assets/leaves/blackthorn.albedo.avif +0 -0
  97. package/assets/leaves/blackthorn.normal.avif +0 -0
  98. package/assets/leaves/blade.albedo.avif +0 -0
  99. package/assets/leaves/blade.normal.avif +0 -0
  100. package/assets/leaves/broomSprig.albedo.avif +0 -0
  101. package/assets/leaves/broomSprig.normal.avif +0 -0
  102. package/assets/leaves/corsicanShoot.albedo.avif +0 -0
  103. package/assets/leaves/corsicanShoot.normal.avif +0 -0
  104. package/assets/leaves/cypress.albedo.avif +0 -0
  105. package/assets/leaves/cypress.normal.avif +0 -0
  106. package/assets/leaves/cypressPad.albedo.avif +0 -0
  107. package/assets/leaves/cypressPad.normal.avif +0 -0
  108. package/assets/leaves/deadFronds.albedo.avif +0 -0
  109. package/assets/leaves/deadFronds.normal.avif +0 -0
  110. package/assets/leaves/deltoid.albedo.avif +0 -0
  111. package/assets/leaves/deltoid.normal.avif +0 -0
  112. package/assets/leaves/douglasShoot.albedo.avif +0 -0
  113. package/assets/leaves/douglasShoot.normal.avif +0 -0
  114. package/assets/leaves/elderSprig.albedo.avif +0 -0
  115. package/assets/leaves/elderSprig.normal.avif +0 -0
  116. package/assets/leaves/elliptic.albedo.avif +0 -0
  117. package/assets/leaves/elliptic.normal.avif +0 -0
  118. package/assets/leaves/eucalyptus.albedo.avif +0 -0
  119. package/assets/leaves/eucalyptus.normal.avif +0 -0
  120. package/assets/leaves/fan.albedo.avif +0 -0
  121. package/assets/leaves/fan.normal.avif +0 -0
  122. package/assets/leaves/fanB.albedo.avif +0 -0
  123. package/assets/leaves/fanB.normal.avif +0 -0
  124. package/assets/leaves/fir.albedo.avif +0 -0
  125. package/assets/leaves/fir.normal.avif +0 -0
  126. package/assets/leaves/frond.albedo.avif +0 -0
  127. package/assets/leaves/frond.normal.avif +0 -0
  128. package/assets/leaves/gorse.albedo.avif +0 -0
  129. package/assets/leaves/gorse.normal.avif +0 -0
  130. package/assets/leaves/hawthorn.albedo.avif +0 -0
  131. package/assets/leaves/hawthorn.normal.avif +0 -0
  132. package/assets/leaves/hemlockShoot.albedo.avif +0 -0
  133. package/assets/leaves/hemlockShoot.normal.avif +0 -0
  134. package/assets/leaves/hornbeam.albedo.avif +0 -0
  135. package/assets/leaves/hornbeam.normal.avif +0 -0
  136. package/assets/leaves/lance.albedo.avif +0 -0
  137. package/assets/leaves/lance.normal.avif +0 -0
  138. package/assets/leaves/larchShoot.albedo.avif +0 -0
  139. package/assets/leaves/larchShoot.normal.avif +0 -0
  140. package/assets/leaves/lime.albedo.avif +0 -0
  141. package/assets/leaves/lime.normal.avif +0 -0
  142. package/assets/leaves/liveOak.albedo.avif +0 -0
  143. package/assets/leaves/liveOak.normal.avif +0 -0
  144. package/assets/leaves/londonPlane.albedo.avif +0 -0
  145. package/assets/leaves/londonPlane.normal.avif +0 -0
  146. package/assets/leaves/maple.albedo.avif +0 -0
  147. package/assets/leaves/maple.normal.avif +0 -0
  148. package/assets/leaves/norMaple.albedo.avif +0 -0
  149. package/assets/leaves/norMaple.normal.avif +0 -0
  150. package/assets/leaves/oak.albedo.avif +0 -0
  151. package/assets/leaves/oak.normal.avif +0 -0
  152. package/assets/leaves/paintFan.albedo.avif +0 -0
  153. package/assets/leaves/paintFan.normal.avif +0 -0
  154. package/assets/leaves/paintFrond.albedo.avif +0 -0
  155. package/assets/leaves/paintFrond.normal.avif +0 -0
  156. package/assets/leaves/pine.albedo.avif +0 -0
  157. package/assets/leaves/pine.normal.avif +0 -0
  158. package/assets/leaves/pineClumpDark.albedo.avif +0 -0
  159. package/assets/leaves/pineClumpDark.normal.avif +0 -0
  160. package/assets/leaves/pineClumpLight.albedo.avif +0 -0
  161. package/assets/leaves/pineClumpLight.normal.avif +0 -0
  162. package/assets/leaves/poplar.albedo.avif +0 -0
  163. package/assets/leaves/poplar.normal.avif +0 -0
  164. package/assets/leaves/queenFrond.albedo.avif +0 -0
  165. package/assets/leaves/queenFrond.normal.avif +0 -0
  166. package/assets/leaves/redAlder.albedo.avif +0 -0
  167. package/assets/leaves/redAlder.normal.avif +0 -0
  168. package/assets/leaves/redOak.albedo.avif +0 -0
  169. package/assets/leaves/redOak.normal.avif +0 -0
  170. package/assets/leaves/round.albedo.avif +0 -0
  171. package/assets/leaves/round.normal.avif +0 -0
  172. package/assets/leaves/scale.albedo.avif +0 -0
  173. package/assets/leaves/scale.normal.avif +0 -0
  174. package/assets/leaves/scotsPineClump.albedo.avif +0 -0
  175. package/assets/leaves/scotsPineClump.normal.avif +0 -0
  176. package/assets/leaves/seaBuckthornSprig.albedo.avif +0 -0
  177. package/assets/leaves/seaBuckthornSprig.normal.avif +0 -0
  178. package/assets/leaves/serrate.albedo.avif +0 -0
  179. package/assets/leaves/serrate.normal.avif +0 -0
  180. package/assets/leaves/sitkaShoot.albedo.avif +0 -0
  181. package/assets/leaves/sitkaShoot.normal.avif +0 -0
  182. package/assets/leaves/stonePineCanopy.albedo.avif +0 -0
  183. package/assets/leaves/stonePineCanopy.normal.avif +0 -0
  184. package/assets/leaves/stonePineCushion.albedo.avif +0 -0
  185. package/assets/leaves/stonePineCushion.normal.avif +0 -0
  186. package/assets/leaves/sycamore.albedo.avif +0 -0
  187. package/assets/leaves/sycamore.normal.avif +0 -0
  188. package/assets/leaves/torreyPine.albedo.avif +0 -0
  189. package/assets/leaves/torreyPine.normal.avif +0 -0
  190. package/assets/leaves/whitePine.albedo.avif +0 -0
  191. package/assets/leaves/whitePine.normal.avif +0 -0
  192. package/assets/leaves/whiteSpruceShoot.albedo.avif +0 -0
  193. package/assets/leaves/whiteSpruceShoot.normal.avif +0 -0
  194. package/assets/leaves/whiteWillow.albedo.avif +0 -0
  195. package/assets/leaves/whiteWillow.normal.avif +0 -0
  196. package/assets/leaves/willow.albedo.avif +0 -0
  197. package/assets/leaves/willow.normal.avif +0 -0
  198. package/assets/marks/marks.json +894 -0
  199. package/assets/marks/painterly.avif +0 -0
  200. package/assets/marks/sheets.avif +0 -0
  201. package/assets/scans.json +6066 -0
  202. package/lib/age.d.ts +36 -0
  203. package/lib/age.d.ts.map +1 -0
  204. package/lib/age.js +170 -0
  205. package/lib/age.js.map +1 -0
  206. package/lib/atmosphere.d.ts +64 -0
  207. package/lib/atmosphere.d.ts.map +1 -0
  208. package/lib/atmosphere.js +260 -0
  209. package/lib/atmosphere.js.map +1 -0
  210. package/lib/dabs.d.ts +4 -0
  211. package/lib/dabs.d.ts.map +1 -0
  212. package/lib/dabs.js +77 -0
  213. package/lib/dabs.js.map +1 -0
  214. package/lib/engine.d.ts +211 -0
  215. package/lib/engine.d.ts.map +1 -0
  216. package/lib/engine.js +3808 -0
  217. package/lib/engine.js.map +1 -0
  218. package/lib/genetics.d.ts +129 -0
  219. package/lib/genetics.d.ts.map +1 -0
  220. package/lib/genetics.js +721 -0
  221. package/lib/genetics.js.map +1 -0
  222. package/lib/geometry.d.ts +237 -0
  223. package/lib/geometry.d.ts.map +1 -0
  224. package/lib/geometry.js +1944 -0
  225. package/lib/geometry.js.map +1 -0
  226. package/lib/grow.d.ts +83 -0
  227. package/lib/grow.d.ts.map +1 -0
  228. package/lib/grow.js +3851 -0
  229. package/lib/grow.js.map +1 -0
  230. package/lib/hiz.d.ts +74 -0
  231. package/lib/hiz.d.ts.map +1 -0
  232. package/lib/hiz.js +161 -0
  233. package/lib/hiz.js.map +1 -0
  234. package/lib/impostor.d.ts +106 -0
  235. package/lib/impostor.d.ts.map +1 -0
  236. package/lib/impostor.js +450 -0
  237. package/lib/impostor.js.map +1 -0
  238. package/lib/index.d.ts +17 -0
  239. package/lib/index.d.ts.map +1 -0
  240. package/lib/index.js +16 -0
  241. package/lib/index.js.map +1 -0
  242. package/lib/leaves.d.ts +30 -0
  243. package/lib/leaves.d.ts.map +1 -0
  244. package/lib/leaves.js +829 -0
  245. package/lib/leaves.js.map +1 -0
  246. package/lib/light.d.ts +110 -0
  247. package/lib/light.d.ts.map +1 -0
  248. package/lib/light.js +430 -0
  249. package/lib/light.js.map +1 -0
  250. package/lib/lobes.d.ts +25 -0
  251. package/lib/lobes.d.ts.map +1 -0
  252. package/lib/lobes.js +151 -0
  253. package/lib/lobes.js.map +1 -0
  254. package/lib/marks.d.ts +63 -0
  255. package/lib/marks.d.ts.map +1 -0
  256. package/lib/marks.js +553 -0
  257. package/lib/marks.js.map +1 -0
  258. package/lib/mips.d.ts +42 -0
  259. package/lib/mips.d.ts.map +1 -0
  260. package/lib/mips.js +220 -0
  261. package/lib/mips.js.map +1 -0
  262. package/lib/paintedMarks.d.ts +21 -0
  263. package/lib/paintedMarks.d.ts.map +1 -0
  264. package/lib/paintedMarks.js +53 -0
  265. package/lib/paintedMarks.js.map +1 -0
  266. package/lib/palm.d.ts +162 -0
  267. package/lib/palm.d.ts.map +1 -0
  268. package/lib/palm.js +779 -0
  269. package/lib/palm.js.map +1 -0
  270. package/lib/palmAtlas.d.ts +79 -0
  271. package/lib/palmAtlas.d.ts.map +1 -0
  272. package/lib/palmAtlas.js +335 -0
  273. package/lib/palmAtlas.js.map +1 -0
  274. package/lib/palmGeometry.d.ts +41 -0
  275. package/lib/palmGeometry.d.ts.map +1 -0
  276. package/lib/palmGeometry.js +309 -0
  277. package/lib/palmGeometry.js.map +1 -0
  278. package/lib/phenology.d.ts +21 -0
  279. package/lib/phenology.d.ts.map +1 -0
  280. package/lib/phenology.js +164 -0
  281. package/lib/phenology.js.map +1 -0
  282. package/lib/random.d.ts +34 -0
  283. package/lib/random.d.ts.map +1 -0
  284. package/lib/random.js +92 -0
  285. package/lib/random.js.map +1 -0
  286. package/lib/scans.d.ts +232 -0
  287. package/lib/scans.d.ts.map +1 -0
  288. package/lib/scans.js +391 -0
  289. package/lib/scans.js.map +1 -0
  290. package/lib/scatter.d.ts +70 -0
  291. package/lib/scatter.d.ts.map +1 -0
  292. package/lib/scatter.js +186 -0
  293. package/lib/scatter.js.map +1 -0
  294. package/lib/species.d.ts +369 -0
  295. package/lib/species.d.ts.map +1 -0
  296. package/lib/species.js +2817 -0
  297. package/lib/species.js.map +1 -0
  298. package/lib/sprays.d.ts +112 -0
  299. package/lib/sprays.d.ts.map +1 -0
  300. package/lib/sprays.js +1137 -0
  301. package/lib/sprays.js.map +1 -0
  302. package/lib/stand.d.ts +52 -0
  303. package/lib/stand.d.ts.map +1 -0
  304. package/lib/stand.js +279 -0
  305. package/lib/stand.js.map +1 -0
  306. package/lib/styles.d.ts +135 -0
  307. package/lib/styles.d.ts.map +1 -0
  308. package/lib/styles.js +79 -0
  309. package/lib/styles.js.map +1 -0
  310. package/lib/tree.d.ts +134 -0
  311. package/lib/tree.d.ts.map +1 -0
  312. package/lib/tree.js +57 -0
  313. package/lib/tree.js.map +1 -0
  314. package/lib/variants.d.ts +157 -0
  315. package/lib/variants.d.ts.map +1 -0
  316. package/lib/variants.js +532 -0
  317. package/lib/variants.js.map +1 -0
  318. package/lib/visibility.d.ts +105 -0
  319. package/lib/visibility.d.ts.map +1 -0
  320. package/lib/visibility.js +242 -0
  321. package/lib/visibility.js.map +1 -0
  322. package/package.json +62 -3
@@ -0,0 +1,1944 @@
1
+ // What is drawn of a grown tree, at each distance: its wood as tubes and its
2
+ // clumps of leaves as dabs, many and small close to, few and broad far off.
3
+ //
4
+ // Every variant's pieces at one distance go into one buffer, one after
5
+ // another, so one mesh draws them all: the graphics card draws each
6
+ // variant's range once for every tree of it that it found in view (see
7
+ // engine.ts). Positions are the variant's own, in metres from its foot; the
8
+ // shaders fit them to each tree.
9
+ //
10
+ // A dab's corners all carry the dab's centre: it is turned to face the eye
11
+ // in the shader, and lit as one thing, the way a brush lays a dab.
12
+ import { flareHeight } from "./grow.js";
13
+ import { palmStemInto } from "./palmGeometry.js";
14
+ import { hash01 } from "./variants.js";
15
+ // (Near, all the wood: every leaf grows from a twig, and a twig left out leaves its leaves in the air and the
16
+ // branch it grew on ending bare. A twig thinner than a pixel is shrunk away in the shader (engine.ts
17
+ // `keepThin`). Mid, the branches that are still a pixel or so across where a tree is handed to it, reaching
18
+ // up into the leaves; its twigs would be under a pixel there, and only cost.)
19
+ export const TIER_SHAPES = [
20
+ { dabsPerClump: 3, dabSize: 1.0, gather: 0, woodFrom: 0, sides: [16, 4], turn: 9, rings: [8, 3], twig: { sides: 2, rings: 3, turn: 20 }, round: true },
21
+ { dabsPerClump: 0, dabSize: 1, gather: 56, woodFrom: 0.1, sides: [7, 3], turn: 18, rings: [3, 1], twig: { sides: 3, rings: 1, turn: 28.8 }, round: false },
22
+ { dabsPerClump: 0, dabSize: 1, gather: 16, woodFrom: 9, sides: [3, 3], turn: 30, rings: [1, 1], twig: { sides: 3, rings: 1, turn: 48 }, round: false },
23
+ ];
24
+ export class Builder {
25
+ /**
26
+ * Each attribute's numbers so far, as doubles (rounded to floats only by `done`), in typed arrays that grow as
27
+ * they fill: the near wood lays some millions of numbers a course, and as arrays of numbers, each vertex an object
28
+ * of arrays, laying them was half its time. `filled[k]` is how many of `floats[k]` are laid.
29
+ */
30
+ floats = {};
31
+ filled = {};
32
+ index = [];
33
+ ranges = [];
34
+ vertices = 0;
35
+ /** Where the variant being built starts: its first index and vertex. */
36
+ start = { index: 0, vertex: 0 };
37
+ // (Not a parameter property: node runs this file's tests by stripping its types, which those are not.)
38
+ sizes;
39
+ /** The attributes by number (`slot`), for laying numbers without looking them up by name. */
40
+ names;
41
+ data;
42
+ at;
43
+ constructor(sizes) {
44
+ this.sizes = sizes;
45
+ this.names = Object.keys(sizes);
46
+ this.data = this.names.map((k) => new Float64Array(1024 * sizes[k]));
47
+ this.at = this.names.map(() => 0);
48
+ this.names.forEach((k, i) => {
49
+ Object.defineProperty(this.floats, k, { get: () => this.data[i], enumerable: true });
50
+ Object.defineProperty(this.filled, k, { get: () => this.at[i], enumerable: true });
51
+ });
52
+ }
53
+ /** An attribute's number, for `putAt`. */
54
+ slot(k) {
55
+ return this.names.indexOf(k);
56
+ }
57
+ /** Room in an attribute's numbers for `more` of them. */
58
+ room(i, more) {
59
+ let a = this.data[i];
60
+ const need = this.at[i] + more;
61
+ if (need > a.length) {
62
+ const b = new Float64Array(Math.max(need, 2 * a.length));
63
+ b.set(a.subarray(0, this.at[i]));
64
+ this.data[i] = a = b;
65
+ }
66
+ return a;
67
+ }
68
+ begin() {
69
+ this.start = { index: this.index.length, vertex: this.vertices };
70
+ }
71
+ end() {
72
+ this.ranges.push({ firstIndex: this.start.index, indexCount: this.index.length - this.start.index, baseVertex: this.start.vertex });
73
+ }
74
+ /**
75
+ * End a variant whose triangles were put in bands (`bands[k]`, indices numbered from its first vertex) rather
76
+ * than in `index`: laid out band by band, and its vertices renumbered in the order they are first used, so a
77
+ * run of its first bands uses only the vertices at the start of its run.
78
+ */
79
+ endBands(bands) {
80
+ const from = this.start.vertex;
81
+ const count = this.vertices - from;
82
+ const order = new Int32Array(count).fill(-1);
83
+ let next = 0;
84
+ const cumulative = [];
85
+ const index = this.index;
86
+ const first = index.length;
87
+ for (const band of bands) {
88
+ for (let j = 0; j < band.length; j++) {
89
+ const k = band[j];
90
+ if (order[k] < 0)
91
+ order[k] = next++;
92
+ index.push(order[k]);
93
+ }
94
+ cumulative.push({ indexCount: index.length - first, vertexCount: next });
95
+ }
96
+ // (Any vertex no triangle uses goes last.)
97
+ for (let k = 0; k < count; k++)
98
+ if (order[k] < 0)
99
+ order[k] = next++;
100
+ this.names.forEach((_, i) => {
101
+ const size = this.sizes[this.names[i]];
102
+ const a = this.data[i];
103
+ const old = a.slice(from * size, (from + count) * size);
104
+ for (let k = 0; k < count; k++) {
105
+ const to = (from + order[k]) * size;
106
+ const at = k * size;
107
+ for (let j = 0; j < size; j++)
108
+ a[to + j] = old[at + j];
109
+ }
110
+ });
111
+ this.ranges.push({ firstIndex: this.start.index, indexCount: index.length - first, baseVertex: from, bands: cumulative });
112
+ }
113
+ /** A vertex, numbered from the variant's first. */
114
+ vertex(values) {
115
+ for (const k in values) {
116
+ const i = this.names.indexOf(k);
117
+ const from = values[k];
118
+ const to = this.room(i, from.length);
119
+ let n = this.at[i];
120
+ for (let j = 0; j < from.length; j++)
121
+ to[n++] = from[j];
122
+ this.at[i] = n;
123
+ }
124
+ return this.vertices++ - this.start.vertex;
125
+ }
126
+ /** One attribute's numbers (by its `slot`) for the vertex being laid (then `next`): as `vertex` lays them, without an object of arrays. */
127
+ putAt(i, x, y, z, w) {
128
+ const to = this.room(i, 4);
129
+ let n = this.at[i];
130
+ to[n++] = x;
131
+ to[n++] = y;
132
+ to[n++] = z;
133
+ if (w !== undefined)
134
+ to[n++] = w;
135
+ this.at[i] = n;
136
+ }
137
+ /** The vertex whose attributes were `putAt`, numbered from the variant's first. */
138
+ next() {
139
+ return this.vertices++ - this.start.vertex;
140
+ }
141
+ done() {
142
+ const attributes = {};
143
+ this.names.forEach((k, i) => (attributes[k] = { array: Float32Array.from(this.data[i].subarray(0, this.at[i])), size: this.sizes[k] }));
144
+ return { attributes, index: new Uint32Array(this.index), ranges: this.ranges };
145
+ }
146
+ }
147
+ const CORNERS = [
148
+ [-1, -1],
149
+ [1, -1],
150
+ [1, 1],
151
+ [-1, 1],
152
+ ];
153
+ /**
154
+ * The dabs of every variant at one distance. Each dab: `position` its centre; `aDab` its corner (x, y),
155
+ * its size (m, across half of it) and a number of its own; `aNormal` its clump's outward normal and how
156
+ * deep in the crown it is; `aOffset` which way it lies from its clump's centre and what it is (0 leaves,
157
+ * 1 a stroke for the trunk, whose half-width is in `aNormal.x`); `aLimb` the foot of the limb it is on, and
158
+ * its variant. A variant `skip` says is left without leaves (its range is empty).
159
+ */
160
+ export function dabPieces(trees, shape, part = "leaves", skip) {
161
+ const b = new Builder({ position: 3, aDab: 4, aNormal: 4, aOffset: 4, aLimb: 4 });
162
+ const [P, DAB, NORMAL, OFFSET, LIMB] = ["position", "aDab", "aNormal", "aOffset", "aLimb"].map((k) => b.slot(k));
163
+ const quad = (c, size, own, n, depth, off, kind, limb, variant) => {
164
+ let f = -1;
165
+ for (const [cx, cy] of CORNERS) {
166
+ b.putAt(P, c[0], c[1], c[2]);
167
+ b.putAt(DAB, cx, cy, size, own);
168
+ b.putAt(NORMAL, n[0], n[1], n[2], depth);
169
+ b.putAt(OFFSET, off[0], off[1], off[2], kind);
170
+ b.putAt(LIMB, limb[0], limb[1], limb[2], variant);
171
+ const k = b.next();
172
+ if (f < 0)
173
+ f = k;
174
+ }
175
+ b.index.push(f, f + 1, f + 2, f, f + 2, f + 3);
176
+ };
177
+ trees.forEach((tree, v) => {
178
+ b.begin();
179
+ const { clumps: cl, skeleton: sk } = tree;
180
+ const limbOf = windLimbs(sk).foot;
181
+ if (part === "stroke") {
182
+ // (The trunk, far off: one upright stroke from the ground into the crown.)
183
+ if (shape.woodFrom >= 1) {
184
+ // (From its lowest leaves: a crown kept to the top of its size's, a stone pine's or one its stand has
185
+ // lifted, has its trunk bare up to it.)
186
+ let low = tree.size.height;
187
+ for (let c = 0; c < cl.count; c++)
188
+ low = Math.min(low, cl.y[c] - cl.radius[c]);
189
+ const from = Math.max(tree.size.crownBase, low < tree.size.height ? low : tree.size.crownBase);
190
+ const top = from + (tree.size.height - from) * 0.25;
191
+ quad([0, top / 2, 0], top / 2, 0.5, [trunkHalfWidth(tree), 0, 0], 0, [0, 0, 0], 1, [0, -1, 0], v);
192
+ }
193
+ }
194
+ else if (skip?.[v]) {
195
+ // (Its leaves are drawn otherwise: a conifer's near boughs as sheets, `sheetPieces`.)
196
+ }
197
+ else if (shape.dabsPerClump > 0) {
198
+ const twigs = clumpTwigs(tree);
199
+ for (let c = 0; c < cl.count; c++) {
200
+ const centre = [cl.x[c], cl.y[c], cl.z[c]];
201
+ const n = [cl.nx[c], cl.ny[c], cl.nz[c]];
202
+ const r = cl.radius[c];
203
+ // (A clump deep in the crown is mostly hidden by those outside it: one dab is all of it that shows.)
204
+ // (And a finer clump than its kind's, fewer: as many dabs over the crown as its kind's clumps would lay.)
205
+ const dabs = cl.depth[c] > 0.65 ? 1 : dabsOf(shape.dabsPerClump, tree.clumpShare ?? 1, hash01(c * 31, v * 977 + 5));
206
+ const laid = [];
207
+ for (let d = 0; d < dabs; d++) {
208
+ const own = hash01(c * 31 + d, v * 977 + 3);
209
+ let off = [0, 0, 0];
210
+ if (dabs > 1) {
211
+ // (Spread over the clump, more on its outer side: the leaves face the light.)
212
+ const u = hash01(c * 31 + d, 11) * 2 - 1;
213
+ const a = hash01(c * 31 + d, 12) * Math.PI * 2;
214
+ const s = Math.sqrt(1 - u * u);
215
+ off = [s * Math.cos(a) + n[0] * 0.6, u + n[1] * 0.6, s * Math.sin(a) + n[2] * 0.6];
216
+ const l = Math.hypot(off[0], off[1], off[2]) || 1;
217
+ off = off.map((q) => q / l);
218
+ }
219
+ const reach = dabs > 1 ? r * 0.5 : 0;
220
+ const size = dabs >= shape.dabsPerClump ? shape.dabSize : dabs > 1 ? DAB_TWO : 1.45;
221
+ const at = [centre[0] + off[0] * reach, centre[1] + off[1] * reach, centre[2] + off[2] * reach];
222
+ laid.push([...at, r * size * (0.85 + own * 0.3)]);
223
+ quad(at, laid[d][3], own, n, cl.depth[c], off, 0, limbOf(cl.node[c]), v);
224
+ }
225
+ // (And one more over each of its twigs' ends that none of those covers, half way in to its centre:
226
+ // no twig of a clump pokes out of it bare.)
227
+ twigs[c].forEach((t, j) => {
228
+ if (laid.some((q) => Math.hypot(sk.x[t] - q[0], sk.y[t] - q[1], sk.z[t] - q[2]) < q[3]))
229
+ return;
230
+ const own = hash01(c * 31 + dabs + j, v * 977 + 3);
231
+ const at = [(sk.x[t] + centre[0]) / 2, (sk.y[t] + centre[1]) / 2, (sk.z[t] + centre[2]) / 2];
232
+ const off = norm([sk.x[t] - centre[0], sk.y[t] - centre[1], sk.z[t] - centre[2]]);
233
+ quad(at, r * shape.dabSize * (0.85 + own * 0.3), own, n, cl.depth[c], off, 0, limbOf(t), v);
234
+ });
235
+ }
236
+ }
237
+ else {
238
+ for (const g of gatherClumps(tree, shape.gather)) {
239
+ quad(g.centre, g.size * shape.dabSize, g.own, g.normal, g.depth, [0, 0, 0], 0, g.limb, v);
240
+ }
241
+ }
242
+ b.end();
243
+ });
244
+ return b.done();
245
+ }
246
+ /** Two dabs to a clump: each this big beside it, between three's (`TierShape.dabSize`) and one's (1.45). */
247
+ const DAB_TWO = 1.2;
248
+ /**
249
+ * How many dabs a clump takes, of `most`, its clump this share of its kind's size (`GrownTree.clumpShare`):
250
+ * as many as cover the same share of the crown, `most` times its area, at least one; a fraction made up by
251
+ * the clump's own number `u`.
252
+ */
253
+ export function dabsOf(most, share, u) {
254
+ const want = Math.max(1, most * Math.min(1, share) ** 2);
255
+ const n = Math.floor(want);
256
+ return Math.min(most, n + (u < want - n ? 1 : 0));
257
+ }
258
+ function trunkHalfWidth(tree) {
259
+ return tree.size.trunkRadius * 1.15;
260
+ }
261
+ /** A crown's clumps gathered into a few broad ones: where each lies, how big it is, which way it faces, and its limb's foot. */
262
+ export function gatherClumps(tree, count) {
263
+ const cl = tree.clumps;
264
+ const n = cl.count;
265
+ if (n === 0)
266
+ return [];
267
+ const wl = windLimbs(tree.skeleton);
268
+ const k = Math.min(count, n);
269
+ // (k-means over the clumps' centres, from clumps at even steps through them.)
270
+ const cx = [];
271
+ const cy = [];
272
+ const cz = [];
273
+ for (let g = 0; g < k; g++) {
274
+ const i = Math.floor(((g + 0.5) * n) / k);
275
+ cx.push(cl.x[i]);
276
+ cy.push(cl.y[i]);
277
+ cz.push(cl.z[i]);
278
+ }
279
+ const of = new Int32Array(n);
280
+ for (let round = 0; round < 10; round++) {
281
+ for (let i = 0; i < n; i++) {
282
+ let best = 0;
283
+ let bestD = Infinity;
284
+ for (let g = 0; g < k; g++) {
285
+ const d = (cl.x[i] - cx[g]) ** 2 + (cl.y[i] - cy[g]) ** 2 + (cl.z[i] - cz[g]) ** 2;
286
+ if (d < bestD) {
287
+ bestD = d;
288
+ best = g;
289
+ }
290
+ }
291
+ of[i] = best;
292
+ }
293
+ const sum = Array.from({ length: k }, () => [0, 0, 0, 0]);
294
+ for (let i = 0; i < n; i++) {
295
+ const s = sum[of[i]];
296
+ const w = cl.radius[i] ** 2;
297
+ s[0] += cl.x[i] * w;
298
+ s[1] += cl.y[i] * w;
299
+ s[2] += cl.z[i] * w;
300
+ s[3] += w;
301
+ }
302
+ for (let g = 0; g < k; g++) {
303
+ if (sum[g][3] > 0) {
304
+ cx[g] = sum[g][0] / sum[g][3];
305
+ cy[g] = sum[g][1] / sum[g][3];
306
+ cz[g] = sum[g][2] / sum[g][3];
307
+ }
308
+ }
309
+ }
310
+ const out = [];
311
+ for (let g = 0; g < k; g++) {
312
+ let reach = 0;
313
+ let area = 0;
314
+ const nn = [0, 0, 0];
315
+ let depth = 0;
316
+ let m = 0;
317
+ let bestI = -1;
318
+ let bestD = Infinity;
319
+ for (let i = 0; i < n; i++) {
320
+ if (of[i] !== g)
321
+ continue;
322
+ const d2 = (cl.x[i] - cx[g]) ** 2 + (cl.y[i] - cy[g]) ** 2 + (cl.z[i] - cz[g]) ** 2;
323
+ if (d2 < bestD) {
324
+ bestD = d2;
325
+ bestI = i;
326
+ }
327
+ const d = Math.sqrt(d2) + cl.radius[i];
328
+ reach = Math.max(reach, d);
329
+ area += cl.radius[i] ** 2;
330
+ nn[0] += cl.nx[i];
331
+ nn[1] += cl.ny[i];
332
+ nn[2] += cl.nz[i];
333
+ depth += cl.depth[i];
334
+ m++;
335
+ }
336
+ if (m === 0)
337
+ continue;
338
+ const l = Math.hypot(nn[0], nn[1], nn[2]) || 1;
339
+ // (Big enough to cover what it gathers, seen from any side, short of its farthest edge: a group of
340
+ // clumps is not a ball of them.)
341
+ // (And never past it: a dab reaching out of the crown shows, as a tree passes from tier to tier and each
342
+ // draws in the other's pixels, as specks of leaves floating round its top.)
343
+ out.push({ centre: [cx[g], cy[g], cz[g]], size: Math.min(reach, Math.max(Math.sqrt(area) * 1.1, reach * 0.8)), normal: nn.map((q) => q / l), depth: depth / m, own: hash01(g, 41), limb: wl.foot(cl.node[bestI]) });
344
+ }
345
+ return out;
346
+ }
347
+ /** A sample of a drawn centre line, in a line's array: where it is (3), which way the wood runs (3), its radius, how fast that changes along it (per m), and how far along the wood from the ground it is. */
348
+ export const LINE_STRIDE = 9;
349
+ const DEG = Math.PI / 180;
350
+ /** Wood at least this thick (m) is thick: it turns by a tier's `turn` between rings, and thinner wood by `THIN_TURN` times that. */
351
+ const THICK = 0.035;
352
+ const THIN_TURN = 1.6;
353
+ /** Wood thinner than this (m) is a twig, with a tier's twig's sides and rings. */
354
+ export const TWIG = 0.02;
355
+ /** A twig's ribbon's half width, in its radii: as wide as the four-sided tube it was, on average over the ways that was turned (2 sqrt(2) / pi). */
356
+ export const RIBBON_WIDE = (2 * Math.SQRT2) / Math.PI;
357
+ /**
358
+ * The near tier's wood in bands by how thick it is (m, as grown): the trunk and wood at least the first, then
359
+ * wood thinner than each. Each variant's triangles are laid out band by band, thickest first, and its
360
+ * vertices in the order they are first used, so drawing a variant's first few bands draws only their
361
+ * vertices: the engine draws, for each tree, the bands that are a pixel's fraction or more across where it
362
+ * stands (engine.ts `WOOD_DEPTHS`); wood thinner than that the shader would shrink to nothing anyway.
363
+ */
364
+ export const WOOD_BANDS = [0.016, 0.006];
365
+ /** How far a limb's tube, where it leaves its parent's, is turned towards the way its parent runs: it leaves in a curve, not at an angle. */
366
+ const LEAVE = 0.35;
367
+ /**
368
+ * A fork: a limb nearly as thick as its parent there (from the first share of its radius to the second) is
369
+ * the parent dividing, not a limb put out of its side. Its tube starts back inside the parent's, up to a
370
+ * parent's radius back, running the parent's way, and bends out of it.
371
+ */
372
+ const FORK = [0.35, 0.85];
373
+ /** A limb's collar: how much thicker it is where it leaves its parent (at most), in how many of its radii past its parent's surface the swelling falls by e (a trumpet's flare, not a bulb), and the thinnest that has one (m). */
374
+ const COLLAR = 0.5;
375
+ const COLLAR_FALL = 0.9;
376
+ const COLLAR_FROM = 0.025;
377
+ /** A stem's buttresses: how much they swell it at the ground, over how much of its flare's height they ease away, and how far the foot goes on under the ground (m, and its radii). */
378
+ const BUTTRESS = 0.75;
379
+ const BUTTRESS_RISE = 0.55;
380
+ /** How wide a buttress is round the stem, in its share of the spacing between them; more sides go round a stem's foot to draw them. */
381
+ const BUTTRESS_WIDTH = 0.22;
382
+ const BUTTRESS_SIDES = 16;
383
+ const UNDERGROUND = 0.25;
384
+ const UNDERGROUND_RADII = 0.75;
385
+ /** A cap closing a tube's end: a ring this far round from its side towards its tip (rad), on wood with at least `CAP_RING_SIDES` sides. */
386
+ const CAP_RING = 55 * DEG;
387
+ const CAP_RING_SIDES = 6;
388
+ /** Each grown tree's wood lines, by tier: the near cards, the near wood and the clumps' shoots all ask for the same ones. */
389
+ const LINES = new WeakMap();
390
+ export function woodLines(tree, shape) {
391
+ let byShape = LINES.get(tree);
392
+ if (!byShape)
393
+ LINES.set(tree, (byShape = new Map()));
394
+ let lines = byShape.get(shape);
395
+ if (!lines)
396
+ byShape.set(shape, (lines = linesOf(tree, shape)));
397
+ return lines;
398
+ }
399
+ function linesOf(tree, shape) {
400
+ const sk = tree.skeleton;
401
+ const n = sk.count;
402
+ const R = sk.radius;
403
+ const trunk = R[0] || tree.size.trunkRadius;
404
+ const thinnest = trunk * shape.woodFrom;
405
+ const line = new Array(n).fill(null);
406
+ const main = mainChildren(sk);
407
+ const from = new Int32Array(n).fill(-1);
408
+ if (shape.woodFrom >= 1)
409
+ return { line, main, from };
410
+ const drawn = (i) => i >= 0 && sk.parent[i] >= 0 && R[i] >= thinnest;
411
+ const len = new Float64Array(n);
412
+ const dirIn = new Array(n);
413
+ for (let i = 0; i < n; i++) {
414
+ const p = sk.parent[i];
415
+ if (p < 0) {
416
+ const c = main[i];
417
+ dirIn[i] = c >= 0 ? norm([sk.x[c] - sk.x[i], sk.y[c] - sk.y[i], sk.z[c] - sk.z[i]]) : [0, 1, 0];
418
+ continue;
419
+ }
420
+ const d = [sk.x[i] - sk.x[p], sk.y[i] - sk.y[p], sk.z[i] - sk.z[p]];
421
+ len[i] = Math.hypot(d[0], d[1], d[2]);
422
+ dirIn[i] = len[i] > 1e-6 ? [d[0] / len[i], d[1] / len[i], d[2] / len[i]] : dirIn[p];
423
+ }
424
+ // (The way a tube runs through each node: halfway between the pieces either side, if it runs on.)
425
+ const tan = new Array(n);
426
+ for (let i = 0; i < n; i++) {
427
+ const c = main[i];
428
+ tan[i] = sk.parent[i] >= 0 && drawn(c) ? norm(add(dirIn[i], dirIn[c])) : dirIn[i];
429
+ }
430
+ // (How fast its radius falls along it there: between the pieces either side, flat where it swells.)
431
+ const slope = new Float64Array(n);
432
+ for (let i = 0; i < n; i++) {
433
+ const p = sk.parent[i];
434
+ const c = main[i];
435
+ if (p < 0) {
436
+ slope[i] = c >= 0 && len[c] > 1e-6 ? (R[c] - R[i]) / len[c] : 0;
437
+ continue;
438
+ }
439
+ const before = main[p] === i ? R[p] : R[i];
440
+ if (drawn(c)) {
441
+ const g = (R[c] - before) / Math.max(1e-6, len[i] + len[c]);
442
+ slope[i] = (before - R[i]) * (R[i] - R[c]) >= 0 ? g : 0;
443
+ }
444
+ else
445
+ slope[i] = (R[i] - before) / Math.max(1e-6, len[i]);
446
+ }
447
+ const hf = flareHeight(tree.size, tree.buttress ?? 0);
448
+ for (let i = 0; i < n; i++) {
449
+ if (!drawn(i))
450
+ continue;
451
+ const p = sk.parent[i];
452
+ const lateral = main[p] !== i;
453
+ const b = [sk.x[i], sk.y[i], sk.z[i]];
454
+ let a = [sk.x[p], sk.y[p], sk.z[p]];
455
+ let ta = tan[p];
456
+ let back = 0;
457
+ let fork = 0;
458
+ if (lateral) {
459
+ // (A fork's tube starts back inside its parent's, so the two part as one divides; a limb's at its parent's centre.)
460
+ const u = Math.min(1, Math.max(0, (R[i] / R[p] - FORK[0]) / (FORK[1] - FORK[0])));
461
+ fork = u * u * (3 - 2 * u);
462
+ back = fork * Math.min(R[p], sk.parent[p] >= 0 ? 0.8 * len[p] : R[p]);
463
+ // (Back along the parent's own line as drawn, so it starts on the parent's wood.)
464
+ let way = tan[p];
465
+ const pl = line[p];
466
+ if (back > 0 && pl) {
467
+ let left = back;
468
+ let o = pl.length - LINE_STRIDE;
469
+ while (o > 0) {
470
+ const q = o - LINE_STRIDE;
471
+ const piece = Math.hypot(pl[o] - pl[q], pl[o + 1] - pl[q + 1], pl[o + 2] - pl[q + 2]);
472
+ if (left <= piece || q === 0) {
473
+ const f = Math.min(1, left / Math.max(piece, 1e-9));
474
+ a = [pl[o] + (pl[q] - pl[o]) * f, pl[o + 1] + (pl[q + 1] - pl[o + 1]) * f, pl[o + 2] + (pl[q + 2] - pl[o + 2]) * f];
475
+ way = [pl[q + 3], pl[q + 4], pl[q + 5]];
476
+ from[i] = q / LINE_STRIDE;
477
+ break;
478
+ }
479
+ left -= piece;
480
+ o = q;
481
+ }
482
+ }
483
+ else if (back > 0)
484
+ a = sub(a, scale(tan[p], back));
485
+ const chord = norm(sub(b, a));
486
+ ta = norm(add(chord, scale(way, LEAVE + 1.5 * fork)));
487
+ if (dot(ta, chord) < 0.3)
488
+ ta = chord;
489
+ }
490
+ const L = Math.max(Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2]), 1e-6);
491
+ const tb = tan[i];
492
+ const r0 = lateral ? R[i] : R[p];
493
+ const g0 = lateral ? 0 : slope[p];
494
+ const r1 = R[i];
495
+ const g1 = slope[i];
496
+ const thick = Math.max(r0, r1) >= THICK;
497
+ const twig = Math.max(r0, r1) < TWIG;
498
+ // (How far it turns along its length, and where: rings go at even steps of its turning, so where it bends
499
+ // hardest, near a node it leaves at an angle, they come closest.)
500
+ const FINE = 24;
501
+ const turned = [0];
502
+ let before = ta;
503
+ for (let q = 1; q <= FINE; q++) {
504
+ const t = q / FINE;
505
+ const t2 = t * t;
506
+ const w0 = 6 * t2 - 6 * t;
507
+ const w1 = (3 * t2 - 4 * t + 1) * L;
508
+ const w2 = -6 * t2 + 6 * t;
509
+ const w3 = (3 * t2 - 2 * t) * L;
510
+ const way = norm([w0 * a[0] + w1 * ta[0] + w2 * b[0] + w3 * tb[0], w0 * a[1] + w1 * ta[1] + w2 * b[1] + w3 * tb[1], w0 * a[2] + w1 * ta[2] + w2 * b[2] + w3 * tb[2]]);
511
+ turned.push(turned[q - 1] + Math.acos(Math.min(1, Math.max(-1, dot(before, way)))));
512
+ before = way;
513
+ }
514
+ const turn = turned[FINE];
515
+ let k = Math.ceil(turn / ((thick ? shape.turn : twig ? shape.twig.turn : shape.turn * THIN_TURN) * DEG) - 1e-9);
516
+ k = Math.min(Math.max(k, 1), thick ? shape.rings[0] : twig ? Math.min(shape.rings[1], shape.twig.rings) : shape.rings[1]);
517
+ const ts = [0];
518
+ for (let q = 1, j = 1; q < k; q++) {
519
+ const want = (turn * q) / k;
520
+ while (j < FINE && turned[j] < want)
521
+ j++;
522
+ const f = (want - turned[j - 1]) / Math.max(1e-9, turned[j] - turned[j - 1]);
523
+ ts.push((j - 1 + Math.min(1, Math.max(0, f))) / FINE);
524
+ }
525
+ ts.push(1);
526
+ // (A stem's foot in finer rings, where its buttresses ease away.)
527
+ if (shape.round && sk.order[i] === 0 && sk.y[p] - sk.y[sk.limb[i]] < 2 * hf) {
528
+ const m = Math.min(6, Math.ceil(L / (0.3 * hf)));
529
+ for (let q = 1; q < m; q++)
530
+ ts.push(q / m);
531
+ }
532
+ // (A limb's collar: swollen inside its parent and where it leaves its surface, falling away fast out of
533
+ // it and then slowly, as a trumpet flares, to nothing by the next node.)
534
+ let collar = { from: 0, C: 0, fall: 1, gone: 1 };
535
+ if (lateral && shape.round && r1 >= COLLAR_FROM) {
536
+ const rp = R[p];
537
+ const c = dot(norm(sub(b, a)), tan[p]);
538
+ const sinA = Math.sqrt(Math.max(0, 1 - c * c));
539
+ const from = Math.min(back + rp / Math.max(sinA, 0.25) - 0.5 * r1, 0.6 * L);
540
+ // (None on a fork: its two tubes run on together inside the parent's, and one swollen would show round the other.)
541
+ const C = Math.min(COLLAR * (1 - fork), Math.max(0, (rp * 0.97) / r1 - 1));
542
+ const fall = COLLAR_FALL * r1;
543
+ if (C > 0.02 && L - from > 0.5 * fall) {
544
+ collar = { from, C, fall, gone: Math.exp(-(L - from) / fall) };
545
+ for (const f of [0, 0.7, 1.6, 3])
546
+ if (from + f * fall < L)
547
+ ts.push((from + f * fall) / L);
548
+ }
549
+ }
550
+ ts.sort((a, b) => a - b);
551
+ const kept = ts.filter((t, j) => t <= 1 && (j === 0 || t - ts[j - 1] > 0.02 || t === 1));
552
+ for (let j = kept.length - 2; j > 0; j--)
553
+ if (kept[j + 1] - kept[j] <= 0.02)
554
+ kept.splice(j, 1);
555
+ const out = new Float64Array(kept.length * LINE_STRIDE);
556
+ const lo = Math.min(r0, r1);
557
+ const hi = Math.max(r0, r1);
558
+ kept.forEach((t, q) => {
559
+ const t2 = t * t;
560
+ const t3 = t2 * t;
561
+ const h00 = 2 * t3 - 3 * t2 + 1;
562
+ const h10 = t3 - 2 * t2 + t;
563
+ const h01 = -2 * t3 + 3 * t2;
564
+ const h11 = t3 - t2;
565
+ const d00 = 6 * t2 - 6 * t;
566
+ const d10 = 3 * t2 - 4 * t + 1;
567
+ const d01 = -6 * t2 + 6 * t;
568
+ const d11 = 3 * t2 - 2 * t;
569
+ const o = q * LINE_STRIDE;
570
+ const dv = [0, 0, 0];
571
+ for (let x = 0; x < 3; x++) {
572
+ out[o + x] = h00 * a[x] + h10 * L * ta[x] + h01 * b[x] + h11 * L * tb[x];
573
+ dv[x] = d00 * a[x] + d10 * L * ta[x] + d01 * b[x] + d11 * L * tb[x];
574
+ }
575
+ const d = norm(dv);
576
+ out[o + 3] = d[0];
577
+ out[o + 4] = d[1];
578
+ out[o + 5] = d[2];
579
+ let r = h00 * r0 + h10 * L * g0 + h01 * r1 + h11 * L * g1;
580
+ let g = (d00 * r0 + d10 * L * g0 + d01 * r1 + d11 * L * g1) / L;
581
+ if (r < lo || r > hi) {
582
+ r = Math.min(hi, Math.max(lo, r));
583
+ g = 0;
584
+ }
585
+ const s = t * L;
586
+ if (collar.C > 0) {
587
+ const x = Math.exp(-Math.max(0, s - collar.from) / collar.fall);
588
+ const f = 1 + (collar.C * (x - collar.gone)) / (1 - collar.gone);
589
+ const df = s > collar.from ? (-collar.C * x) / collar.fall / (1 - collar.gone) : 0;
590
+ g = g * f + r * df;
591
+ r *= f;
592
+ }
593
+ out[o + 6] = r;
594
+ out[o + 7] = g;
595
+ out[o + 8] = sk.along[p] + s - back;
596
+ });
597
+ line[i] = out;
598
+ }
599
+ return { line, main, from };
600
+ }
601
+ /**
602
+ * The child each node's wood runs on into: the thickest, as it is the one going straightest on (a leader a
603
+ * little thinner than a limb leaving at an angle carries the stem on; the limb leaves it).
604
+ */
605
+ function mainChildren(sk) {
606
+ const n = sk.count;
607
+ const main = new Int32Array(n).fill(-1);
608
+ const score = new Float64Array(n);
609
+ for (let i = 0; i < n; i++) {
610
+ const p = sk.parent[i];
611
+ if (p < 0)
612
+ continue;
613
+ const g = sk.parent[p];
614
+ const into = g < 0 ? [0, 1, 0] : norm([sk.x[p] - sk.x[g], sk.y[p] - sk.y[g], sk.z[p] - sk.z[g]]);
615
+ const out = norm([sk.x[i] - sk.x[p], sk.y[i] - sk.y[p], sk.z[i] - sk.z[p]]);
616
+ score[i] = sk.radius[i] * (0.5 + 0.5 * dot(into, out));
617
+ if (main[p] < 0 || score[i] > score[main[p]])
618
+ main[p] = i;
619
+ }
620
+ return main;
621
+ }
622
+ /**
623
+ * How many sides a tier gives wood of radius `r` on a tree whose trunk's is `trunk`: a twig the least (most of
624
+ * the wood is twigs, and a twig is a few pixels across even close to), wood thicker than that more, the more
625
+ * of the trunk's radius it has, up to the most on the trunk itself.
626
+ */
627
+ function sidesFor(shape, r, trunk) {
628
+ const [most, least] = shape.sides;
629
+ // (A tube: a twig drawn as a ribbon is not one.)
630
+ if (r < TWIG)
631
+ return Math.max(3, Math.min(least, shape.twig.sides));
632
+ return Math.max(least, Math.min(most, Math.round(least + 1 + (most - least - 1) * Math.min(1, r / trunk) ** 0.75)));
633
+ }
634
+ /**
635
+ * A stem's buttresses: lobes round its foot where its roots run off, each its own size and a little off even
636
+ * spacing. Gives `swell` — how much they widen the stem at an angle round it (1 none) and a height above
637
+ * its foot, and how fast that changes round it (per radian) and up it (per m) — plus the `lobes` themselves so
638
+ * radiating surface roots follow the same ridges.
639
+ */
640
+ function buttresses(seed, hf, foot = 0) {
641
+ // (A buttressed species' foot has more of them, and they stand out further: a cedar's fluted foot.)
642
+ const count = 4 + Math.floor(hash01(seed, 17) * 3) + Math.round(3 * foot);
643
+ const step = (Math.PI * 2) / count;
644
+ const lobes = [];
645
+ for (let k = 0; k < count; k++) {
646
+ lobes.push({
647
+ angle: step * (k + (hash01(seed + k, 18) - 0.5) * 0.7),
648
+ size: 0.35 + 0.65 * hash01(seed + k, 19),
649
+ });
650
+ }
651
+ const sigma = step * BUTTRESS_WIDTH;
652
+ const rise = BUTTRESS_RISE * hf;
653
+ const swell = (angle, h) => {
654
+ let lobe = 0;
655
+ let dLobe = 0;
656
+ for (let k = 0; k < count; k++) {
657
+ let d = angle - lobes[k].angle;
658
+ d -= Math.round(d / (Math.PI * 2)) * Math.PI * 2;
659
+ const g = lobes[k].size * Math.exp(-0.5 * (d / sigma) ** 2);
660
+ lobe += g;
661
+ dLobe += (-g * d) / (sigma * sigma);
662
+ }
663
+ const A = BUTTRESS * (1 + 0.6 * foot) * Math.exp(-Math.max(0, h) / rise);
664
+ const dA = h > 0 ? -A / rise : 0;
665
+ const shape = Math.max(-0.04, lobe - 0.06);
666
+ return [1 + A * shape, A * dLobe, dA * shape];
667
+ };
668
+ return { swell, lobes };
669
+ }
670
+ /**
671
+ * How a stem's bark is laid over its root flare, from its centre lines (its first pieces, from its foot at
672
+ * `y0`), the flare's height `hf` and its buttresses (`swell`, as `buttresses`): `along(a, angle)`, how far along
673
+ * the wood a point is over its surface (not up its centre line: where the flare widens, and more on a
674
+ * buttress, the surface runs out as well as up, and bark laid up the centre line was drawn out along it in
675
+ * long smears); and `radius`, the stem's radius over its flare, which the bark is laid round there as round the
676
+ * stem above (the shader's `aWood.w`, as a share of the radius), so its furrows run on down the flare and
677
+ * spread out, as a real stem's do, and do not turn aside, crossing in chevrons where the bark's two sides
678
+ * meet. Above twice the flare's height it is the centre line's own.
679
+ */
680
+ export function flareBark(lines, y0, hf, swell) {
681
+ // (The centre line's samples up to twice the flare's height: how far along, how high, and the radius.)
682
+ const as = [];
683
+ const hs = [];
684
+ const rs = [];
685
+ let radius = 0;
686
+ outer: for (const l of lines) {
687
+ for (let o = 0; o < l.length; o += LINE_STRIDE) {
688
+ if (as.length > 0 && l[o + 8] <= as[as.length - 1])
689
+ continue;
690
+ const h = l[o + 1] - y0;
691
+ as.push(l[o + 8]);
692
+ hs.push(h);
693
+ rs.push(l[o + 6]);
694
+ if (h >= hf && radius === 0)
695
+ radius = l[o + 6];
696
+ if (h >= 2 * hf)
697
+ break outer;
698
+ }
699
+ }
700
+ if (radius === 0)
701
+ radius = rs[rs.length - 1] ?? 0;
702
+ const top = as[as.length - 1] ?? 0;
703
+ /** The centre line's height and radius at `a` along it (on at the first piece's slope under its first sample). */
704
+ const at = (a) => {
705
+ if (as.length < 2)
706
+ return [a, rs[0] ?? 0];
707
+ let k = 0;
708
+ while (k + 1 < as.length - 1 && as[k + 1] <= a)
709
+ k++;
710
+ const f = (a - as[k]) / Math.max(1e-9, as[k + 1] - as[k]);
711
+ return [hs[k] + (hs[k + 1] - hs[k]) * f, Math.max(0, rs[k] + (rs[k + 1] - rs[k]) * Math.max(0, f))];
712
+ };
713
+ /** The surface's distance out from the centre line at `a`, round at `angle`. */
714
+ const out = (a, angle) => {
715
+ const [h, r] = at(a);
716
+ return r * (swell ? swell(angle, h)[0] : 1);
717
+ };
718
+ const STEPS = 16;
719
+ const along = (a, angle) => {
720
+ if (as.length < 2 || a >= top)
721
+ return a;
722
+ // (The surface's length from here up to the top of the flare, over its length up the centre line.)
723
+ let extra = 0;
724
+ let prev = out(a, angle);
725
+ for (let k = 1; k <= STEPS; k++) {
726
+ const da = (top - a) / STEPS;
727
+ const next = out(a + da * k, angle);
728
+ extra += Math.hypot(da, next - prev) - da;
729
+ prev = next;
730
+ }
731
+ return a - extra;
732
+ };
733
+ return { along, radius };
734
+ }
735
+ /**
736
+ * The wood of every variant at one distance, as tubes along the curves `woodLines` draws: one tube from each
737
+ * stem's foot, and from where each limb leaves its parent, on through each node's thickest child, its rings
738
+ * as many-sided as the wood is thick there (a ring with fewer sides than the one before it is stitched to
739
+ * it), each tube's end closed in a rounded cap. Each vertex: `position` a point on the centre line;
740
+ * `aRadial` which way the surface lies from it (as long as the surface swells there: buttresses), and the
741
+ * radius there; `aNormal` which way the surface faces; `aLimb` the foot of the limb it is on (a stem's:
742
+ * below its foot), and its variant; `aWood` how far along the wood from the ground (m, over the surface of
743
+ * a stem's root flare: `flareBark`), its order, a number of its own (its tube's), and how much of its radius
744
+ * the bark is laid round (under 1 on a root flare: `flareBark`); `aFrame` the ring's
745
+ * own first direction out from the centre line (carried along the tube without twisting) and `aAxis` the
746
+ * way the wood runs there, so a picture of bark can be wrapped round it (engine.ts).
747
+ */
748
+ export function woodPieces(trees, shape) {
749
+ const b = new Builder({ position: 3, aRadial: 4, aNormal: 3, aLimb: 4, aWood: 4, aFrame: 3, aAxis: 3 });
750
+ const [P, RADIAL, NORMAL, LIMB, WOOD, FRAME, AXIS] = ["position", "aRadial", "aNormal", "aLimb", "aWood", "aFrame", "aAxis"].map((k) => b.slot(k));
751
+ trees.forEach((tree, v) => {
752
+ b.begin();
753
+ if (tree.palm) {
754
+ // (A palm's stem, as palm.ts shaped it, all of it in the first band; its fronds' rachises are its leaves'
755
+ // to draw: palmGeometry.ts.)
756
+ palmStemInto(b, tree, shape, v);
757
+ const all = b.index.splice(b.start.index);
758
+ b.endBands([all, ...WOOD_BANDS.map(() => [])]);
759
+ return;
760
+ }
761
+ const sk = tree.skeleton;
762
+ const W = woodLines(tree, shape);
763
+ // (Each band's triangles; a piece of tube goes in the band of the thicker of its two rings.)
764
+ const bands = [[], ...WOOD_BANDS.map(() => [])];
765
+ const bandOf = (r) => WOOD_BANDS.reduce((k, e) => (r < e ? k + 1 : k), 0);
766
+ const trunk = sk.radius[0] || tree.size.trunkRadius;
767
+ const hf = flareHeight(tree.size, tree.buttress ?? 0);
768
+ const ownOf = new Float64Array(sk.count).fill(0.5);
769
+ const kidCount = new Uint16Array(sk.count);
770
+ // (Children of a fair size: a stem dividing, not a stub or a twig leaving it.)
771
+ for (let i = 0; i < sk.count; i++)
772
+ if (sk.parent[i] >= 0 && sk.radius[i] >= 0.3 * sk.radius[sk.parent[i]])
773
+ kidCount[sk.parent[i]]++;
774
+ const stitch = (a, na, c, nc, r) => {
775
+ const into = bands[bandOf(r)];
776
+ let i = 0;
777
+ let j = 0;
778
+ while (i < na || j < nc) {
779
+ if (j >= nc || (i < na && (i + 1) / na <= (j + 1) / nc)) {
780
+ into.push(a + (i % na), c + (j % nc), a + ((i + 1) % na));
781
+ i++;
782
+ }
783
+ else {
784
+ into.push(a + (i % na), c + (j % nc), c + ((j + 1) % nc));
785
+ j++;
786
+ }
787
+ }
788
+ };
789
+ for (let j = 0; j < sk.count; j++) {
790
+ const p = sk.parent[j];
791
+ // A tube starts at a stem's foot, or where a limb leaves its parent.
792
+ const chain = [];
793
+ let at = p < 0 ? W.main[j] : W.line[j] && W.main[p] !== j ? j : -1;
794
+ while (at >= 0 && W.line[at]) {
795
+ chain.push(at);
796
+ at = W.main[at];
797
+ }
798
+ if (chain.length === 0)
799
+ continue;
800
+ // (Each tube a shade of its own, from its parent's where it leaves it: no seam of colour at a fork.)
801
+ const own = hash01(chain[0], v * 131 + 5);
802
+ const ownFrom = p < 0 ? own : ownOf[p];
803
+ const blend = p < 0 ? 1 : 4 * sk.radius[j] + 0.3;
804
+ for (const i of chain)
805
+ ownOf[i] = own;
806
+ if (p < 0)
807
+ ownOf[j] = own;
808
+ const foot = p < 0 ? j : -1;
809
+ const flared = foot >= 0 && shape.round && sk.radius[foot] > 0.06 && sk.radius[foot] > 1.02 * sk.radius[chain[0]];
810
+ const buttSpec = flared ? buttresses(foot * 7 + v * 1013, hf, tree.buttress ?? 0) : null;
811
+ const lobe = buttSpec ? buttSpec.swell : null;
812
+ let u = [];
813
+ let last = -1;
814
+ let lastSides = 0;
815
+ let lastR = 0;
816
+ let lastKey = "";
817
+ let end = { c: [0, 1, 0], d: [0, 1, 0], r: 0, attrs: { limb: [0, 0, 0], order: 0, along: 0 } };
818
+ const startAlong = W.line[chain[0]][8];
819
+ // (Over its root flare up to where the stem first divides, if lower: a forked trunk's or a clump's stems
820
+ // narrow fast where they part, and that is not flare to lay bark over.)
821
+ const parts = flared ? chain.findIndex((i) => (kidCount[i] ?? 0) > 1) : -1;
822
+ const bark = flared ? flareBark((parts >= 0 ? chain.slice(0, parts + 1) : chain).map((i) => W.line[i]), sk.y[foot], hf, lobe ?? undefined) : null;
823
+ const ownAt = (along) => {
824
+ const f = Math.min(1, Math.max(0, (along - startAlong) / blend));
825
+ return ownFrom + (own - ownFrom) * f * f * (3 - 2 * f);
826
+ };
827
+ // (Where a limb leaves its parent, its surface is lit as its parent's is, easing to its own over its
828
+ // first radius or so out of it: two tubes meet in a crease, and lit as two they show it as a seam; lit
829
+ // as one, the eye reads the crotch of a fork, the swell of a collar.)
830
+ const parentLines = p >= 0 && shape.round ? [W.line[p], W.line[W.main[p]]].filter((l) => l !== null) : [];
831
+ const leaving = (x, rLimb) => {
832
+ let best = Infinity;
833
+ let n = [];
834
+ for (const l of parentLines) {
835
+ for (let o = 0; o + LINE_STRIDE < l.length; o += LINE_STRIDE) {
836
+ const a = [l[o], l[o + 1], l[o + 2]];
837
+ const dd = [l[o + LINE_STRIDE] - a[0], l[o + LINE_STRIDE + 1] - a[1], l[o + LINE_STRIDE + 2] - a[2]];
838
+ const l2 = dot(dd, dd);
839
+ const f = l2 > 0 ? Math.min(1, Math.max(0, dot(sub(x, a), dd) / l2)) : 0;
840
+ const off = sub(x, add(a, scale(dd, f)));
841
+ const out = Math.hypot(off[0], off[1], off[2]) - (l[o + 6] + (l[o + LINE_STRIDE + 6] - l[o + 6]) * f);
842
+ if (out < best) {
843
+ best = out;
844
+ n = norm(off);
845
+ }
846
+ }
847
+ }
848
+ if (n.length === 0)
849
+ return null;
850
+ const t = Math.min(1, Math.max(0, best / (1.5 * rLimb)));
851
+ return { n, w: 1 - t * t * (3 - 2 * t) };
852
+ };
853
+ const ring = (c, d, r, g, limb, order, along, blend = false) => {
854
+ u = u.length ? norm(sub(u, scale(d, dot(u, d)))) : basis(d)[0];
855
+ if (!Number.isFinite(u[0]) || Math.hypot(u[0], u[1], u[2]) < 0.5)
856
+ u = basis(d)[0];
857
+ const w = cross(d, u);
858
+ const h = foot >= 0 ? c[1] - sk.y[foot] : 0;
859
+ const swells = lobe !== null && h < 2.5 * hf;
860
+ // (Its bark laid over the root flare as over the stem above it: see `flareBark`.)
861
+ const barkShare = bark ? Math.min(1, bark.radius / Math.max(r, 1e-4)) : 1;
862
+ const sides = sidesFor(shape, r, trunk) + (swells ? BUTTRESS_SIDES : 0);
863
+ let first = -1;
864
+ // (Its numbers laid one by one (`Builder.put`), each worked out as before, without arrays a vertex.)
865
+ const own = ownAt(along);
866
+ for (let s = 0; s < sides; s++) {
867
+ const a = (s / sides) * Math.PI * 2;
868
+ const cs = Math.cos(a);
869
+ const sn = Math.sin(a);
870
+ const e0 = u[0] * cs + w[0] * sn;
871
+ const e1 = u[1] * cs + w[1] * sn;
872
+ const e2 = u[2] * cs + w[2] * sn;
873
+ const r0 = -u[0] * sn + w[0] * cs;
874
+ const r1 = -u[1] * sn + w[1] * cs;
875
+ const r2 = -u[2] * sn + w[2] * cs;
876
+ let m = 1;
877
+ let mA = 0;
878
+ let mH = 0;
879
+ if (swells)
880
+ [m, mA, mH] = lobe(a, h);
881
+ // (The surface's normal: out, tipped back where it swells along the wood and round where it swells round it.)
882
+ const slopeAlong = g * m + r * mH * d[1];
883
+ const q0 = e0 - r0 * (mA / m) - d[0] * slopeAlong;
884
+ const q1 = e1 - r1 * (mA / m) - d[1] * slopeAlong;
885
+ const q2 = e2 - r2 * (mA / m) - d[2] * slopeAlong;
886
+ const ql = Math.hypot(q0, q1, q2) || 1;
887
+ let n0 = q0 / ql;
888
+ let n1 = q1 / ql;
889
+ let n2 = q2 / ql;
890
+ if (blend) {
891
+ const at = leaving([c[0] + e0 * r, c[1] + e1 * r, c[2] + e2 * r], r);
892
+ if (at && at.w > 0)
893
+ [n0, n1, n2] = norm(add(scale([n0, n1, n2], 1 - at.w), scale(at.n, at.w)));
894
+ }
895
+ const barkAlong = bark ? bark.along(along, a) : along;
896
+ b.putAt(P, c[0], c[1], c[2]);
897
+ b.putAt(RADIAL, e0 * m, e1 * m, e2 * m, r);
898
+ b.putAt(NORMAL, n0, n1, n2);
899
+ b.putAt(LIMB, limb[0], limb[1], limb[2], v);
900
+ b.putAt(WOOD, barkAlong, order, own, barkShare);
901
+ b.putAt(FRAME, u[0], u[1], u[2]);
902
+ b.putAt(AXIS, d[0], d[1], d[2]);
903
+ const k = b.next();
904
+ if (first < 0)
905
+ first = k;
906
+ }
907
+ if (last >= 0)
908
+ stitch(last, lastSides, first, sides, Math.max(lastR, r));
909
+ last = first;
910
+ lastSides = sides;
911
+ lastR = r;
912
+ end = { c, d, r, attrs: { limb, order, along } };
913
+ return first;
914
+ };
915
+ // A tube's end closed: a rounded cap (a ring part way round and its tip), or on thin wood its tip alone.
916
+ const capTube = () => {
917
+ const { c, d, r, attrs } = end;
918
+ const w = cross(d, u);
919
+ let rim = last;
920
+ let rimSides = lastSides;
921
+ if (lastSides >= CAP_RING_SIDES) {
922
+ const cs = Math.cos(CAP_RING);
923
+ const sn = Math.sin(CAP_RING);
924
+ let first = -1;
925
+ for (let s = 0; s < lastSides; s++) {
926
+ const a = (s / lastSides) * Math.PI * 2;
927
+ const e = [u[0] * Math.cos(a) + w[0] * Math.sin(a), u[1] * Math.cos(a) + w[1] * Math.sin(a), u[2] * Math.cos(a) + w[2] * Math.sin(a)];
928
+ const dir = [e[0] * cs + d[0] * sn, e[1] * cs + d[1] * sn, e[2] * cs + d[2] * sn];
929
+ const k = b.vertex({ position: c, aRadial: [...dir, r], aNormal: dir, aLimb: [...attrs.limb, v], aWood: [attrs.along, attrs.order, ownAt(attrs.along), 1], aFrame: u, aAxis: d });
930
+ if (first < 0)
931
+ first = k;
932
+ }
933
+ stitch(rim, rimSides, first, lastSides, r);
934
+ rim = first;
935
+ }
936
+ const tip = b.vertex({ position: c, aRadial: [...d, r], aNormal: d, aLimb: [...attrs.limb, v], aWood: [attrs.along, attrs.order, ownAt(attrs.along), 1], aFrame: u, aAxis: d });
937
+ for (let s = 0; s < rimSides; s++)
938
+ bands[bandOf(r)].push(rim + s, tip, rim + ((s + 1) % rimSides));
939
+ };
940
+ // (A twig, near: a ribbon of two vertices a ring, turned to the eye in the shader (engine.ts), its own
941
+ // side of the centre line in `aRadial.x`, as wide as the four-sided tube it was (`RIBBON_WIDE`); no normal
942
+ // (`aNormal` 0: the shader rounds it, facing the eye in the middle and out to its sides at its edges).
943
+ // Its side is the wood's way crossed with the way to the eye, so its triangles, wound from its -1 side
944
+ // to its +1 and on along the wood, always face the eye.)
945
+ let inRibbon = false;
946
+ const ribbonRing = (c, d, r, limb, order, along) => {
947
+ u = u.length ? norm(sub(u, scale(d, dot(u, d)))) : basis(d)[0];
948
+ if (!Number.isFinite(u[0]) || Math.hypot(u[0], u[1], u[2]) < 0.5)
949
+ u = basis(d)[0];
950
+ const own = ownAt(along);
951
+ let k = -1;
952
+ for (const side of [-RIBBON_WIDE, RIBBON_WIDE]) {
953
+ b.putAt(P, c[0], c[1], c[2]);
954
+ b.putAt(RADIAL, side, 0, 0, r);
955
+ b.putAt(NORMAL, 0, 0, 0);
956
+ b.putAt(LIMB, limb[0], limb[1], limb[2], v);
957
+ b.putAt(WOOD, along, order, own, 1);
958
+ b.putAt(FRAME, u[0], u[1], u[2]);
959
+ b.putAt(AXIS, d[0], d[1], d[2]);
960
+ const at = b.next();
961
+ if (k < 0)
962
+ k = at;
963
+ }
964
+ if (last >= 0)
965
+ bands[bandOf(Math.max(lastR, r))].push(last, last + 1, k, last + 1, k + 1, k);
966
+ last = k;
967
+ lastSides = 2;
968
+ lastR = r;
969
+ end = { c, d, r, attrs: { limb, order, along } };
970
+ };
971
+ // (Its end: a point a radius on.)
972
+ const ribbonTip = () => {
973
+ const { c, d, r, attrs } = end;
974
+ if (last < 0)
975
+ return;
976
+ const tip = b.vertex({ position: [c[0] + d[0] * r, c[1] + d[1] * r, c[2] + d[2] * r], aRadial: [0, 0, 0, r], aNormal: [0, 0, 0], aLimb: [...attrs.limb, v], aWood: [attrs.along + r, attrs.order, ownAt(attrs.along), 1], aFrame: u, aAxis: d });
977
+ bands[bandOf(r)].push(last, last + 1, tip);
978
+ };
979
+ // (A ring of the tube, or of its ribbon once it is a twig: a tube closed where its ribbon starts, and a
980
+ // ribbon a ribbon to its end.)
981
+ const put = (c, d, r, g, limb, order, along, blend = false) => {
982
+ if (shape.twig.sides === 2 && (inRibbon || r < TWIG)) {
983
+ if (!inRibbon) {
984
+ inRibbon = true;
985
+ if (last >= 0) {
986
+ // (Closed with its tip, and its ribbon starting at its last ring, as thick as the ribbon is here,
987
+ // in the tip: the piece between that ring and this one is the ribbon's.)
988
+ capTube();
989
+ last = -1;
990
+ ribbonRing(end.c, end.d, r, end.attrs.limb, end.attrs.order, end.attrs.along);
991
+ }
992
+ }
993
+ ribbonRing(c, d, r, limb, order, along);
994
+ }
995
+ else
996
+ ring(c, d, r, g, limb, order, along, blend);
997
+ };
998
+ const wl = windLimbs(sk);
999
+ for (let q = 0; q < chain.length; q++) {
1000
+ const i = chain[q];
1001
+ const line = W.line[i];
1002
+ const limbNode = wl.node[i];
1003
+ const limb = wl.foot(i);
1004
+ const key = `${limbNode},${sk.order[i]}`;
1005
+ const samples = line.length / LINE_STRIDE;
1006
+ for (let s = 0; s < samples; s++) {
1007
+ const o = s * LINE_STRIDE;
1008
+ const c = [line[o], line[o + 1], line[o + 2]];
1009
+ const d = [line[o + 3], line[o + 4], line[o + 5]];
1010
+ if (s === 0) {
1011
+ // (Where one piece runs on into the next, they share a ring; where a tube runs on into wood of
1012
+ // another limb or order, which the wind moves its own way, a ring of its own starts it again.)
1013
+ if (q > 0 && key === lastKey)
1014
+ continue;
1015
+ if (q > 0)
1016
+ last = -1;
1017
+ if (q === 0 && foot >= 0) {
1018
+ // (A stem's foot goes on a little into the ground, so it stands in it on a slope.)
1019
+ const deep = UNDERGROUND + UNDERGROUND_RADII * line[o + 6];
1020
+ put([c[0] - d[0] * deep, c[1] - d[1] * deep, c[2] - d[2] * deep], d, line[o + 6] * 1.15, 0, limb, sk.order[i], line[o + 8] - deep);
1021
+ }
1022
+ }
1023
+ put(c, d, line[o + 6], line[o + 7], limb, sk.order[i], line[o + 8], q === 0 && parentLines.length > 0);
1024
+ }
1025
+ lastKey = key;
1026
+ }
1027
+ if (inRibbon)
1028
+ ribbonTip();
1029
+ else
1030
+ capTube();
1031
+ // Radiating surface roots on mature near-tier flared stems: sinuous tapering tubes emerging from the
1032
+ // strongest buttress ridges, hugging the turf, and diving underground at their capped tips.
1033
+ if (buttSpec && sk.radius[foot] >= 0.12) {
1034
+ const rFoot = sk.radius[foot];
1035
+ const butt = tree.buttress ?? 0.25;
1036
+ const sorted = [...buttSpec.lobes].sort((a, b) => b.size - a.size);
1037
+ const strong = sorted.filter((l) => l.size >= 0.48);
1038
+ const pool = strong.length >= 3 ? strong : sorted;
1039
+ const rootCount = Math.min(pool.length, Math.max(3, Math.round(3 + 3 * butt)));
1040
+ const rootLimb = wl.foot(foot);
1041
+ const cx0 = sk.x[foot];
1042
+ const cy0 = sk.y[foot];
1043
+ const cz0 = sk.z[foot];
1044
+ const ROOT_STATIONS = [0, 0.24, 0.52, 0.80, 1.0];
1045
+ const ROOT_SIDES = 10;
1046
+ const rMaxCap = 0.44 * trunk;
1047
+ for (let ri = 0; ri < rootCount; ri++) {
1048
+ const lb = pool[ri];
1049
+ const rBase = Math.max(0.022, Math.min(rMaxCap, rFoot * (0.20 + 0.13 * lb.size) * (0.85 + 0.30 * butt)));
1050
+ const rTip = Math.max(0.018, Math.min(0.35 * rBase, 0.045 * rFoot));
1051
+ const reach = rFoot * (1.35 + 1.55 * butt) * (0.78 + 0.42 * lb.size);
1052
+ const rStart = 0.22 * rFoot;
1053
+ const wiggle = (hash01(foot * 31 + v * 977 + ri, 71) - 0.5) * 0.28;
1054
+ const hook = (hash01(foot * 31 + v * 977 + ri, 72) - 0.5) * 0.16;
1055
+ const rads = ROOT_STATIONS.map((t) => (t >= 1 ? rTip : Math.max(rTip, Math.min(rMaxCap, rBase * (1 - 0.62 * t) ** 1.15))));
1056
+ const pts = ROOT_STATIONS.map((t, k) => {
1057
+ const dist = rStart + (reach - rStart) * t;
1058
+ const az = lb.angle + wiggle * Math.sin(Math.PI * t) + hook * t * t;
1059
+ const rk = rads[k];
1060
+ const yOff = k === 0
1061
+ ? Math.min(0.18 * hf, 0.28 * rFoot)
1062
+ : k === 1
1063
+ ? 0.14 * rk
1064
+ : k === 2
1065
+ ? 0.02 * rk
1066
+ : k === 3
1067
+ ? -0.16 * rk
1068
+ : -0.34 - 0.4 * rBase;
1069
+ return [cx0 + dist * Math.cos(az), cy0 + yOff, cz0 + dist * Math.sin(az)];
1070
+ });
1071
+ const dirs = pts.map((_, k) => {
1072
+ const a = pts[Math.max(0, k - 1)];
1073
+ const q = pts[Math.min(pts.length - 1, k + 1)];
1074
+ return norm([q[0] - a[0], q[1] - a[1], q[2] - a[2]]);
1075
+ });
1076
+ let ru = norm(sub([0, 1, 0], scale(dirs[0], dirs[0][1])));
1077
+ if (!Number.isFinite(ru[0]) || Math.hypot(ru[0], ru[1], ru[2]) < 0.5)
1078
+ ru = basis(dirs[0])[0];
1079
+ const ringIds = [];
1080
+ let rootAlong = startAlong;
1081
+ for (let k = 0; k < pts.length; k++) {
1082
+ const c = pts[k];
1083
+ const d = dirs[k];
1084
+ if (k > 0)
1085
+ rootAlong -= Math.hypot(c[0] - pts[k - 1][0], c[1] - pts[k - 1][1], c[2] - pts[k - 1][2]) * 0.7;
1086
+ ru = norm(sub(ru, scale(d, dot(ru, d))));
1087
+ if (!Number.isFinite(ru[0]) || Math.hypot(ru[0], ru[1], ru[2]) < 0.5)
1088
+ ru = basis(d)[0];
1089
+ const rw = cross(d, ru);
1090
+ const r = rads[k];
1091
+ const squash = k >= 1 && k <= 3 ? 0.72 : 0.85;
1092
+ const segBefore = k > 0 ? Math.hypot(c[0] - pts[k - 1][0], c[1] - pts[k - 1][1], c[2] - pts[k - 1][2]) : 0;
1093
+ const segAfter = k + 1 < pts.length ? Math.hypot(pts[k + 1][0] - c[0], pts[k + 1][1] - c[1], pts[k + 1][2] - c[2]) : 0;
1094
+ const slope = k === 0
1095
+ ? (rads[1] - r) / Math.max(segAfter, 1e-4)
1096
+ : k === pts.length - 1
1097
+ ? (r - rads[k - 1]) / Math.max(segBefore, 1e-4)
1098
+ : (rads[k + 1] - rads[k - 1]) / Math.max(segBefore + segAfter, 1e-4);
1099
+ let firstV = -1;
1100
+ for (let s = 0; s < ROOT_SIDES; s++) {
1101
+ const a = (s / ROOT_SIDES) * Math.PI * 2;
1102
+ const cs = Math.cos(a);
1103
+ const sn = Math.sin(a);
1104
+ const e0 = ru[0] * (cs * squash) + rw[0] * sn;
1105
+ const e1 = ru[1] * (cs * squash) + rw[1] * sn;
1106
+ const e2 = ru[2] * (cs * squash) + rw[2] * sn;
1107
+ const nu = cs / squash;
1108
+ const nw = sn;
1109
+ const q0 = ru[0] * nu + rw[0] * nw - d[0] * slope;
1110
+ const q1 = ru[1] * nu + rw[1] * nw - d[1] * slope;
1111
+ const q2 = ru[2] * nu + rw[2] * nw - d[2] * slope;
1112
+ const ql = Math.hypot(q0, q1, q2) || 1;
1113
+ b.putAt(P, c[0], c[1], c[2]);
1114
+ b.putAt(RADIAL, e0, e1, e2, r);
1115
+ b.putAt(NORMAL, q0 / ql, q1 / ql, q2 / ql);
1116
+ b.putAt(LIMB, rootLimb[0], rootLimb[1], rootLimb[2], v);
1117
+ b.putAt(WOOD, rootAlong, 0, ownFrom, 0.75);
1118
+ b.putAt(FRAME, ru[0], ru[1], ru[2]);
1119
+ b.putAt(AXIS, d[0], d[1], d[2]);
1120
+ const idx = b.next();
1121
+ if (firstV < 0)
1122
+ firstV = idx;
1123
+ }
1124
+ ringIds.push(firstV);
1125
+ if (k > 0)
1126
+ stitch(ringIds[k - 1], ROOT_SIDES, firstV, ROOT_SIDES, Math.max(rads[k - 1], r));
1127
+ }
1128
+ const dStart = dirs[0];
1129
+ const startApex = b.vertex({
1130
+ position: pts[0],
1131
+ aRadial: [-dStart[0], -dStart[1], -dStart[2], 0.1 * rads[0]],
1132
+ aNormal: [-dStart[0], -dStart[1], -dStart[2]],
1133
+ aLimb: [...rootLimb, v],
1134
+ aWood: [startAlong, 0, ownFrom, 0.75],
1135
+ aFrame: ru,
1136
+ aAxis: dStart,
1137
+ });
1138
+ const r0 = ringIds[0];
1139
+ for (let s = 0; s < ROOT_SIDES; s++)
1140
+ bands[0].push(r0 + s, r0 + ((s + 1) % ROOT_SIDES), startApex);
1141
+ const dEnd = dirs[dirs.length - 1];
1142
+ const endApex = b.vertex({
1143
+ position: pts[pts.length - 1],
1144
+ aRadial: [dEnd[0], dEnd[1], dEnd[2], rTip],
1145
+ aNormal: dEnd,
1146
+ aLimb: [...rootLimb, v],
1147
+ aWood: [rootAlong, 0, ownFrom, 0.75],
1148
+ aFrame: ru,
1149
+ aAxis: dEnd,
1150
+ });
1151
+ const rLast = ringIds[ringIds.length - 1];
1152
+ for (let s = 0; s < ROOT_SIDES; s++)
1153
+ bands[0].push(rLast + s, endApex, rLast + ((s + 1) % ROOT_SIDES));
1154
+ }
1155
+ }
1156
+ }
1157
+ b.endBands(bands);
1158
+ });
1159
+ return b.done();
1160
+ }
1161
+ function add(a, b) {
1162
+ return [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
1163
+ }
1164
+ function sub(a, b) {
1165
+ return [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
1166
+ }
1167
+ function scale(a, k) {
1168
+ return [a[0] * k, a[1] * k, a[2] * k];
1169
+ }
1170
+ function dot(a, b) {
1171
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
1172
+ }
1173
+ function cross(a, b) {
1174
+ return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
1175
+ }
1176
+ function norm(a) {
1177
+ const l = Math.hypot(a[0], a[1], a[2]) || 1;
1178
+ return [a[0] / l, a[1] / l, a[2] / l];
1179
+ }
1180
+ /** Two directions square to `d` and to each other, chosen the same way for every `d`, so rings along a branch do not twist. */
1181
+ function basis(d) {
1182
+ const ref = Math.abs(d[1]) < 0.9 ? [0, 1, 0] : [1, 0, 0];
1183
+ const u = norm([ref[1] * d[2] - ref[2] * d[1], ref[2] * d[0] - ref[0] * d[2], ref[0] * d[1] - ref[1] * d[0]]);
1184
+ const w = [d[1] * u[2] - d[2] * u[1], d[2] * u[0] - d[0] * u[2], d[0] * u[1] - d[1] * u[0]];
1185
+ return [u, w];
1186
+ }
1187
+ /** How far from a clump's centre (in its radii) a twig's end may be and still be one of the clump's twigs: a little past the grower's 0.8, which the fitting and the outline move. */
1188
+ export const IN_CLUMP = 1.2;
1189
+ /** How far back along the wood from a clump's twig end its cards' feet may be, in the clump's radii. */
1190
+ const SHOOT = 1.1;
1191
+ /** Where a spray's twig enters its card, from the card's centre, in its half-lengths (the sprays in leaves.ts start 0.7 to 0.97 below). */
1192
+ export const SPRAY_FOOT = 0.8;
1193
+ /** An upright cushion card's size about its kind's, from 1 - this / 2 to 1 + this / 2; and how far up or down its twig it stands, in its clump's radii. */
1194
+ const CUSHION_VARY = 0.7;
1195
+ const CUSHION_RISE = 0.55;
1196
+ /**
1197
+ * Each clump's twigs: the node it hangs on, then the ends of the other twigs inside it. A clump is a spray of
1198
+ * leaves over the twigs where it hangs, and the grower keeps the twigs inside one for that (grow.ts
1199
+ * `leafy`); a twig's end that no clump hangs on goes to the clump it is deepest in, if it is in one.
1200
+ */
1201
+ /** Each grown tree's clumps' twigs (`clumpTwigs`), worked out once: its dabs, near cards and mid cards each ask. */
1202
+ const TWIGS = new WeakMap();
1203
+ export function clumpTwigs(tree) {
1204
+ let twigs = TWIGS.get(tree);
1205
+ if (!twigs)
1206
+ TWIGS.set(tree, (twigs = twigsOf(tree)));
1207
+ return twigs;
1208
+ }
1209
+ function twigsOf(tree) {
1210
+ const { clumps: cl, skeleton: sk } = tree;
1211
+ const out = [];
1212
+ const hung = new Uint8Array(sk.count);
1213
+ for (let c = 0; c < cl.count; c++) {
1214
+ out.push([cl.node[c]]);
1215
+ hung[cl.node[c]] = 1;
1216
+ }
1217
+ const kids = new Uint8Array(sk.count);
1218
+ for (let i = 0; i < sk.count; i++)
1219
+ if (sk.parent[i] >= 0)
1220
+ kids[sk.parent[i]] = 1;
1221
+ for (let i = 0; i < sk.count; i++) {
1222
+ if (kids[i] || hung[i] || sk.parent[i] < 0)
1223
+ continue;
1224
+ let best = -1;
1225
+ let bestF = IN_CLUMP;
1226
+ for (let c = 0; c < cl.count; c++) {
1227
+ const f = Math.hypot(sk.x[i] - cl.x[c], sk.y[i] - cl.y[c], sk.z[i] - cl.z[c]) / cl.radius[c];
1228
+ if (f < bestF) {
1229
+ bestF = f;
1230
+ best = c;
1231
+ }
1232
+ }
1233
+ if (best >= 0)
1234
+ out[best].push(i);
1235
+ }
1236
+ return out;
1237
+ }
1238
+ /**
1239
+ * The wood leading to a node, back from it along its parents for up to `most` metres (not down onto a stem,
1240
+ * unless the node is on one), along its centre line as drawn close to (`lines`): `at(s)` is the point `s`
1241
+ * metres back from the node, and which way the wood runs there (out, towards the node).
1242
+ */
1243
+ function shootOf(sk, lines, node, most) {
1244
+ const pts = [[sk.x[node], sk.y[node], sk.z[node]]];
1245
+ const dirs = [];
1246
+ const lens = [];
1247
+ let length = 0;
1248
+ const back = (q) => {
1249
+ const a = pts[pts.length - 1];
1250
+ const seg = [a[0] - q[0], a[1] - q[1], a[2] - q[2]];
1251
+ const l = Math.hypot(seg[0], seg[1], seg[2]);
1252
+ if (l <= 1e-6)
1253
+ return;
1254
+ pts.push(q);
1255
+ dirs.push(seg.map((x) => x / l));
1256
+ lens.push(l);
1257
+ length += l;
1258
+ };
1259
+ // (Down each line from where the wood came onto it: a node's own line from its end, its parent's from
1260
+ // where the node's line left it.)
1261
+ let at = -1;
1262
+ for (let i = node; length < most;) {
1263
+ const p = sk.parent[i];
1264
+ if (p < 0 || (sk.order[i] === 0 && sk.order[node] > 0))
1265
+ break;
1266
+ const line = lines.line[i];
1267
+ const top = at >= 0 ? at * LINE_STRIDE : line ? line.length - 2 * LINE_STRIDE : 0;
1268
+ if (line)
1269
+ for (let o = top; o >= 0 && length < most; o -= LINE_STRIDE)
1270
+ back([line[o], line[o + 1], line[o + 2]]);
1271
+ else
1272
+ back([sk.x[p], sk.y[p], sk.z[p]]);
1273
+ at = lines.from[i];
1274
+ i = p;
1275
+ }
1276
+ length = Math.min(length, most);
1277
+ return {
1278
+ length,
1279
+ at(s) {
1280
+ if (dirs.length === 0)
1281
+ return { p: pts[0], d: [0, 1, 0] };
1282
+ let left = Math.min(Math.max(0, s), length);
1283
+ for (let j = 0; j < lens.length; j++) {
1284
+ if (left <= lens[j] || j === lens.length - 1) {
1285
+ const f = Math.min(1, left / lens[j]);
1286
+ const a = pts[j];
1287
+ const b = pts[j + 1];
1288
+ return { p: [a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f, a[2] + (b[2] - a[2]) * f], d: dirs[j] };
1289
+ }
1290
+ left -= lens[j];
1291
+ }
1292
+ return { p: pts[0], d: dirs[0] };
1293
+ },
1294
+ };
1295
+ }
1296
+ /** How a conifer's sheet is shaped: rows along it, columns across it (a sheet is (ROWS-1) (COLS-1) quads). */
1297
+ export const SHEET_ALONG = 4;
1298
+ export const SHEET_ACROSS = 3;
1299
+ /** The most sheets a clump of its own is laid with: one along its own twig, and one along another of its twigs that reaches out of the first. */
1300
+ export const SHEETS_PER_CLUMP = 2;
1301
+ /** A clump's own sheet: its length, and its half width, in the clump's radii; how far back along the wood its foot is. */
1302
+ const SHEET_LENGTH = 3.6;
1303
+ const SHEET_HALF = 1.4;
1304
+ /** A spire's sheets round its leader: how many to a clump, and how long and wide, in its clump's radii. */
1305
+ const SPIRE_SHEETS = 3;
1306
+ const SPIRE_SHEET_LENGTH = 2.2;
1307
+ const SPIRE_SHEET_HALF = 0.95;
1308
+ const SHEET_BACK = 0.75;
1309
+ /**
1310
+ * How far a sheet's edges fall away for a species whose side shoots hang in curtains (`habit.sprayHang` 1),
1311
+ * over its own arch, in its half widths: a Norway spruce's low boughs hang their combs of shoots, so from the
1312
+ * side a bough is a fringe the depth of the gap to the next, and the crown is closed. The highest boughs hang
1313
+ * this share of it.
1314
+ */
1315
+ const CURTAIN = 1.4;
1316
+ /** The most a sheet's edges fall for curtains, over its own arch (half widths): its top still faces up. */
1317
+ const CURTAIN_MOST = 0.6;
1318
+ const CURTAIN_TOP = 0.35;
1319
+ /** How much a sheet's edges fall, over its own arch, for a tree's habit, its foot at height `y`. */
1320
+ function curtainOf(tree, y) {
1321
+ const hang = tree.habit?.sprayHang ?? 0;
1322
+ if (hang <= 0)
1323
+ return 0;
1324
+ const { crownBase, height } = tree.size;
1325
+ const up = Math.min(1, Math.max(0, (y - crownBase) / Math.max(0.01, height - crownBase)));
1326
+ return Math.min(CURTAIN_MOST, CURTAIN * hang * (CURTAIN_TOP + (1 - CURTAIN_TOP) * (1 - up)));
1327
+ }
1328
+ /** A bough's sheets: each this many of its clumps' radii long, the next starting this share of it on. */
1329
+ const BOUGH_PIECE = 3.2;
1330
+ const BOUGH_STEP = 0.62;
1331
+ /**
1332
+ * A conifer's near foliage as sheets: curved strips lying along its boughs, a comb of needles (Koerye's
1333
+ * foliage-mass study found these read as tiered boughs from every side, where loose leaves gave spiky balls
1334
+ * and closed blocks cushions). Each bough is laid with a run of them along its own wood, from its first
1335
+ * clump to its tip, overlapping, each as wide as its clumps reach either side of it; a clump off its bough's
1336
+ * line, or on the leader, a sheet or two of its own along its twig. Each sheet's foot is on the wood. It is lifted there and droops to its tip, its edges falling
1337
+ * away either side of its middle, a little twisted, so seen from the side it is a bough hanging its fringe
1338
+ * and from below a bough's shade.
1339
+ *
1340
+ * `kinds[v]` says what kind of sheet each variant's clumps are laid with (an index into marks.ts
1341
+ * `SHEET_KINDS`: 0 fir, 1 cedar), or -1 for none (its clumps are dabs). Each vertex: `position` where
1342
+ * it is (its variant's frame); `aDab` where it is on the sheet's picture (x across, y along its length, each
1343
+ * -1..1), half the sheet's length (m), and a number of the sheet's own; `aNormal` its clump's outward normal
1344
+ * and depth; `aOffset` the sheet's own normal there (its top's side) and its kind; `aLimb` the foot of its
1345
+ * limb and its variant; `aSpine` from it to the sheet's middle line, across.
1346
+ */
1347
+ export function sheetPieces(trees, kinds, coarse = false) {
1348
+ const b = new Builder({ position: 3, aDab: 4, aNormal: 4, aOffset: 4, aLimb: 4, aSpine: 3 });
1349
+ trees.forEach((tree, v) => {
1350
+ b.begin();
1351
+ const kind = kinds[v] ?? -1;
1352
+ if (kind >= 0) {
1353
+ const { clumps: cl, skeleton: sk } = tree;
1354
+ const lines = woodLines(tree, TIER_SHAPES[0]);
1355
+ const covered = new Uint8Array(cl.count);
1356
+ boughSheets(b, tree, lines, kind, v, covered, coarse);
1357
+ const twigs = clumpTwigs(tree);
1358
+ const spire = [];
1359
+ for (let c = 0; c < cl.count; c++) {
1360
+ if (covered[c])
1361
+ continue;
1362
+ const r = cl.radius[c];
1363
+ const n = [cl.nx[c], cl.ny[c], cl.nz[c]];
1364
+ // (Along its own twig first, then along the twig of it that reaches farthest from that sheet's line.)
1365
+ const laid = [];
1366
+ // (Mid, only the leader's: a bough's own sheets, wider there, cover its side shoots' clumps well enough
1367
+ // from where a mid tree is seen.)
1368
+ if (coarse && sk.order[cl.node[c]] > 0)
1369
+ continue;
1370
+ if (sk.order[cl.node[c]] === 0 && coarse) {
1371
+ // (Mid, the spire is one: below.)
1372
+ spire.push(c);
1373
+ continue;
1374
+ }
1375
+ if (sk.order[cl.node[c]] === 0) {
1376
+ // (On the leader, its spire: short sheets round it, splayed out and up as a fir's top shoots are,
1377
+ // each turned from the last, so the leader is clothed in needles all round and ends in a point.)
1378
+ const node = cl.node[c];
1379
+ const foot = [sk.x[node], sk.y[node] - r * 0.35, sk.z[node]];
1380
+ const around = coarse ? 2 : SPIRE_SHEETS;
1381
+ const turn0 = c * 2.39996;
1382
+ for (let s = 0; s < around; s++) {
1383
+ const a = turn0 + (s * 2 * Math.PI) / around;
1384
+ const out = [Math.cos(a), 0, Math.sin(a)];
1385
+ const k = c * 53 + s;
1386
+ const dir = norm([out[0] * 0.85, 1, out[2] * 0.85]);
1387
+ const length = r * SPIRE_SHEET_LENGTH * (0.9 + 0.2 * hash01(k, 12));
1388
+ sheet(b, foot, dir, length, r * SPIRE_SHEET_HALF, { lift: 0.04, droop: 0.12 + 0.08 * hash01(k, 14), arch: 0.5 + 0.3 * hash01(k, 15), twist: (hash01(k, 16) - 0.5) * 0.4 }, hash01(k, v * 389 + 11), n, cl.depth[c], kind, limbOf(sk, node), v, coarse ? 2 : SHEET_ALONG);
1389
+ }
1390
+ continue;
1391
+ }
1392
+ const most = cl.depth[c] > 0.65 || coarse ? 1 : SHEETS_PER_CLUMP;
1393
+ const order = [...twigs[c]].sort((p, q) => (p === cl.node[c] ? -1 : q === cl.node[c] ? 1 : 0));
1394
+ for (const t of order) {
1395
+ if (laid.length >= most)
1396
+ break;
1397
+ const tip = [sk.x[t], sk.y[t], sk.z[t]];
1398
+ if (laid.some((s) => offLine(tip, s.foot, s.dir, s.length) < r * 0.7))
1399
+ continue;
1400
+ const k = c * 53 + laid.length;
1401
+ const shoot = shootOf(sk, lines, t, r * SHEET_BACK * 1.5);
1402
+ const foot = shoot.at(Math.min(shoot.length, r * SHEET_BACK)).p;
1403
+ // (Along its limb more than along its own twig, out from the trunk, and nearer level than either:
1404
+ // sprays lie flat and turn up only a little.)
1405
+ const d0 = shoot.at(0).d;
1406
+ const l = sk.limb[t];
1407
+ const limb = sk.order[t] === 0 ? d0 : norm([tip[0] - sk.x[l], tip[1] - sk.y[l], tip[2] - sk.z[l]]);
1408
+ const out = norm([tip[0], 0, tip[2]]);
1409
+ const run = add(add(scale(limb, 0.6), scale(d0, 0.4)), scale(out, 0.2));
1410
+ // (On the leader, upright: a conifer's top is a spire, not a flag.)
1411
+ const dir = sk.order[t] === 0 ? norm([d0[0] * 0.3, 1, d0[2] * 0.3]) : norm([run[0], run[1] * 0.45 + 0.03, run[2]]);
1412
+ const length = r * SHEET_LENGTH * (0.85 + 0.3 * hash01(k, 12)) * (coarse ? 1.2 : 1);
1413
+ const half = r * SHEET_HALF * (0.85 + 0.3 * hash01(k, 13)) * (coarse ? 1.15 : 1) * (sk.order[t] === 0 ? 0.3 : 1);
1414
+ laid.push({ foot, dir, length });
1415
+ const a = hash01(k, 14);
1416
+ sheet(b, foot, dir, length, half, { lift: 0.1 + 0.08 * a, droop: 0.26 + 0.22 * a, arch: 0.55 + 0.35 * hash01(k, 15) + curtainOf(tree, foot[1]), twist: (hash01(k, 16) - 0.5) * 0.7 }, hash01(k, v * 389 + 11), n, cl.depth[c], kind, limbOf(sk, t), v, coarse ? 2 : SHEET_ALONG);
1417
+ }
1418
+ }
1419
+ // (Any twig's end the sheets leave out, a sheet of its own along that twig, over its end: a twig poking out
1420
+ // of a conifer's needles bare is a dead stick, which it is not.)
1421
+ coverEnds(b, tree, lines, kind, v, coarse);
1422
+ if (spire.length > 0) {
1423
+ // (Mid, a spire is two sheets crossed, from its lowest needles to its tip, widest at its foot: a
1424
+ // narrow point and not a string of beads, which a few small sheets each its own read as.)
1425
+ let lo = Infinity;
1426
+ let hi = -Infinity;
1427
+ let wide = 0;
1428
+ let lowest = spire[0];
1429
+ for (const c of spire) {
1430
+ const r = cl.radius[c];
1431
+ if (cl.y[c] - r * 0.6 < lo) {
1432
+ lo = cl.y[c] - r * 0.6;
1433
+ lowest = c;
1434
+ }
1435
+ hi = Math.max(hi, cl.y[c] + r * 0.9);
1436
+ wide = Math.max(wide, r);
1437
+ }
1438
+ const node = cl.node[lowest];
1439
+ const foot = [sk.x[node], lo, sk.z[node]];
1440
+ const n = [cl.nx[lowest], cl.ny[lowest], cl.nz[lowest]];
1441
+ for (let s = 0; s < 2; s++) {
1442
+ const a = lowest * 2.39996 + s * Math.PI * 0.5;
1443
+ const dir = norm([Math.cos(a) * 0.04, 1, Math.sin(a) * 0.04]);
1444
+ sheet(b, foot, dir, hi - lo, wide * 1.15, { lift: 0, droop: 0.02, arch: 0.25, twist: 0, point: true }, hash01(lowest * 53 + s, v * 389 + 11), n, cl.depth[lowest], kind, limbOf(sk, node), v, 2);
1445
+ }
1446
+ }
1447
+ }
1448
+ b.end();
1449
+ });
1450
+ return b.done();
1451
+ }
1452
+ /**
1453
+ * A fir's boughs: each limb's clumps that lie along its own wood, laid as a run of overlapping sheets on that
1454
+ * wood from its first clump to past its last, each as wide as those clumps reach either side of it. The
1455
+ * clumps it covers are marked in `covered`; one off its line is left to a sheet of its own.
1456
+ */
1457
+ function boughSheets(b, tree, lines, kind, v, covered, coarse) {
1458
+ const { clumps: cl, skeleton: sk } = tree;
1459
+ const byLimb = new Map();
1460
+ for (let c = 0; c < cl.count; c++) {
1461
+ const node = cl.node[c];
1462
+ if (sk.order[node] === 0)
1463
+ continue;
1464
+ const l = sk.limb[node];
1465
+ if (!byLimb.has(l))
1466
+ byLimb.set(l, []);
1467
+ byLimb.get(l).push(c);
1468
+ }
1469
+ let piece = 0;
1470
+ for (const [l, list] of byLimb) {
1471
+ // (The bough's wood as drawn: its centre line from where it leaves the trunk, on through its thickest child.)
1472
+ const pts = [];
1473
+ for (let i = l; i >= 0 && lines.line[i]; i = lines.main[i]) {
1474
+ const line = lines.line[i];
1475
+ for (let o = 0; o < line.length; o += LINE_STRIDE) {
1476
+ const p = [line[o], line[o + 1], line[o + 2]];
1477
+ const last = pts[pts.length - 1];
1478
+ if (!last || Math.hypot(p[0] - last[0], p[1] - last[1], p[2] - last[2]) > 1e-4)
1479
+ pts.push(p);
1480
+ }
1481
+ }
1482
+ if (pts.length < 2)
1483
+ continue;
1484
+ const along = [0];
1485
+ for (let q = 1; q < pts.length; q++)
1486
+ along.push(along[q - 1] + Math.hypot(pts[q][0] - pts[q - 1][0], pts[q][1] - pts[q - 1][1], pts[q][2] - pts[q - 1][2]));
1487
+ const total = along[along.length - 1];
1488
+ const at = (s) => {
1489
+ const t = Math.min(total, Math.max(0, s));
1490
+ let q = 1;
1491
+ while (q < pts.length - 1 && along[q] < t)
1492
+ q++;
1493
+ const f = (t - along[q - 1]) / Math.max(1e-9, along[q] - along[q - 1]);
1494
+ return [pts[q - 1][0] + (pts[q][0] - pts[q - 1][0]) * f, pts[q - 1][1] + (pts[q][1] - pts[q - 1][1]) * f, pts[q - 1][2] + (pts[q][2] - pts[q - 1][2]) * f];
1495
+ };
1496
+ // (Where each clump lies along the bough, and how far off it.)
1497
+ const on = [];
1498
+ for (const c of list) {
1499
+ const p = [cl.x[c], cl.y[c], cl.z[c]];
1500
+ let best = { s: 0, off: Infinity };
1501
+ for (let q = 1; q < pts.length; q++) {
1502
+ const a = pts[q - 1];
1503
+ const d = sub(pts[q], a);
1504
+ const l2 = dot(d, d);
1505
+ const f = l2 > 0 ? Math.min(1, Math.max(0, dot(sub(p, a), d) / l2)) : 0;
1506
+ const off = Math.hypot(p[0] - a[0] - d[0] * f, p[1] - a[1] - d[1] * f, p[2] - a[2] - d[2] * f);
1507
+ if (off < best.off)
1508
+ best = { s: along[q - 1] + f * (along[q] - along[q - 1]), off };
1509
+ }
1510
+ on.push({ c, ...best });
1511
+ }
1512
+ const rMean = on.reduce((sum, o) => sum + cl.radius[o.c], 0) / on.length;
1513
+ // (A clump far off the bough's line is a side shoot of its own: its own sheet.)
1514
+ const near = on.filter((o) => o.off < cl.radius[o.c] * 2.2 + rMean * (coarse ? 1.5 : 0.5));
1515
+ if (near.length === 0)
1516
+ continue;
1517
+ // (From its first clump, or from a third of the way out if that is nearer the trunk: a bough is leafy
1518
+ // along most of its length, and the grower's clumps keep to its outer part.)
1519
+ const s0 = Math.max(0, Math.min(total * 0.3, ...near.map((o) => o.s - cl.radius[o.c] * 1.2)));
1520
+ const s1 = Math.min(total + rMean, Math.max(...near.map((o) => o.s + cl.radius[o.c] * 1.4)));
1521
+ // (Mid, longer pieces, fewer of them: a bough or two to a sheet.)
1522
+ const length = rMean * BOUGH_PIECE * (coarse ? 2.8 : 1);
1523
+ const count = Math.max(1, Math.ceil((s1 - s0 - length) / (length * BOUGH_STEP)) + 1);
1524
+ const step = count > 1 ? (s1 - s0 - length) / (count - 1) : 0;
1525
+ for (const o of near)
1526
+ covered[o.c] = 1;
1527
+ for (let k = 0; k < count; k++) {
1528
+ const sa = s0 + step * k;
1529
+ const sb = sa + length;
1530
+ const foot = at(sa);
1531
+ // (Its clumps: those it lies over, for how wide it is, which way they face, how deep they are.)
1532
+ const mine = near.filter((o) => o.s > sa - cl.radius[o.c] && o.s < sb + cl.radius[o.c]);
1533
+ const use = mine.length ? mine : near;
1534
+ const half = Math.max(rMean * 1.3, Math.max(...use.map((o) => o.off + cl.radius[o.c])) * 1.15) * (coarse ? 1.15 : 1);
1535
+ const nn = norm(use.reduce((m, o) => [m[0] + cl.nx[o.c], m[1] + cl.ny[o.c], m[2] + cl.nz[o.c]], [0, 0, 0]));
1536
+ const depth = use.reduce((m, o) => m + cl.depth[o.c], 0) / use.length;
1537
+ // (Along the bough's chord over its length, nearer level: past the bough's tip, on as it ran.)
1538
+ const end = sb <= total ? at(sb) : add(at(total), scale(norm(sub(at(total), at(Math.max(0, total - length * 0.5)))), sb - total));
1539
+ const chord = norm(sub(end, foot));
1540
+ const dir = norm([chord[0], chord[1] * 0.5 + 0.02, chord[2]]);
1541
+ // (The last of a bough's sheets hangs most, as its tip does; those along it lie as the wood does.)
1542
+ const tipward = sb >= s1 - 1e-6 ? 1 : 0.35;
1543
+ const h = piece * 31 + v * 7;
1544
+ sheet(b, foot, dir, length * (0.95 + 0.1 * hash01(h, 21)), half, { lift: 0.06, droop: (0.12 + 0.12 * hash01(h, 22)) * (0.5 + tipward) * (coarse ? 0.7 : 1), arch: 0.55 + 0.3 * hash01(h, 23) + curtainOf(tree, foot[1]), twist: (hash01(h, 24) - 0.5) * 0.4 }, hash01(h, v * 389 + 11), nn, depth, kind, limbOf(sk, l), v, coarse ? 2 : SHEET_ALONG);
1545
+ piece++;
1546
+ }
1547
+ }
1548
+ }
1549
+ /** How far past a sheet a twig's end may be (in its clump's radii, near and mid) before it is given a sheet of its own. */
1550
+ const END_UNDER = [0.18, 0.4];
1551
+ /**
1552
+ * Each twig's end in the crown that the variant's sheets so far (those since `b.begin()`) leave more than
1553
+ * `END_UNDER` of a clump's radius from them: a short sheet along its twig, over its end.
1554
+ */
1555
+ function coverEnds(b, tree, lines, kind, v, coarse) {
1556
+ const { clumps: cl, skeleton: sk } = tree;
1557
+ if (cl.count === 0)
1558
+ return;
1559
+ const pos = b.floats.position;
1560
+ // (This variant's triangles, as corner positions.)
1561
+ const start = b.start;
1562
+ const tris = [];
1563
+ for (let t = start.index; t < b.index.length; t += 3) {
1564
+ for (let c = 0; c < 3; c++) {
1565
+ const vtx = (b.index[t + c] + start.vertex) * 3;
1566
+ tris.push(pos[vtx], pos[vtx + 1], pos[vtx + 2]);
1567
+ }
1568
+ }
1569
+ const has = new Uint8Array(sk.count);
1570
+ for (let i = 0; i < sk.count; i++)
1571
+ if (sk.parent[i] >= 0)
1572
+ has[sk.parent[i]] = 1;
1573
+ // (Each end's clump: the nearest whose ball it is in, for the size of what covers it.)
1574
+ let rMean = 0;
1575
+ for (let c = 0; c < cl.count; c++)
1576
+ rMean += cl.radius[c] / cl.count;
1577
+ const reach = END_UNDER[coarse ? 1 : 0];
1578
+ const off = (p, most) => {
1579
+ let best = most;
1580
+ for (let t = 0; t < tris.length; t += 9) {
1581
+ const lo = Math.max(Math.min(tris[t], tris[t + 3], tris[t + 6]) - p[0], p[0] - Math.max(tris[t], tris[t + 3], tris[t + 6]), Math.min(tris[t + 1], tris[t + 4], tris[t + 7]) - p[1], p[1] - Math.max(tris[t + 1], tris[t + 4], tris[t + 7]), Math.min(tris[t + 2], tris[t + 5], tris[t + 8]) - p[2], p[2] - Math.max(tris[t + 2], tris[t + 5], tris[t + 8]));
1582
+ if (lo >= best)
1583
+ continue;
1584
+ best = Math.min(best, triangleDistance(p, tris, t));
1585
+ }
1586
+ return best;
1587
+ };
1588
+ for (let i = 0; i < sk.count; i++) {
1589
+ if (has[i] || sk.parent[i] < 0 || sk.order[i] === 0 || sk.y[i] < tree.size.crownBase)
1590
+ continue;
1591
+ const tip = [sk.x[i], sk.y[i], sk.z[i]];
1592
+ let r = rMean;
1593
+ let nearest = Infinity;
1594
+ for (let c = 0; c < cl.count; c++) {
1595
+ const d = Math.hypot(cl.x[c] - tip[0], cl.y[c] - tip[1], cl.z[c] - tip[2]);
1596
+ if (d < nearest) {
1597
+ nearest = d;
1598
+ r = cl.radius[c];
1599
+ }
1600
+ }
1601
+ r = Math.min(r, rMean);
1602
+ if (off(tip, reach * r + 1e-6) <= reach * r)
1603
+ continue;
1604
+ const shoot = shootOf(sk, lines, i, r * 1.2);
1605
+ const foot = shoot.at(Math.min(shoot.length, r * 0.9)).p;
1606
+ const along = norm(sub(tip, foot));
1607
+ const dir = along;
1608
+ const k = i * 37 + 5;
1609
+ const length = Math.max(r * 1.7, Math.hypot(...sub(tip, foot)) * 1.6);
1610
+ sheet(b, foot, dir, length, r * (coarse ? 0.9 : 0.75), { lift: 0, droop: 0.02 + 0.04 * hash01(k, 22), arch: 0.35, twist: (hash01(k, 24) - 0.5) * 0.4 }, hash01(k, v * 389 + 11), norm([tip[0], 0.4, tip[2]]), 0.3, kind, limbOf(sk, i), v, coarse ? 2 : SHEET_ALONG);
1611
+ // (Its triangles count for the ends after it.)
1612
+ const vtx = b.vertices - (coarse ? 2 : SHEET_ALONG) * SHEET_ACROSS;
1613
+ const rows = coarse ? 2 : SHEET_ALONG;
1614
+ for (let j = 0; j + 1 < rows; j++)
1615
+ for (let q = 0; q + 1 < SHEET_ACROSS; q++) {
1616
+ const a = (vtx + j * SHEET_ACROSS + q) * 3;
1617
+ const c2 = (vtx + (j + 1) * SHEET_ACROSS + q) * 3;
1618
+ for (const [x, y, z] of [
1619
+ [a, a + 3, c2],
1620
+ [a + 3, c2 + 3, c2],
1621
+ ])
1622
+ tris.push(pos[x], pos[x + 1], pos[x + 2], pos[y], pos[y + 1], pos[y + 2], pos[z], pos[z + 1], pos[z + 2]);
1623
+ }
1624
+ }
1625
+ }
1626
+ /** How far a point is from the triangle at `t` in a flat list of corners. */
1627
+ function triangleDistance(p, tris, t) {
1628
+ const a = [tris[t], tris[t + 1], tris[t + 2]];
1629
+ const ab = [tris[t + 3] - a[0], tris[t + 4] - a[1], tris[t + 5] - a[2]];
1630
+ const ac = [tris[t + 6] - a[0], tris[t + 7] - a[1], tris[t + 8] - a[2]];
1631
+ const ap = sub(p, a);
1632
+ const d1 = dot(ab, ap);
1633
+ const d2 = dot(ac, ap);
1634
+ const d00 = dot(ab, ab);
1635
+ const d01 = dot(ab, ac);
1636
+ const d11 = dot(ac, ac);
1637
+ const den = d00 * d11 - d01 * d01;
1638
+ if (den > 1e-12) {
1639
+ const s = (d11 * d1 - d01 * d2) / den;
1640
+ const w = (d00 * d2 - d01 * d1) / den;
1641
+ if (s >= 0 && w >= 0 && s + w <= 1)
1642
+ return Math.hypot(ap[0] - ab[0] * s - ac[0] * w, ap[1] - ab[1] * s - ac[1] * w, ap[2] - ab[2] * s - ac[2] * w);
1643
+ }
1644
+ const seg = (u, d) => {
1645
+ const f = Math.min(1, Math.max(0, dot(sub(p, u), d) / Math.max(1e-12, dot(d, d))));
1646
+ return Math.hypot(p[0] - u[0] - d[0] * f, p[1] - u[1] - d[1] * f, p[2] - u[2] - d[2] * f);
1647
+ };
1648
+ const b = [tris[t + 3], tris[t + 4], tris[t + 5]];
1649
+ return Math.min(seg(a, ab), seg(a, ac), seg(b, [tris[t + 6] - b[0], tris[t + 7] - b[1], tris[t + 8] - b[2]]));
1650
+ }
1651
+ /** How far a point lies from a sheet's line (its foot, the way it runs, its length): 0 on it. */
1652
+ function offLine(p, foot, dir, length) {
1653
+ const d = sub(p, foot);
1654
+ const s = Math.min(length, Math.max(0, dot(d, dir)));
1655
+ return Math.hypot(d[0] - dir[0] * s, d[1] - dir[1] * s, d[2] - dir[2] * s);
1656
+ }
1657
+ const WIND_LIMBS = new WeakMap();
1658
+ /**
1659
+ * Resolves each skeleton node's wind-limb anchor without mutating `sk.order` or `sk.limb`.
1660
+ * Keeps V-fork `k = 0` arms symmetric with their `order === 1` siblings (skipping vertical
1661
+ * `FORK_APART` crotch spacers) and places `foot(n)` on the parent stem's bark collar so
1662
+ * short whorl boughs keep their full first-internode lever arm and wood collars do not tear.
1663
+ */
1664
+ function windLimbs(sk) {
1665
+ const cached = WIND_LIMBS.get(sk);
1666
+ if (cached)
1667
+ return cached;
1668
+ const kids = Array.from({ length: sk.count }, () => []);
1669
+ const queue = [];
1670
+ for (let i = 0; i < sk.count; i++) {
1671
+ const p = sk.parent[i];
1672
+ if (p < 0)
1673
+ queue.push(i);
1674
+ else
1675
+ kids[p].push(i);
1676
+ }
1677
+ const wnode = new Int32Array(sk.count).fill(-1);
1678
+ for (let q = 0; q < queue.length; q++) {
1679
+ const i = queue[q];
1680
+ for (const c of kids[i])
1681
+ queue.push(c);
1682
+ if (sk.order[i] !== 0) {
1683
+ wnode[i] = sk.limb[i];
1684
+ continue;
1685
+ }
1686
+ const p = sk.parent[i];
1687
+ if (p < 0)
1688
+ continue;
1689
+ if (wnode[p] >= 0) {
1690
+ wnode[i] = wnode[p];
1691
+ continue;
1692
+ }
1693
+ const hasForkSibling = kids[p].some((s) => s !== i && sk.order[s] === 1 && sk.radius[s] >= 0.4 * sk.radius[p]);
1694
+ if (hasForkSibling && Math.hypot(sk.x[i] - sk.x[p], sk.z[i] - sk.z[p]) > 0.08 * Math.max(0.1, sk.y[i] - sk.y[p])) {
1695
+ wnode[i] = i;
1696
+ }
1697
+ }
1698
+ const feet = new Map();
1699
+ const foot = (n) => {
1700
+ const l = wnode[n];
1701
+ if (l < 0)
1702
+ return [0, -1, 0];
1703
+ const hit = feet.get(l);
1704
+ if (hit)
1705
+ return hit;
1706
+ const p = sk.parent[l];
1707
+ let res;
1708
+ if (p < 0) {
1709
+ res = [sk.x[l], Math.max(0, sk.y[l]), sk.z[l]];
1710
+ }
1711
+ else {
1712
+ const dx = sk.x[l] - sk.x[p];
1713
+ const dy = sk.y[l] - sk.y[p];
1714
+ const dz = sk.z[l] - sk.z[p];
1715
+ const segLen = Math.hypot(dx, dy, dz);
1716
+ if (segLen < 1e-6) {
1717
+ res = [sk.x[p], Math.max(0, sk.y[p]), sk.z[p]];
1718
+ }
1719
+ else {
1720
+ const step = Math.min(0.5 * segLen, Math.max(0.02, sk.radius[p]));
1721
+ res = [sk.x[p] + (dx / segLen) * step, Math.max(0, sk.y[p] + (dy / segLen) * step), sk.z[p] + (dz / segLen) * step];
1722
+ }
1723
+ }
1724
+ feet.set(l, res);
1725
+ return res;
1726
+ };
1727
+ const wl = { node: wnode, foot };
1728
+ WIND_LIMBS.set(sk, wl);
1729
+ return wl;
1730
+ }
1731
+ function limbOf(sk, node) {
1732
+ return windLimbs(sk).foot(node);
1733
+ }
1734
+ /**
1735
+ * One sheet: `rows` rows of `SHEET_ACROSS` points from its foot along `dir`, `length` long and `half`
1736
+ * wide either side at its widest, curved as `shape` says.
1737
+ */
1738
+ function sheet(b, foot, dir, length, half, shape, own, n, depth, kind, limb, v, rows = SHEET_ALONG) {
1739
+ const up = [0, 1, 0];
1740
+ let side = cross(up, dir);
1741
+ if (Math.hypot(side[0], side[1], side[2]) < 0.2)
1742
+ side = basis(dir)[0];
1743
+ side = norm(side);
1744
+ const top = norm(cross(dir, side));
1745
+ const { lift, droop, arch, twist } = shape;
1746
+ const point = (u, s) => {
1747
+ // (Its middle line: on along the bough, up a little at first, then down to its tip as it hangs.)
1748
+ const h = length * (lift * u * (1 - u) * 2 - droop * u * u);
1749
+ const c = [foot[0] + dir[0] * length * u, foot[1] + dir[1] * length * u + h, foot[2] + dir[2] * length * u];
1750
+ // (Across it, turned about its length by its twist, more towards its tip; narrower at its foot and its tip.)
1751
+ const t = twist * u;
1752
+ const sd = add(scale(side, Math.cos(t)), scale(top, Math.sin(t)));
1753
+ const tp = sub(scale(top, Math.cos(t)), scale(side, Math.sin(t)));
1754
+ const wide = shape.point ? half * Math.max(0.03, 1 - u) ** 0.85 : half * (0.62 + 0.38 * Math.sin(Math.PI * Math.min(1, 0.15 + u * 0.95)));
1755
+ return add(add(c, scale(sd, s * wide)), scale(tp, -arch * wide * s * s));
1756
+ };
1757
+ let first = -1;
1758
+ for (let j = 0; j < rows; j++) {
1759
+ const u = j / (rows - 1);
1760
+ for (let i = 0; i < SHEET_ACROSS; i++) {
1761
+ const s = (i / (SHEET_ACROSS - 1)) * 2 - 1;
1762
+ const p = point(u, s);
1763
+ // (Its normal, from the way it runs along and across here: its top's side.)
1764
+ const e = 1e-3;
1765
+ const du = sub(point(Math.min(1, u + e), s), point(Math.max(0, u - e), s));
1766
+ const ds = sub(point(u, Math.min(1, s + e)), point(u, Math.max(-1, s - e)));
1767
+ let nrm = norm(cross(du, ds));
1768
+ if (dot(nrm, top) < 0)
1769
+ nrm = scale(nrm, -1);
1770
+ // (And where its middle line is, from it: a sheet may be turned about it, as the painterly look does.)
1771
+ const mid = point(u, 0);
1772
+ const k = b.vertex({ position: p, aDab: [s, u * 2 - 1, length / 2, own], aNormal: [...n, depth], aOffset: [...nrm, kind], aLimb: [...limb, v], aSpine: sub(mid, p) });
1773
+ if (first < 0)
1774
+ first = k;
1775
+ }
1776
+ }
1777
+ for (let j = 0; j + 1 < rows; j++) {
1778
+ for (let i = 0; i + 1 < SHEET_ACROSS; i++) {
1779
+ const q = first + j * SHEET_ACROSS + i;
1780
+ // (Wound so its top faces the way its normal does.)
1781
+ b.index.push(q, q + SHEET_ACROSS, q + SHEET_ACROSS + 1, q, q + SHEET_ACROSS + 1, q + 1);
1782
+ }
1783
+ }
1784
+ }
1785
+ /**
1786
+ * The realistic look's near leaves: each clump as `perClump` cards (close to, at least one for each of its
1787
+ * twigs), each a spray of leaves growing from the tree's own wood, its foot on one of the clump's
1788
+ * twigs, set in the crown at angles of their own (not turned to the eye: a card's face shows as it is). They face
1789
+ * out of the crown and a little up, as leaves turn to the light, each its own way about that. Each card:
1790
+ * `position` its centre; `aDab` its corner, its size (m, across half of it), a number of its own;
1791
+ * `aNormal` its clump's outward normal and depth; `aOffset` its own facing (unit) and 0; `aTangent` the
1792
+ * way its twig runs (unit, square to its facing) and how high the corner is in its clump (its radii); `aLimb` the foot of its limb and its variant. A variant
1793
+ * `skip` says is left without cards.
1794
+ */
1795
+ /**
1796
+ * A tree whose leaves lie in pads (`habit.pads` 1): its near sprays spread this much wider about their shoots
1797
+ * and this share less high, and lie this share nearer level, facing up by this much more, so a pad is a
1798
+ * shelf, flat-topped and thin.
1799
+ */
1800
+ /** A clump faces up past this when its sprays hang less there (`FixedCards.hangTop`). */
1801
+ const HANG_TOP_FROM = 0.3;
1802
+ const PAD_WIDE = 0.5;
1803
+ const PAD_FLAT = 0.75;
1804
+ const PAD_LEVEL = 0.8;
1805
+ const PAD_FACE_UP = 1.65;
1806
+ /** How far back along the wood under a clump its clothing sprays reach (m, `FixedCards.clothe`), and how big they are beside its own. */
1807
+ const CLOTHE_REACH = 3.5;
1808
+ /** A crown this far in pads is shelves (a coastal cypress's), each laid on its wood and not hung below it. */
1809
+ const PAD_SHELF = 0.8;
1810
+ const CLOTHE_SIZE = 0.8;
1811
+ export function cardPieces(trees, perClump, size, skip, fixed, rises, upright, sizes) {
1812
+ const b = new Builder({ position: 3, aDab: 4, aNormal: 4, aOffset: 4, aTangent: 4, aLimb: 4 });
1813
+ const [P, DAB, NORMAL, OFFSET, TANGENT, LIMB] = ["position", "aDab", "aNormal", "aOffset", "aTangent", "aLimb"].map((k) => b.slot(k));
1814
+ trees.forEach((tree, v) => {
1815
+ b.begin();
1816
+ if (skip?.[v]) {
1817
+ // (Its leaves are drawn as sheets: `sheetPieces`.)
1818
+ b.end();
1819
+ return;
1820
+ }
1821
+ const { clumps: cl, skeleton: sk } = tree;
1822
+ const wl = windLimbs(sk);
1823
+ const twigs = clumpTwigs(tree);
1824
+ const lines = woodLines(tree, TIER_SHAPES[0]);
1825
+ const pads = Math.min(1, Math.max(0, tree.habit?.pads ?? 0));
1826
+ for (let c = 0; c < cl.count; c++) {
1827
+ const n = [cl.nx[c], cl.ny[c], cl.nz[c]];
1828
+ const r = cl.radius[c];
1829
+ // (Its twigs in turn, the one it hangs on first. Close to, a card for each at the least: no twig of it
1830
+ // is left bare. A few broad cards a clump (mid) cover it whole, and its twigs are under a pixel there.
1831
+ // Deep in the crown, fewer: little of it shows.)
1832
+ const shoots = twigs[c].map((t) => shootOf(sk, lines, t, r * SHOOT));
1833
+ const fix = fixed?.[v] ?? null;
1834
+ // (Cards of a fixed size: as many as cover the clump as the usual ones would, the leaves' spray a card
1835
+ // fills more of than a whole clump's; the deep ones fewer, as below.)
1836
+ const own = fix ? Math.round(Math.min(fix.most, Math.max(perClump, perClump * ((r * size) / fix.half) ** 2 * fix.fill))) : perClump;
1837
+ const base = cl.depth[c] > 0.65 ? Math.max(1, own >> 1) : own;
1838
+ const count = fix ? base : perClump >= 4 ? Math.max(base, Math.min(shoots.length, 4 * perClump)) : base;
1839
+ // (With small cards, a few big ones too, a clump wide, set a little into it: the mass of its leaves, which
1840
+ // the small ones at its surface lay their detail over.)
1841
+ const big = fix ? (cl.depth[c] > 0.65 ? Math.min(1, fix.big) : fix.big) : 0;
1842
+ // (Sprays clothing the wood under it (`clothe`): along its first twig's wood, back past its own reach.)
1843
+ const clothes = fix?.clothe && cl.depth[c] <= 0.65 ? fix.clothe : 0;
1844
+ const unders = clothes > 0 ? twigs[c].slice(0, 2).map((t) => shootOf(sk, lines, t, r * SHOOT + CLOTHE_REACH)) : [];
1845
+ for (let d = 0; d < count + big + clothes; d++) {
1846
+ const clothing = d >= count + big;
1847
+ const filler = d >= count && !clothing;
1848
+ const twig = twigs[c][d % shoots.length];
1849
+ const shoot = clothing && unders.length > 0 ? unders[d % unders.length] : shoots[d % shoots.length];
1850
+ const reach = shoot.length;
1851
+ const limb = wl.foot(twig);
1852
+ const k = c * 37 + d;
1853
+ const own = hash01(k, v * 613 + 7);
1854
+ const u = hash01(k, 21) * 2 - 1;
1855
+ const a = hash01(k, 22) * Math.PI * 2;
1856
+ const s = Math.sqrt(1 - u * u);
1857
+ const off = [s * Math.cos(a), u, s * Math.sin(a)];
1858
+ // (Its foot is on the wood: on its twig, or on the last of the wood leading to it, more of them near
1859
+ // its end, and each twig's first card at its very end. A spray grows from a shoot; set about the
1860
+ // clump's centre, the cards hang in the air beside the twig, and past its end.)
1861
+ const near0 = Math.min(reach, r * SHOOT);
1862
+ const at0 = clothing ? shoot.at(near0 + (reach - near0) * ((d - count - big + hash01(k, 25)) / clothes)) : shoot.at(reach * hash01(k, 25) ** 1.6 * (d < shoots.length ? 0.2 : 1));
1863
+ // (Small cards spread through the clump about their shoots, as its side twigs carry them: else they
1864
+ // would crowd along a line or two.)
1865
+ // (In a tree whose leaves lie in pads, `habit.pads`, flattened into a shelf: wider, and thin.)
1866
+ const spread = fix && !filler ? r * (clothing ? 0.2 : 0.55) * Math.sqrt(hash01(k, 26)) : 0;
1867
+ const pineShelf = fix && (fix.rise ?? 0) >= 0.7 ? 1 : 0;
1868
+ const wide = Math.max(1 + PAD_WIDE * pads, 1 + 0.28 * pineShelf);
1869
+ const flatV = Math.min(1 - PAD_FLAT * pads, 1 - 0.55 * pineShelf);
1870
+ // (A weeping tree's sprays, `lift`, spring from as high as their clump is hung over its wood: a
1871
+ // whip's arch, its crown's clothed top. Hung from the wood, they left it bare over them.)
1872
+ const lift = fix?.lift ? Math.max(0, cl.y[c] - at0.p[1]) : 0;
1873
+ // (A pine's tufts, held up off their shoots, make a layered bough shelf rather than hanging below the branch.)
1874
+ const offUp = fix && (fix.rise ?? 0) > 0.5 ? Math.abs(off[1]) : off[1];
1875
+ const from = fix && !filler ? { p: [at0.p[0] + off[0] * spread * wide, at0.p[1] + lift + offUp * spread * flatV, at0.p[2] + off[2] * spread * wide], d: at0.d } : lift > 0 ? { p: [at0.p[0], at0.p[1] + lift, at0.p[2]], d: at0.d } : at0;
1876
+ // (A hanging spray's twig turned down, as far as the species' sprays hang: a eucalyptus's, a willow's;
1877
+ // its big cards too, the clump's hanging mass.)
1878
+ // (Less on a clump facing the sky, as far as its kind says: `hangTop`.)
1879
+ const top = Math.max(0, (n[1] - HANG_TOP_FROM) / (1 - HANG_TOP_FROM));
1880
+ const hang = fix ? fix.hang * (filler ? 0.85 : 0.75 + 0.5 * hash01(k, 27)) * (1 - (fix.hangTop ?? 0) * top) : 0;
1881
+ // (Its facing: out of the crown and up, turned its own way by as much again; a hanging spray's no
1882
+ // more up than its leaves let it, as they hang edge to the sky: a card facing up has no way down
1883
+ // along it, and its leaves would lie flat.)
1884
+ // (So too a spray that rises along its twig, half as far.)
1885
+ // (Its big cards too, and a mid card of a variant `rises` says, as far: a pine's big card is a branch's
1886
+ // cushion of tufts held up off it, flat beneath and domed above; spun any way about its facing, a blot.)
1887
+ const rise = fix ? (fix.rise ?? 0) : (rises?.[v] ?? 0);
1888
+ // (A pad's sprays face the sky, as a shelf's top does.)
1889
+ const face = norm([n[0] * 0.9 + off[0] * 0.8, (n[1] * 0.9 + off[1] * 0.8 + 0.5) * (1 - 0.85 * Math.min(1, hang)) * (1 - 0.5 * rise) + PAD_FACE_UP * pads, n[2] * 0.9 + off[2] * 0.8]);
1890
+ // (Its twig: on along the wood its foot is on, out of the crown a little, turned its own way (a
1891
+ // frond's leaves follow the frond, a whip's hang with the whip), and square to its facing.)
1892
+ const [e1, e2] = basis(face);
1893
+ const t = hash01(k, 23) * Math.PI * 2;
1894
+ const spin = [e1[0] * Math.cos(t) + e2[0] * Math.sin(t), e1[1] * Math.cos(t) + e2[1] * Math.sin(t), e1[2] * Math.cos(t) + e2[2] * Math.sin(t)];
1895
+ // (A rising spray's shoots point out of the crown as well as up: a pine's tufts bristle from its outline.)
1896
+ const out = 0.3 + 0.5 * rise;
1897
+ const along0 = [from.d[0] + spin[0] * 0.6 * (1 - 0.5 * rise) + n[0] * out, from.d[1] + spin[1] * 0.6 * (1 - 0.5 * rise) + n[1] * out + rise, from.d[2] + spin[2] * 0.6 * (1 - 0.5 * rise) + n[2] * out];
1898
+ const l0 = Math.hypot(along0[0], along0[1], along0[2]) || 1;
1899
+ // (A pad's sprays, its big cards too, lie level: from the side a pad is a band of them, not a ball.)
1900
+ const level = 1 - PAD_LEVEL * pads * (1 - Math.min(1, rise));
1901
+ const along = [(along0[0] / l0) * (1 - hang), ((along0[1] / l0) * (1 - hang) - hang) * level, (along0[2] / l0) * (1 - hang)];
1902
+ const dotF = along[0] * face[0] + along[1] * face[1] + along[2] * face[2];
1903
+ const flat = [along[0] - face[0] * dotF, along[1] - face[1] * dotF, along[2] - face[2] * dotF];
1904
+ // (A variant `upright` says stands its big cards (a near tree's, every one of a mid tree's) upright on
1905
+ // their twigs, facing out of the crown level: a pine's cushion picture, its flat base kept level, which the
1906
+ // shader turns to the eye about the vertical.)
1907
+ const stands = upright?.[v] === true && (!fix || filler);
1908
+ const tangent = stands ? [0, 1, 0] : Math.hypot(flat[0], flat[1], flat[2]) > 1e-3 ? norm(flat) : norm(spin);
1909
+ const facing = stands ? (Math.hypot(n[0], n[2]) > 1e-3 ? norm([n[0], 0, n[2]]) : norm([off[0] + 1e-3, 0, off[2]])) : face;
1910
+ // (A variant's own size for its cards where `sizes` gives one: a stone pine's mid cards, strips of its canopy.)
1911
+ // (Upright cushions vary more, and stand at heights of their own about their twigs, a half of the
1912
+ // clump's radius up or down: at one height, a crown of them seen from beneath was rings of plates.)
1913
+ const vary = stands ? CUSHION_VARY : 0.4;
1914
+ const half = (fix && !filler ? fix.half * (clothing ? CLOTHE_SIZE : 1) : fix ? r * fix.bigSize : r * (sizes?.[v] ?? size)) * (1 - vary / 2 + hash01(k, 24) * vary);
1915
+ // (The spray's own twig enters its picture near the bottom edge (leaves.ts): its centre is that far
1916
+ // on from its foot.)
1917
+ // (A shelf (a crown in pads, `pads` 0.8 or more) only up from its wood: dropped under it, it hung below its own
1918
+ // limb, the limb running on bare above it.)
1919
+ const upDown = pads >= PAD_SHELF ? 0.5 * hash01(k, 28) : hash01(k, 28) - 0.5;
1920
+ const on = half * SPRAY_FOOT + (stands ? upDown * r * CUSHION_RISE : 0);
1921
+ const at = [from.p[0] + tangent[0] * on, from.p[1] + tangent[1] * on, from.p[2] + tangent[2] * on];
1922
+ let f = -1;
1923
+ for (const [cx, cy] of CORNERS) {
1924
+ // (How high the corner is in its clump, in the clump's radii: along the twig, which the card keeps
1925
+ // however it is turned to the eye. A dense clump's needles low in it are in its own shade.)
1926
+ const inClump = Math.max(-1.5, Math.min(1.5, (at[1] + tangent[1] * cy * half - cl.y[c]) / Math.max(r, 1e-3)));
1927
+ b.putAt(P, at[0], at[1], at[2]);
1928
+ b.putAt(DAB, cx, cy, half, own);
1929
+ b.putAt(NORMAL, n[0], n[1], n[2], cl.depth[c]);
1930
+ b.putAt(OFFSET, facing[0], facing[1], facing[2], filler ? 1 : 0);
1931
+ b.putAt(TANGENT, tangent[0], tangent[1], tangent[2], inClump);
1932
+ b.putAt(LIMB, limb[0], limb[1], limb[2], v);
1933
+ const i = b.next();
1934
+ if (f < 0)
1935
+ f = i;
1936
+ }
1937
+ b.index.push(f, f + 1, f + 2, f, f + 2, f + 3);
1938
+ }
1939
+ }
1940
+ b.end();
1941
+ });
1942
+ return b.done();
1943
+ }
1944
+ //# sourceMappingURL=geometry.js.map