@casmo/tree.js 0.2.0 → 0.4.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 (164) hide show
  1. package/README.md +392 -1
  2. package/dist/{apply-CcodnAbs.js → apply-Cio2t7CZ.js} +51 -16
  3. package/dist/apply-Cio2t7CZ.js.map +1 -0
  4. package/dist/bake/index.d.ts +43 -4
  5. package/dist/bake/index.d.ts.map +1 -1
  6. package/dist/definition/defaults.d.ts +9 -1
  7. package/dist/definition/defaults.d.ts.map +1 -1
  8. package/dist/definition/index.d.ts +2 -2
  9. package/dist/definition/index.d.ts.map +1 -1
  10. package/dist/definition/schema.d.ts.map +1 -1
  11. package/dist/definition/types.d.ts +86 -0
  12. package/dist/definition/types.d.ts.map +1 -1
  13. package/dist/effects/effects.d.ts +51 -6
  14. package/dist/effects/effects.d.ts.map +1 -1
  15. package/dist/effects/glow.d.ts +5 -0
  16. package/dist/effects/glow.d.ts.map +1 -1
  17. package/dist/effects/grade.d.ts +3 -0
  18. package/dist/effects/grade.d.ts.map +1 -1
  19. package/dist/effects/highlight.d.ts +35 -0
  20. package/dist/effects/highlight.d.ts.map +1 -0
  21. package/dist/effects/index.d.ts +5 -1
  22. package/dist/effects/index.d.ts.map +1 -1
  23. package/dist/effects/inner-lines.d.ts +39 -0
  24. package/dist/effects/inner-lines.d.ts.map +1 -0
  25. package/dist/effects/live.d.ts +12 -0
  26. package/dist/effects/live.d.ts.map +1 -0
  27. package/dist/effects/mask.d.ts +23 -11
  28. package/dist/effects/mask.d.ts.map +1 -1
  29. package/dist/effects/outline.d.ts +12 -0
  30. package/dist/effects/outline.d.ts.map +1 -1
  31. package/dist/effects/pass.d.ts +27 -0
  32. package/dist/effects/pass.d.ts.map +1 -0
  33. package/dist/effects/screen.d.ts +31 -0
  34. package/dist/effects/screen.d.ts.map +1 -0
  35. package/dist/effects/suggested.d.ts +5 -0
  36. package/dist/effects/suggested.d.ts.map +1 -1
  37. package/dist/effects/tree-id.d.ts +50 -0
  38. package/dist/effects/tree-id.d.ts.map +1 -0
  39. package/dist/effects.js +772 -57
  40. package/dist/effects.js.map +1 -1
  41. package/dist/forest/Forest.d.ts +29 -1
  42. package/dist/forest/Forest.d.ts.map +1 -1
  43. package/dist/forest/nodes.d.ts +2 -0
  44. package/dist/forest/nodes.d.ts.map +1 -1
  45. package/dist/{forest-DTrD8puH.js → forest-lg61rhKM.js} +1125 -191
  46. package/dist/forest-lg61rhKM.js.map +1 -0
  47. package/dist/generator/crown.d.ts +28 -0
  48. package/dist/generator/crown.d.ts.map +1 -0
  49. package/dist/generator/growth.d.ts +1 -1
  50. package/dist/generator/growth.d.ts.map +1 -1
  51. package/dist/generator/index.d.ts +2 -1
  52. package/dist/generator/index.d.ts.map +1 -1
  53. package/dist/generator/mesh.d.ts +10 -2
  54. package/dist/generator/mesh.d.ts.map +1 -1
  55. package/dist/generator/occlusion.d.ts +8 -0
  56. package/dist/generator/occlusion.d.ts.map +1 -0
  57. package/dist/generator/roots.d.ts +16 -0
  58. package/dist/generator/roots.d.ts.map +1 -0
  59. package/dist/generator/trunk.d.ts +8 -0
  60. package/dist/generator/trunk.d.ts.map +1 -1
  61. package/dist/generator/types.d.ts +27 -1
  62. package/dist/generator/types.d.ts.map +1 -1
  63. package/dist/growth/index.d.ts +1 -1
  64. package/dist/growth/index.d.ts.map +1 -1
  65. package/dist/growth/tsl.d.ts +2 -0
  66. package/dist/growth/tsl.d.ts.map +1 -1
  67. package/dist/index.d.ts +4 -3
  68. package/dist/index.d.ts.map +1 -1
  69. package/dist/index.js +234 -28
  70. package/dist/index.js.map +1 -1
  71. package/dist/materials/crown-nodes.d.ts +20 -0
  72. package/dist/materials/crown-nodes.d.ts.map +1 -0
  73. package/dist/materials/crown-normals.d.ts +17 -0
  74. package/dist/materials/crown-normals.d.ts.map +1 -0
  75. package/dist/materials/ground-tint.d.ts +13 -0
  76. package/dist/materials/ground-tint.d.ts.map +1 -0
  77. package/dist/materials/index.d.ts +7 -1
  78. package/dist/materials/index.d.ts.map +1 -1
  79. package/dist/materials/leaf-translucency-model.d.ts +14 -0
  80. package/dist/materials/leaf-translucency-model.d.ts.map +1 -0
  81. package/dist/materials/leaf-translucency.d.ts +73 -0
  82. package/dist/materials/leaf-translucency.d.ts.map +1 -0
  83. package/dist/materials/material-features.d.ts +43 -0
  84. package/dist/materials/material-features.d.ts.map +1 -0
  85. package/dist/materials/occlusion.d.ts +10 -0
  86. package/dist/materials/occlusion.d.ts.map +1 -0
  87. package/dist/materials/toon.d.ts +18 -1
  88. package/dist/materials/toon.d.ts.map +1 -1
  89. package/dist/{names-C6-wuJ29.js → names-BE9he6CS.js} +133 -9
  90. package/dist/names-BE9he6CS.js.map +1 -0
  91. package/dist/react.js +1 -1
  92. package/dist/species/almond.js +12 -2
  93. package/dist/species/almond.json +10 -1
  94. package/dist/species/apple.js +12 -2
  95. package/dist/species/apple.json +10 -1
  96. package/dist/species/ash.js +12 -2
  97. package/dist/species/ash.json +10 -1
  98. package/dist/species/beech.js +12 -2
  99. package/dist/species/beech.json +10 -1
  100. package/dist/species/birch.js +12 -2
  101. package/dist/species/birch.json +10 -1
  102. package/dist/species/cedar.js +12 -2
  103. package/dist/species/cedar.json +10 -1
  104. package/dist/species/cherry.js +12 -2
  105. package/dist/species/cherry.json +10 -1
  106. package/dist/species/chestnut.js +12 -2
  107. package/dist/species/chestnut.json +10 -1
  108. package/dist/species/douglas-fir.js +12 -2
  109. package/dist/species/douglas-fir.json +10 -1
  110. package/dist/species/elm.js +12 -2
  111. package/dist/species/elm.json +10 -1
  112. package/dist/species/hemlock.js +12 -2
  113. package/dist/species/hemlock.json +10 -1
  114. package/dist/species/hickory.js +12 -2
  115. package/dist/species/hickory.json +10 -1
  116. package/dist/species/juniper.js +12 -2
  117. package/dist/species/juniper.json +10 -1
  118. package/dist/species/mahogany.js +12 -2
  119. package/dist/species/mahogany.json +10 -1
  120. package/dist/species/maple.js +12 -2
  121. package/dist/species/maple.json +10 -1
  122. package/dist/species/oak.js +12 -2
  123. package/dist/species/oak.json +10 -1
  124. package/dist/species/olive.js +12 -2
  125. package/dist/species/olive.json +10 -1
  126. package/dist/species/peach.js +12 -2
  127. package/dist/species/peach.json +10 -1
  128. package/dist/species/pear.js +12 -2
  129. package/dist/species/pear.json +10 -1
  130. package/dist/species/pine.js +12 -2
  131. package/dist/species/pine.json +10 -1
  132. package/dist/species/plum.js +12 -2
  133. package/dist/species/plum.json +10 -1
  134. package/dist/species/red-oak.js +12 -2
  135. package/dist/species/red-oak.json +10 -1
  136. package/dist/species/redwood.js +12 -2
  137. package/dist/species/redwood.json +10 -1
  138. package/dist/species/sequoia.js +12 -2
  139. package/dist/species/sequoia.json +10 -1
  140. package/dist/species/spruce.js +12 -2
  141. package/dist/species/spruce.json +10 -1
  142. package/dist/species/teak.js +12 -2
  143. package/dist/species/teak.json +10 -1
  144. package/dist/species/types.d.ts +7 -3
  145. package/dist/species/types.d.ts.map +1 -1
  146. package/dist/species/walnut.js +12 -2
  147. package/dist/species/walnut.json +10 -1
  148. package/dist/species/white-oak.js +12 -2
  149. package/dist/species/white-oak.json +10 -1
  150. package/dist/styles/apply.d.ts.map +1 -1
  151. package/dist/styles/low-poly.js +6 -4
  152. package/dist/styles/low-poly.js.map +1 -1
  153. package/dist/styles/material-features.d.ts +27 -0
  154. package/dist/styles/material-features.d.ts.map +1 -0
  155. package/dist/styles/realistic.js +6 -4
  156. package/dist/styles/realistic.js.map +1 -1
  157. package/dist/styles/stylized.js +6 -4
  158. package/dist/styles/stylized.js.map +1 -1
  159. package/dist/tree/Tree.d.ts +28 -1
  160. package/dist/tree/Tree.d.ts.map +1 -1
  161. package/package.json +1 -1
  162. package/dist/apply-CcodnAbs.js.map +0 -1
  163. package/dist/forest-DTrD8puH.js.map +0 -1
  164. package/dist/names-C6-wuJ29.js.map +0 -1
package/README.md CHANGED
@@ -17,10 +17,12 @@ thousands at once as an instanced Forest, add opt-in Tree Effects, or design you
17
17
  - [Growth and Season](#growth-and-season)
18
18
  - [Wind](#wind)
19
19
  - [Forests](#forests)
20
+ - [Material Features](#material-features)
20
21
  - [Tree Effects](#tree-effects)
21
22
  - [React Three Fiber](#react-three-fiber)
22
23
  - [Without a bundler: import map (CDN)](#without-a-bundler-import-map-cdn)
23
24
  - [Baked Trees (glTF export)](#baked-trees-gltf-export)
25
+ - [Using a Baked Tree in other engines](#using-a-baked-tree-in-other-engines)
24
26
  - [Textures](#textures)
25
27
  - [Tree Editor](#tree-editor)
26
28
  - [Examples](#examples)
@@ -226,6 +228,83 @@ trunks (each with the whole branch structure) in a small ring, leaning out about
226
228
  Seed varies each lean). `trunk.gravity` (−1..1) bends only the leader, the top third of each Stem: −1 makes
227
229
  it nod like a hemlock's. Absent, a tree has one upright Stem without gravity.
228
230
 
231
+ A **Root Flare** widens each Stem towards the ground: `trunk.flare` (0..1) eases the bottom ~12% of the
232
+ Stem's length out to (1 + 0.8 × `flare`) × the trunk radius at the base, so the trunk grows into the soil
233
+ instead of standing on it like a post. It is geometry only: branches, leaves, Fruit, Growth, Wind and Sculpts
234
+ stay exactly where they were. The optional `flareSections` (integer ≥ 1) is how many extra rings the flare
235
+ gets, set by `Style.apply` (2 in low-poly, 3 in the others; absent = 3). Absent `flare` means none. Every
236
+ trunk's base ring sits a tenth of its radius below the ground (also without flare), so no seam shows on
237
+ uneven terrain:
238
+
239
+ ```ts
240
+ import { createTree, extendDefinition, type TreeDefinitionInput } from '@casmo/tree.js';
241
+
242
+ const oak: TreeDefinitionInput = { schemaVersion: 3, trunk: { length: 5, radius: 0.35, flare: 0.8 } };
243
+ const flared = createTree(oak, { seed: 3 });
244
+ const slender = extendDefinition(oak, { trunk: { flare: 0.15 } }); // a hint of a flare, same crown
245
+ ```
246
+
247
+ **Roots** are an optional `roots` block: a few Roots grow from the Root Flare of every Stem, run outward
248
+ and down, taper to a point and vanish below the ground. `count` is Roots per Stem (0..12), `length` a
249
+ fraction of the Stem's length (`lengthVariation` is the Seed's ± range), `radius` a fraction of the trunk's
250
+ base radius, `angle` how steeply they dive (degrees below horizontal, 0..60) and `bend` how much they wander
251
+ sideways. A partial block is filled from `DEFAULT_ROOTS` (5 Roots, length 0.25, radius 0.35, angle 12°);
252
+ absent means none. A single Stem's Roots spread all round it; with several Stems each Stem's Roots cover
253
+ only the half-circle facing away from the others. Roots follow the Sculpts of their Stem: a deleted Stem has
254
+ none, a turned Stem keeps them on the ground at its base, a scaled one scales them with its length, and
255
+ another Stem's Roots never change. The optional `sides` and `sections` are their polygon detail, set by `Style.apply`
256
+ (realistic 8 / 6, stylized 6 / 4, low-poly 3 / 2). Roots are part of the wood mesh, grow with the trunk from
257
+ Growth 0, never sway in the Wind and cannot be Sculpted; adding or removing them leaves the branches,
258
+ leaves and Fruit exactly as they were. The tree data lists them in `skeleton.roots` (`SkeletonRoot` entries
259
+ with paths `0/r0`, `0/r1`, ... and their Stem as `parent`) with their Growth windows in `growth.roots`:
260
+
261
+ ```ts
262
+ import { createTree, DEFAULT_ROOTS, type SkeletonRoot } from '@casmo/tree.js';
263
+
264
+ const rooted = createTree({ schemaVersion: 3, trunk: { flare: 0.6 }, roots: { count: 7, angle: 10 } }, { seed: 3 });
265
+ const roots: SkeletonRoot[] = rooted.data.skeleton.roots; // 7 Roots: '0/r0' .. '0/r6', parent '0'
266
+ const tips = roots.map((root) => root.points.at(-1)!.position); // all below the ground (y < 0)
267
+ const windows = rooted.data.growth.roots; // { start: 0, end: 0 }: there from Growth 0, like the trunk
268
+ const defaults = DEFAULT_ROOTS; // { count: 5, length: 0.25, lengthVariation: 0.3, radius: 0.35, angle: 12, bend: 0.3 }
269
+ ```
270
+
271
+ A **Ground Tint** darkens the bark or turns it mossy near the soil: the optional
272
+ `materials.bark.groundTint = { color, height, strength }`. At and below the ground the bark colour blends
273
+ towards `color` by `strength` (0..1); the blend fades smoothly to nothing `height` metres (> 0) up the Stem.
274
+ It works in every shading model (standard, flat, toon), is measured on the grown tree (a sapling's tint
275
+ reaches as high, in metres, as a grown tree's) and is baked into the wood's vertex colours of a Baked Tree.
276
+ A partial block is filled from `DEFAULT_GROUND_TINT` (height 0.5 m); absent means none, and no Species sets
277
+ one. It is not part of a Style's look, so `Style.apply` on a Definition keeps it:
278
+
279
+ ```ts
280
+ import { createTree, DEFAULT_GROUND_TINT, extendDefinition } from '@casmo/tree.js';
281
+ import realistic from '@casmo/tree.js/styles/realistic';
282
+ import { oak } from '@casmo/tree.js/species';
283
+
284
+ const mossy = extendDefinition(realistic.apply(oak), {
285
+ materials: { bark: { groundTint: { color: '#4d6a26', height: 0.8, strength: 0.7 } } },
286
+ });
287
+ const tree = createTree(mossy, { seed: 3 });
288
+ const wet = extendDefinition(mossy, { materials: { bark: { groundTint: { color: '#1e1610' } } } }); // dark wet bark
289
+ const defaults = DEFAULT_GROUND_TINT; // { color: '#3f4a2a', height: 0.5, strength: 0.6 }
290
+ ```
291
+
292
+ The **Crown Volume** is one smooth ellipsoid around all leaves of the fully grown tree (every Stem's
293
+ together), fitted as tightly as an axis-aligned ellipsoid can be. The Generator always computes it,
294
+ deterministically per Definition and Seed, and keeps it next to the geometry as `data.crown = { center, radii }`
295
+ (tree space, metres), so the meshes and `hashTreeData` are unchanged. Use it in your own shaders or
296
+ gameplay: `crownDistance` is 0 at its centre, 1 on its shell and more outside, and `crownNormal` is the
297
+ ellipsoid's outward normal through a point. A tree without leaves gets a Volume around its branches.
298
+
299
+ ```ts
300
+ import { createTree, crownDistance, crownNormal, type CrownVolume } from '@casmo/tree.js';
301
+
302
+ const tree = createTree({ schemaVersion: 3 }, { seed: 3 });
303
+ const crown: CrownVolume = tree.data.crown; // { center: [x, y, z], radii: [rx, ry, rz] }
304
+ const inside = crownDistance(crown, [0, 4, 0]) <= 1; // is this point within the crown?
305
+ const outward = crownNormal(crown, [0, 4, 0]); // unit normal of the ellipsoid through the point
306
+ ```
307
+
229
308
  **Fruit** is an optional `fruit` block: `type` (`'round'`, `'pear'`, `'nut'`, `'cone'` or `'berry'`),
230
309
  `count` per outermost twig, `size`, `sizeVariation` and `hang` (0 = sits on the twig .. 1 = hangs
231
310
  straight down). A fractional `count` is a chance per twig: `0.3` puts one Fruit on about 30% of the
@@ -343,6 +422,97 @@ if (hit) console.log(forest.treeAt(hit)?.key);
343
422
 
344
423
  `forest.dispose()` frees everything. `forest.ready` resolves once its textures have loaded.
345
424
 
425
+ ## Material Features
426
+
427
+ ![The same stylized tree without (left) and with (right) the suggested Material Features: the crown is lit as one rounded shape, glows at its edge against the low sun and is darker inside](docs/images/material-features.png)
428
+
429
+ *The same tree and lights, without (left) and with (right) `SUGGESTED_MATERIAL_FEATURES.stylized`.*
430
+
431
+ Material Features make a crown read as one soft volume instead of a noise of leaf cards. There are
432
+ three, each an optional field in the Definition's `materials` section:
433
+
434
+ | Field | Range | What it does |
435
+ | --- | --- | --- |
436
+ | `materials.leaf.crownNormals` | 0..1 | **Crown Normals**: each leaf's normal is blended towards the [Crown Volume](#tree-definitions-and-seeds)'s, so the crown is lit as one rounded shape (0 = each leaf on its own .. 1 = fully). With flat shading the facets stay visible below 1. |
437
+ | `materials.leaf.translucency` | `{ strength, edge, ambient }`, each 0..1 | **Leaf Translucency**: leaves glow in their own Season colour when you look towards a light through them. `strength` per direct light (shadowed leaves don't glow), `edge` = how much more the thin edge of the crown glows than its inside, `ambient` = the sky shining through, dimmed by occlusion. Leaves only, never bark or Fruit. |
438
+ | `materials.occlusion` | `{ strength }`, 0..1 | **Structural Occlusion**: the inside of the crown and the trunk under it get less ambient light. Worked out once from the tree's shape (baked per vertex, the same for every Season), for wood, leaves and Fruit. Changing `strength` doesn't regenerate the tree. |
439
+
440
+ **They are strictly opt-in and pass-free.** Absent means off, and no built-in Style or Species turns one
441
+ on, so a game that sets nothing sees exactly the trees it saw before (same geometry, attributes and
442
+ materials). Turning one on only changes the tree's own node materials: your renderer, scene, lights and
443
+ post-processing are left alone, and there is no extra render pass, only some shader math per pixel. They
444
+ work in every Style (flat, standard and toon shading), with Growth and Wind, and in Forests.
445
+
446
+ Each Style has suggested values. Opt in with one line: `withMaterialFeatures(definition, features)`
447
+ returns a new Definition whose Material Features are exactly `features` (a feature you leave out is off,
448
+ `{}` turns them all off) and leaves its input unchanged:
449
+
450
+ ```ts
451
+ import { createTree, SUGGESTED_MATERIAL_FEATURES, withMaterialFeatures } from '@casmo/tree.js';
452
+ import { oak } from '@casmo/tree.js/species';
453
+ import realistic from '@casmo/tree.js/styles/realistic';
454
+ import stylized from '@casmo/tree.js/styles/stylized';
455
+
456
+ const tree = createTree(withMaterialFeatures(stylized.broadleaf, SUGGESTED_MATERIAL_FEATURES.stylized), { seed: 3 });
457
+
458
+ // Or your own values, e.g. only a little crown shading and occlusion:
459
+ const subtle = withMaterialFeatures(realistic.apply(oak), { crownNormals: 0.4, occlusion: { strength: 0.5 } });
460
+ const off = withMaterialFeatures(subtle, {}); // the plain Style tree again
461
+ ```
462
+
463
+ | Style | `crownNormals` | `translucency` | `occlusion` |
464
+ | --- | --- | --- | --- |
465
+ | `low-poly` | 0.5 | (off: it would soften the flat look) | `{ strength: 0.8 }` |
466
+ | `stylized` | 1 | `{ strength: 0.3, edge: 0.8, ambient: 0.2 }` | `{ strength: 0.9 }` |
467
+ | `realistic` | 0.6 | `{ strength: 0.45, edge: 0.7, ambient: 0.25 }` | `{ strength: 0.9 }` |
468
+
469
+ The fields are plain numbers, so they are saved in the Definition JSON (the Tree Editor exports them) and
470
+ can be set with `extendDefinition` too (`{ materials: { leaf: { crownNormals: 1 } } }`). Validation
471
+ rejects values outside 0..1.
472
+
473
+ **Tuning live.** A feature that is on can be retuned on a Tree or Forest without regenerating it: the
474
+ values are uniforms, so there is no new geometry and no recompile. Values are clamped to 0..1; setting a
475
+ feature that is off throws (switching one on or off needs a new Tree or Forest). A Baked Tree is baked
476
+ with the values as tuned.
477
+
478
+ ```ts
479
+ import { createTree, SUGGESTED_MATERIAL_FEATURES, withMaterialFeatures } from '@casmo/tree.js';
480
+ import stylized from '@casmo/tree.js/styles/stylized';
481
+
482
+ const tree = createTree(withMaterialFeatures(stylized.broadleaf, SUGGESTED_MATERIAL_FEATURES.stylized));
483
+ tree.crownNormals = 0.8; // number | null (null = off)
484
+ tree.translucency = { strength: 0.6 }; // any of strength, edge, ambient; the others are kept
485
+ tree.occlusionStrength = 0.5; // number | null
486
+ tree.materialFeatures; // { crownNormals?, translucency?, occlusion? } as tuned now
487
+ ```
488
+
489
+ **With your SSAO/GTAO.** Structural Occlusion is the materials' built-in ambient occlusion (`aoNode`),
490
+ so it darkens ambient and indirect light only (sunlit sides stay sunlit) and three.js multiplies it
491
+ with screen-space AO the same way it does for any material. Your SSAO pass needs no changes; trees simply
492
+ bring their own occlusion, including the inside of the crown, which screen-space AO can't see:
493
+
494
+ ```ts
495
+ import * as THREE from 'three/webgpu';
496
+ import { builtinAOContext, mrt, normalView, output, pass, screenUV } from 'three/tsl';
497
+ import { ao } from 'three/addons/tsl/display/GTAONode.js';
498
+
499
+ const prePass = pass(scene, camera);
500
+ prePass.setMRT(mrt({ output, normal: normalView }));
501
+ const gtao = ao(prePass.getTextureNode('depth'), prePass.getTextureNode('normal'), camera);
502
+
503
+ const scenePass = pass(scene, camera);
504
+ // GTAO and the trees' Structural Occlusion are multiplied together, for ambient light only.
505
+ scenePass.contextNode = builtinAOContext(gtao.getTextureNode().sample(screenUV).r);
506
+
507
+ const pipeline = new THREE.RenderPipeline(renderer);
508
+ pipeline.outputNode = scenePass;
509
+ renderer.setAnimationLoop(() => pipeline.render());
510
+ ```
511
+
512
+ Material Features are a different thing from [Tree Effects](#tree-effects): those are post-processing
513
+ (the "leaf glow" effect is a screen-space bloom, not Leaf Translucency). See them side by side per Style in
514
+ [`examples/material-features`](examples/material-features/main.ts).
515
+
346
516
  ## Tree Effects
347
517
 
348
518
  ![A stylized tree, a rock and a crate without (left) and with (right) the stylized Tree Effects: only the tree gets an outline and colour grading](docs/images/effects.png)
@@ -362,6 +532,19 @@ renderer.setAnimationLoop(() => effects.render()); // instead of renderer.render
362
532
  effects.set({ outline: { color: '#203018', thickness: 2 }, grade: { saturation: 1.1 } }); // or null = none
363
533
  ```
364
534
 
535
+ Each Style has a suggested combination (`SUGGESTED_TREE_EFFECTS`): `low-poly` has a colour grade, ink
536
+ [Inner Lines](#inner-lines) and a dark outline that is also drawn [between overlapping trees](#outline-between-overlapping-trees);
537
+ `stylized` has a warm grade, a leaf glow, soft Inner Lines and a soft outline; `realistic` only a gentle
538
+ grade and a faint leaf glow (no ink).
539
+
540
+ > **Changed in this release:** the `low-poly` and `stylized` suggestions now include Inner Lines, and
541
+ > `low-poly` also `outline.betweenTrees`. Apps that use either suggestion get a changed look (ink lines
542
+ > inside the crown, and for low-poly between overlapping trees) and extra channels in the scene pass:
543
+ > the `normal` channel for both, and for low-poly also the [Tree ID](#tree-id) channel (a scene pass with
544
+ > the Tree ID renders without MSAA). In your own pipeline, request those channels from `treeEffectsPass`
545
+ > (see below). Use your own settings, e.g. `{ ...SUGGESTED_TREE_EFFECTS.stylized, innerLines: undefined }`,
546
+ > to keep the old look.
547
+
365
548
  Pass `selection: [tree]` to outline only some trees. In your own pipeline, the effects are nodes that
366
549
  compose with your other effects:
367
550
 
@@ -371,7 +554,8 @@ import { float, screenUV, vec4 } from 'three/tsl';
371
554
  import { applyTreeEffects, SUGGESTED_TREE_EFFECTS, treeEffectsPass } from '@casmo/tree.js/effects';
372
555
 
373
556
  const pipeline = new THREE.RenderPipeline(renderer);
374
- const input = treeEffectsPass(scene, camera); // { pass, color, mask }
557
+ // The low-poly suggestion's Inner Lines need the normal channel, its betweenTrees outline the Tree ID.
558
+ const input = treeEffectsPass(scene, camera, null, { normal: true, treeId: true }); // { pass, color, mask, ... }
375
559
  const trees = applyTreeEffects(input, SUGGESTED_TREE_EFFECTS['low-poly']); // or treeOutline / leafGlow / treeColorGrade
376
560
  const vignette = float(1).sub(screenUV.sub(0.5).length().mul(0.9).pow(2)); // your own effect on top
377
561
  pipeline.outputNode = vec4(trees.rgb.mul(vignette), 1);
@@ -381,6 +565,177 @@ renderer.setAnimationLoop(() => pipeline.render());
381
565
  To add the tree mask to a scene pass you already have, merge `treeMaskMRT()` into its MRT and read the
382
566
  mask with `scenePass.getTextureNode(TREE_MASK)`.
383
567
 
568
+ ### Tree ID
569
+
570
+ To tell trees apart on screen (GPU picking, your own per-tree effects), add the opt-in **Tree ID**
571
+ channel: an extra MRT target in which every tree writes its own number. Each Tree has one ID for all
572
+ its parts (wood, leaves, Fruit), and each tree of a Forest has its own. Nothing else changes: the tree
573
+ mask, its format and the `treeEffectsPass` default stay as they are.
574
+
575
+ ```ts
576
+ import { mrt, output, pass } from 'three/tsl';
577
+ import { readTreeId, TREE_ID, treeFromId, treeIdMRT, treeIdTexture, treeMaskMRT } from '@casmo/tree.js/effects';
578
+
579
+ const scenePass = pass(scene, camera);
580
+ scenePass.setMRT(mrt({ output }).merge(treeMaskMRT()).merge(treeIdMRT()));
581
+ treeIdTexture(scenePass); // makes the target one 32-bit unsigned integer per pixel
582
+ const ids = scenePass.getTextureNode(TREE_ID); // read it with exact texel loads (ids.load(...)), never filtered
583
+
584
+ renderer.domElement.addEventListener('click', async (event) => {
585
+ const id = await readTreeId(renderer, scenePass, event.offsetX, event.offsetY); // CSS pixels
586
+ const tree = treeFromId(id); // the Tree or ForestTree, or undefined (0 = no tree)
587
+ });
588
+ ```
589
+
590
+ - **Encoding:** `r32uint`, 0 = not a tree. A Forest Variant reserves a block of IDs the size of its
591
+ capacity, and its trees write block start + instance index.
592
+ - **No MSAA:** an integer target cannot be multisampled, so turning on the Tree ID turns MSAA off on
593
+ that scene pass: `treeIdTexture` sets `samples: 0`, also with an `antialias: true` renderer. This
594
+ applies wherever the ID channel is on: `treeIdTexture`, `treeEffectsPass(..., { treeId: true })`,
595
+ and in `TreeEffects` the `treeId: true` option, `outline.betweenTrees`, `highlight` and the
596
+ `low-poly` suggestion (which uses `betweenTrees`). Add FXAA or SMAA after the pass if you need
597
+ smooth edges there.
598
+ - **Limits:** IDs are handed out by one registry for the whole page on first use: the first time a
599
+ tree is drawn with the channel or asked for with `treeIdOf(tree)`, whichever comes first. They are
600
+ never reused: about 4.29 billion per session. The registry keeps no tree alive. The ID ignores the
601
+ outline's `selection`.
602
+ - **Frame-relative:** a Forest tree's ID follows its instance slot. Removing a tree (the last tree
603
+ moves into its slot) or a Variant growing past its capacity can change the IDs of other trees. So
604
+ resolve an ID with `treeFromId` in the frame it was read, and ask `treeIdOf(tree)` for a tree's
605
+ current ID; a removed tree resolves to `undefined`.
606
+ - `readTreeId` reads the pixel under a point of the canvas from the last render of the pass (it
607
+ handles the target's index, the y flip and the device pixel ratio). It works on WebGPU and on the
608
+ WebGL2 fallback.
609
+ - **WebGL2 fallback:** three clears every target there as floats, which is invalid for an integer
610
+ target, so `treeIdTexture` makes the pass clear the ID target itself right before every render (a
611
+ frame with nothing drawn reads 0). three's own clear still logs a GL warning
612
+ (a `GL_INVALID_OPERATION` from `clearBufferfv`) in the console each frame; it is harmless.
613
+
614
+ #### Picking with `TreeEffects` and the opt-in channels
615
+
616
+ The ready-made pipeline only renders the channels its settings need. Without them (`effects: null`,
617
+ or grade, glow and outline without `betweenTrees`) the scene pass is exactly `{ output, treeMask }` with the 8-bit mask, as
618
+ always. Pass `treeId: true` to keep the Tree ID channel on without any effect needing it, then pick
619
+ with one call:
620
+
621
+ ```ts
622
+ import { createTreeEffects } from '@casmo/tree.js/effects';
623
+
624
+ const effects = createTreeEffects(renderer, scene, camera, { effects: 'stylized', treeId: true });
625
+ renderer.domElement.addEventListener('pointermove', async (event) => {
626
+ const tree = await effects.pick(event.offsetX, event.offsetY); // Tree, ForestTree or undefined
627
+ });
628
+ ```
629
+
630
+ `pick` reads the ID from the last render and resolves it right away (IDs are frame-relative). Without
631
+ the Tree ID channel it throws an error that names the `treeId` option. The scene pass's MRT (and with
632
+ it the compiled materials of your scene) only changes when `set()` needs a different set of channels;
633
+ switching between settings that need the same channels keeps it. When the channels do change,
634
+ `effects.scenePass` is a new pass (three cannot remove a target from a pass, nor turn MSAA back on
635
+ for it), so read `effects.scenePass` again after such a `set()` instead of keeping the old one. In your own pipeline,
636
+ `treeEffectsPass(scene, camera, selection, { treeId: true })` adds the channel and fills in the
637
+ effects' `treeId` input.
638
+
639
+ #### Outline between overlapping trees
640
+
641
+ By default the outline goes around all trees together, so trees that overlap on screen merge into one
642
+ shape. With `betweenTrees` the outline is also drawn where a tree lies in front of another one, for a
643
+ Tree and a Tree, two Forest trees, or a Tree and a Forest tree:
644
+
645
+ ```ts
646
+ import { createTreeEffects } from '@casmo/tree.js/effects';
647
+
648
+ const effects = createTreeEffects(renderer, scene, camera, {
649
+ effects: { outline: { color: '#18230f', thickness: 2, betweenTrees: true } },
650
+ });
651
+ ```
652
+
653
+ The line is drawn on a selected tree pixel when the pixel `thickness` px away is another tree (a
654
+ different Tree ID) that is further away, so it lies on the front tree's side, with the outline's own
655
+ colour, thickness and strength (with a standard, reversed or logarithmic depth buffer). It is off by
656
+ default (the outline stays as it was). It needs the Tree
657
+ ID: `TreeEffects` turns the channel on for it, and switching `betweenTrees` on or off builds a new
658
+ graph. In your own pipeline, use `treeEffectsPass(scene, camera, selection, { treeId: true })`, which
659
+ also fills in the `depth` input; `treeOutline` throws when the `treeId` or `depth` input is missing.
660
+
661
+ ### Inner Lines
662
+
663
+ **Inner Lines** are ink lines inside the trees where the surface folds or steps away from the viewer,
664
+ such as around each leaf clump, on top of the outline around the tree. They come from depth edges
665
+ (a relative step `|Δz| / z`, so they look the same near and far) and normal edges (`1 − dot`), are
666
+ only drawn on tree pixels of every tree (whatever the `selection`) and only from neighbours that are
667
+ tree pixels too: the silhouette is left to the outline. They work with a standard, reversed
668
+ (`reversedDepthBuffer`) or logarithmic (`logarithmicDepthBuffer`) depth buffer.
669
+
670
+ ```ts
671
+ import { createTreeEffects } from '@casmo/tree.js/effects';
672
+
673
+ const effects = createTreeEffects(renderer, scene, camera, {
674
+ effects: { outline: {}, innerLines: { color: '#1d2a14', thickness: 1, strength: 1, normalThreshold: 0.4, depthThreshold: 0.02 } },
675
+ });
676
+ ```
677
+
678
+ Inner Lines need view normals, so with `innerLines` the ready-made pipeline adds a `normal` channel
679
+ (RGBA8) to its scene pass; without it the pass stays `{ output, treeMask }`. Order of the effects:
680
+ grade, glow, inner lines, outline. In your own pipeline, `treeEffectsPass(scene, camera, selection, { normal: true })`
681
+ fills in the `normal`, `depth` and `camera` inputs, or merge `treeNormalMRT()` into your scene pass.
682
+ `innerLines()` throws an error naming the missing input when `normal`, `depth` or `camera` is missing.
683
+
684
+ If your pipeline already renders normals (for GTAO, SSR and the like), pass that texture instead of
685
+ rendering them twice, with its encoding: `'color'` (default, `directionToColor(normalView)` in an
686
+ RGBA8 target) or `'direction'` (the normal itself, e.g. in a float target):
687
+
688
+ ```ts
689
+ import * as THREE from 'three/webgpu';
690
+ import { mrt, normalView, output, pass } from 'three/tsl';
691
+ import { innerLines, TREE_MASK, treeMaskMRT, treeOutline } from '@casmo/tree.js/effects';
692
+
693
+ const scenePass = pass(scene, camera);
694
+ scenePass.setMRT(mrt({ output, normal: normalView }).merge(treeMaskMRT())); // your MRT, plus the tree mask
695
+ scenePass.getTexture(TREE_MASK).type = THREE.UnsignedByteType;
696
+ const normal = scenePass.getTextureNode('normal'); // also feeds your GTAO / SSR
697
+ const input = {
698
+ color: scenePass.getTextureNode('output'),
699
+ mask: scenePass.getTextureNode(TREE_MASK),
700
+ depth: scenePass.getTextureNode('depth'),
701
+ camera,
702
+ normal,
703
+ normalEncoding: 'direction' as const,
704
+ };
705
+ const lined = innerLines(input, { strength: 0.8 });
706
+ const pipeline = new THREE.RenderPipeline(renderer);
707
+ pipeline.outputNode = treeOutline({ ...input, color: lined });
708
+ ```
709
+
710
+ ### Highlight
711
+
712
+ **Highlight** marks the trees you point out, such as the one under the cursor: it brightens and tints
713
+ them and draws a ring just outside them, optionally pulsing. It is the one Tree Effect that also
714
+ changes pixels next to a tree (its ring). It is never on by default and in no suggestion. It needs
715
+ the Tree ID, so `highlight` turns that channel on (and with it `pick`):
716
+
717
+ ```ts
718
+ import { createTreeEffects } from '@casmo/tree.js/effects';
719
+
720
+ const effects = createTreeEffects(renderer, scene, camera, {
721
+ effects: { outline: {}, highlight: { color: '#ffe066', tint: 0.25, brightness: 1.25, outlineColor: '#ffd23f', thickness: 2, pulse: 0 } },
722
+ });
723
+ renderer.domElement.addEventListener('pointermove', async (event) => {
724
+ const tree = await effects.pick(event.offsetX, event.offsetY);
725
+ effects.highlighted.splice(0, effects.highlighted.length, ...(tree ? [tree] : [])); // read every frame, no recompile
726
+ });
727
+ ```
728
+
729
+ - `highlighted` (an option, or the `effects.highlighted` list) holds Trees and Forest trees, not a
730
+ Forest or a group. Change it in place; it is read every frame. At most 64 trees are highlighted at
731
+ once (one console warning beyond that). Removed, disposed and undrawn trees are skipped.
732
+ - Options: `color` and `tint` (0..1) of the tint, `brightness` (a multiplier), `outlineColor` and
733
+ `thickness` (px) of the ring, `strength` (0..1) and `pulse` (Hz, 0 = off): tint and brightness swing
734
+ between their value and half of it, the ring stays solid.
735
+ - It is applied last (grade, glow, inner lines, outline, then highlight), so it is always on top. In your own
736
+ pipeline: `treeHighlight(input, highlighted, options)`, with the `treeId` input of
737
+ `treeEffectsPass(scene, camera, null, { treeId: true })`, or `applyTreeEffects(input, settings, highlighted)`.
738
+
384
739
  ## React Three Fiber
385
740
 
386
741
  ![Two low-poly trees rendered with React Three Fiber](docs/images/react.png)
@@ -505,6 +860,41 @@ const baked = bakeTree(tree, { season: 0.6 }); // a THREE.Group, e.g. for your o
505
860
  disposeBakedTree(baked);
506
861
  ```
507
862
 
863
+ ## Using a Baked Tree in other engines
864
+
865
+ A Baked Tree carries its Material Features (Crown Normals, Leaf Translucency, Structural Occlusion; see
866
+ `materials` in the Tree Definition) in standard glTF channels, so other engines can show them. With no
867
+ Material Feature set, the `.glb` is exactly what it was without them.
868
+
869
+ ```ts
870
+ import { createTree, exportBakedTree, extendDefinition } from '@casmo/tree.js';
871
+
872
+ const definition = extendDefinition({ schemaVersion: 3 }, {
873
+ materials: { leaf: { crownNormals: 1, translucency: { strength: 0.5, edge: 0.6, ambient: 0.3 } }, occlusion: { strength: 0.7 } },
874
+ });
875
+ const tree = createTree(definition, { seed: 4 });
876
+ const glb = await exportBakedTree(tree, { occlusionInVertexColors: true }); // the option works for bakeTree too
877
+ ```
878
+
879
+ | glTF channel | What it holds | Unity | Godot 4 | Unreal | Blender |
880
+ | --- | --- | --- | --- | --- | --- |
881
+ | `NORMAL` | Crown Normals already blended in (flat shading: the facet normals, blended by the same amount). Flat leaf cards (`leaves.shape: 'card'`) are turned (normal and winding together) to face outward of the Crown Volume, so engines that flip the normal of back faces still light every card from the crown's outside. Solid leaf shapes keep their winding. | Imported as mesh normals; keep the importer from recalculating them. | Imported as mesh normals. | Imported as mesh normals; turn "Recompute Normals" off. | Imported as custom normals. |
882
+ | `_OCCLUSION` (float, 0..1, all meshes) | Structural Occlusion as the tree shows it: `mix(1, aOcclusion, strength)`, 0 = occluded. **Final: the strength is already applied**, use it as AO as it is. Only when `materials.occlusion` is set. | Custom attributes are not imported by default: copy it into a UV channel or vertex colour in a custom importer, then feed it to the shader's occlusion. Or use `COLOR_0` (below). | Copy it into `CUSTOM0` with a `GLTFDocumentExtension` and read it as `AO` in a `ShaderMaterial`. Or use `COLOR_0`. | Not imported: use `COLOR_0`. | Imported as a mesh attribute `_OCCLUSION`: an Attribute node, multiplied into the indirect light or the Base Color. |
883
+ | `COLOR_0` | The vertex colours (Season colour, bark shading) as without the features; times `_OCCLUSION` with `occlusionInVertexColors: true`. | A shader that multiplies vertex colour into albedo (glTFast's shaders do). | `vertex_color_use_as_albedo` on the material. | Vertex Color node into Base Color. | Color Attribute node into Base Color (the importer wires it). |
884
+ | `KHR_materials_diffuse_transmission` (leaf material) | Leaf Translucency: `diffuseTransmissionFactor` = strength, `diffuseTransmissionColorFactor` = the leaf colour (linear, mean at the baked Season). | A foliage or translucent shader: transmission or thickness from the factor, colour from the colour factor. | `backlight_enabled`, `backlight` = colour × factor. | Shading model Two Sided Foliage, Subsurface Color = colour × factor. | Mix a Translucent BSDF (the colour) into the leaf shader by the factor. |
885
+ | `extras.treejs` (leaf and bark materials) | The settings `crownNormals`, `translucency { strength, edge, ambient }`, `occlusion { strength, strengthApplied: true, inVertexColors }` (only those set) and the Crown Volume `crown { center, radii }` in the Baked Tree's space (scaled by its Growth). `occlusion.strength` is for reference: `strengthApplied: true` says `_OCCLUSION` already has it, and `inVertexColors` whether `COLOR_0` has the occlusion too. | Read the glTF JSON in a custom importer to rebuild the effects in your own shader. | Imported as metadata on the material (`extras`), or read in a `GLTFDocumentExtension`. | Not imported: read the glTF JSON. | Imported as custom properties of the material. |
886
+
887
+ Importer support differs between versions; the columns show where each value goes.
888
+
889
+ **Don't apply the occlusion strength twice:** `_OCCLUSION` (and `COLOR_0` with `occlusionInVertexColors`)
890
+ already has `materials.occlusion.strength` applied. Use `_OCCLUSION` as AO directly, and only read
891
+ `extras.treejs.occlusion.strength` if you rebuild the effect from scratch.
892
+
893
+ **`occlusionInVertexColors`** (default `false`, in `bakeTree` and `exportBakedTree`): engines that only read
894
+ vertex colours show the occlusion without a custom shader. The trade-off: `COLOR_0` darkens all light,
895
+ direct sunlight included, while Structural Occlusion in tree.js (and `_OCCLUSION` used as AO) darkens only
896
+ ambient and indirect light. Leave it off when your engine can read `_OCCLUSION`, or keep the strength lower.
897
+
508
898
  ## Textures
509
899
 
510
900
  ![The realistic Style up close: textured bark and leaf cards on a broadleaf, needle cards on a conifer](docs/images/textures.png)
@@ -548,6 +938,7 @@ a live preview (Seed, Growth, Season, Wind, Tree Effects), sculpt single branche
548
938
  | [`examples/react`](examples/react/main.tsx) | `/examples/react/` | React Three Fiber: `<Tree>`, `<Wind>`, `useTreeStyle`; `?scene=forest` for `<Forest>` | <img src="docs/images/example-react.png" alt="examples/react" width="160"> |
549
939
  | [`examples/forest`](examples/forest/main.ts) | `/examples/forest/` | a 400-tree Forest; `?trees=&variants=&style=&season=` | <img src="docs/images/example-forest.png" alt="examples/forest" width="160"> |
550
940
  | [`examples/effects`](examples/effects/main.ts) | `/examples/effects/` | Tree Effects per Style; `?style=stylized&effects=outline` | <img src="docs/images/example-effects.png" alt="examples/effects" width="160"> |
941
+ | [`examples/material-features`](examples/material-features/main.ts) | `/examples/material-features/` | the same tree with Material Features off and on (`SUGGESTED_MATERIAL_FEATURES`); `?style=realistic&species=oak` | <img src="docs/images/example-material-features.png" alt="examples/material-features" width="160"> |
551
942
  | [`examples/species`](examples/species/main.ts) | `/examples/species/` | a Species x Style picker over the whole collection; `?species=douglas-fir&style=realistic` | <img src="docs/images/example-species.png" alt="examples/species" width="160"> |
552
943
 
553
944
  ```sh
@@ -1,4 +1,4 @@
1
- import { a as extendDefinition, i as styleShading, r as styleOfShading, s as parseDefinition } from "./names-C6-wuJ29.js";
1
+ import { c as extendDefinition, i as styleShading, o as materialFeaturesOf, r as styleOfShading, u as parseDefinition } from "./names-BE9he6CS.js";
2
2
  // src/styles/realistic/textures.ts
3
3
  /**
4
4
  * The realistic Style's texture files, as relative URLs (resolved against the texture base path).
@@ -59,7 +59,8 @@ var LOOKS = {
59
59
  "low-poly": {
60
60
  trunk: {
61
61
  sides: 5,
62
- sections: 4
62
+ sections: 4,
63
+ flareSections: 2
63
64
  },
64
65
  branches: [{
65
66
  sides: 4,
@@ -70,6 +71,10 @@ var LOOKS = {
70
71
  }],
71
72
  bark: untexturedBark,
72
73
  fruitSides: 4,
74
+ roots: {
75
+ sides: 3,
76
+ sections: 2
77
+ },
73
78
  leaf: (type) => isNeedleLike(type) ? {
74
79
  shape: "needle",
75
80
  perDensity: 14,
@@ -85,7 +90,8 @@ var LOOKS = {
85
90
  stylized: {
86
91
  trunk: {
87
92
  sides: 10,
88
- sections: 8
93
+ sections: 8,
94
+ flareSections: 3
89
95
  },
90
96
  branches: [
91
97
  {
@@ -103,6 +109,10 @@ var LOOKS = {
103
109
  ],
104
110
  bark: untexturedBark,
105
111
  fruitSides: 6,
112
+ roots: {
113
+ sides: 6,
114
+ sections: 4
115
+ },
106
116
  leaf: (type) => isNeedleLike(type) ? {
107
117
  shape: "puff",
108
118
  perDensity: 8,
@@ -118,7 +128,8 @@ var LOOKS = {
118
128
  realistic: {
119
129
  trunk: {
120
130
  sides: 12,
121
- sections: 10
131
+ sections: 10,
132
+ flareSections: 3
122
133
  },
123
134
  branches: [
124
135
  {
@@ -139,6 +150,10 @@ var LOOKS = {
139
150
  ...BARK_TEXTURES[type]
140
151
  }),
141
152
  fruitSides: 9,
153
+ roots: {
154
+ sides: 8,
155
+ sections: 6
156
+ },
142
157
  leaf: (type) => isNeedleLike(type) ? {
143
158
  shape: "card",
144
159
  perDensity: 120,
@@ -160,8 +175,12 @@ var LOOKS = {
160
175
  }
161
176
  }
162
177
  };
178
+ /** `{ [key]: value }` for an optional block that is present, `{}` when it is absent (to spread). */
179
+ function present(key, value) {
180
+ return value === void 0 ? {} : { [key]: value };
181
+ }
163
182
  function fromSpecies(species) {
164
- const { id, name, trunk, branches, season, wind, variation, fruit, foliage, bark } = species;
183
+ const { id, name, trunk, branches, season, wind, variation, fruit, roots, foliage, bark } = species;
165
184
  return {
166
185
  base: {
167
186
  schemaVersion: 3,
@@ -173,14 +192,17 @@ function fromSpecies(species) {
173
192
  wind,
174
193
  variation,
175
194
  sculpts: [],
176
- ...fruit ? { fruit } : {}
195
+ ...present("fruit", fruit),
196
+ ...present("roots", roots)
177
197
  },
178
198
  foliage,
179
- bark
199
+ bark,
200
+ features: {}
180
201
  };
181
202
  }
182
203
  function fromDefinition(input) {
183
- const { leaves, materials, ...base } = parseDefinition(input);
204
+ const definition = parseDefinition(input);
205
+ const { leaves, materials, ...base } = definition;
184
206
  const leafType = leaves.type ?? (leaves.shape === "needle" || /needle/.test(materials.leaf.map ?? "") ? "needle" : "broad");
185
207
  const source = LOOKS[styleOfShading(materials.shading)].leaf(leafType);
186
208
  return {
@@ -195,20 +217,27 @@ function fromDefinition(input) {
195
217
  },
196
218
  bark: {
197
219
  type: materials.bark.type ?? "furrowed",
198
- color: materials.bark.color
199
- }
220
+ color: materials.bark.color,
221
+ ...present("groundTint", materials.bark.groundTint)
222
+ },
223
+ features: materialFeaturesOf(definition)
200
224
  };
201
225
  }
202
- function draw(name, { base, foliage, bark }) {
226
+ function draw(name, { base, foliage, bark, features }) {
203
227
  const look = LOOKS[name];
204
228
  const leaf = look.leaf(foliage.type);
205
229
  const fruit = base.fruit;
230
+ const roots = base.roots;
206
231
  return parseDefinition({
207
232
  ...base,
208
- ...fruit ? { fruit: {
233
+ ...present("fruit", fruit && {
209
234
  ...fruit,
210
235
  sides: look.fruitSides
211
- } } : {},
236
+ }),
237
+ ...present("roots", roots && {
238
+ ...roots,
239
+ ...look.roots
240
+ }),
212
241
  trunk: {
213
242
  ...base.trunk,
214
243
  ...look.trunk
@@ -231,9 +260,15 @@ function draw(name, { base, foliage, bark }) {
231
260
  bark: {
232
261
  type: bark.type,
233
262
  color: bark.color,
234
- ...look.bark(bark.type)
263
+ ...look.bark(bark.type),
264
+ ...present("groundTint", bark.groundTint)
265
+ },
266
+ leaf: {
267
+ ...leaf.material,
268
+ ...present("crownNormals", features.crownNormals),
269
+ ...present("translucency", features.translucency)
235
270
  },
236
- leaf: { ...leaf.material }
271
+ ...present("occlusion", features.occlusion)
237
272
  }
238
273
  });
239
274
  }
@@ -247,4 +282,4 @@ function applyStyle(name, source, overrides) {
247
282
  }
248
283
  export { TEXTURES as i, BARK_TEXTURES as n, LEAF_TEXTURES as r, applyStyle as t };
249
284
 
250
- //# sourceMappingURL=apply-CcodnAbs.js.map
285
+ //# sourceMappingURL=apply-Cio2t7CZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apply-Cio2t7CZ.js","names":[],"sources":["../src/styles/realistic/textures.ts","../src/styles/apply.ts"],"sourcesContent":["import type { BarkType, LeafType } from '../../definition/types';\n\n/**\n * The realistic Style's texture files, as relative URLs (resolved against the texture base path).\n * All made by scripts/generate-textures.mjs. `bark`/`barkNormal` are the furrowed pair, `leaf` the\n * broad card and `needles` the needle card (the generic broadleaf / conifer use these).\n */\nexport const TEXTURES = {\n bark: 'realistic/bark.png',\n barkNormal: 'realistic/bark-normal.png',\n leaf: 'realistic/leaf.png',\n needles: 'realistic/needles.png',\n} as const;\n\n/** The alpha-cut leaf card texture for each Leaf Type. */\nexport const LEAF_TEXTURES: Readonly<Record<LeafType, string>> = {\n broad: TEXTURES.leaf,\n lobed: 'realistic/leaf-lobed.png',\n palmate: 'realistic/leaf-palmate.png',\n compound: 'realistic/leaf-compound.png',\n needle: TEXTURES.needles,\n scale: 'realistic/scale.png',\n};\n\n/** The colour + normal map pair for each Bark Type. */\nexport const BARK_TEXTURES: Readonly<Record<BarkType, { map: string; normalMap: string }>> = {\n furrowed: { map: TEXTURES.bark, normalMap: TEXTURES.barkNormal },\n smooth: { map: 'realistic/bark-smooth.png', normalMap: 'realistic/bark-smooth-normal.png' },\n papery: { map: 'realistic/bark-papery.png', normalMap: 'realistic/bark-papery-normal.png' },\n fibrous: { map: 'realistic/bark-fibrous.png', normalMap: 'realistic/bark-fibrous-normal.png' },\n plated: { map: 'realistic/bark-plated.png', normalMap: 'realistic/bark-plated-normal.png' },\n};\n","// Style.apply (ADR 0005): a Style turns a Style-neutral Species (or an existing Tree Definition)\n// into a complete Tree Definition by choosing only the look: shading, polygon detail, how the\n// Leaf Type and Bark Type are drawn, and textures. Shape fields pass through untouched.\nimport { extendDefinition, parseDefinition, type DefinitionPatch } from '../definition/parse';\nimport {\n CURRENT_SCHEMA_VERSION,\n type BarkMaterialDefinition,\n type MaterialFeatures,\n type BarkType,\n type LeafMaterialDefinition,\n type LeafShape,\n type LeafType,\n type TreeDefinition,\n type TreeDefinitionInput,\n} from '../definition/types';\nimport type { SpeciesBarkDefinition, SpeciesDefinition, SpeciesFoliageDefinition } from '../species/types';\nimport { styleOfShading, styleShading, type StyleName } from './names';\nimport { materialFeaturesOf } from './material-features';\nimport { BARK_TEXTURES, LEAF_TEXTURES } from './realistic/textures';\n\n/** Polygon detail of one tree part. */\ninterface Detail {\n sides: number;\n sections: number;\n}\n\n/** How a Style draws one Leaf Type. */\ninterface LeafLook {\n shape: LeafShape;\n /** Leaves per terminal branch at density 1 (count = round(density × this)). */\n perDensity: number;\n /** Leaf size = the Species' real leaf-spray size × this. */\n sizeScale: number;\n material: LeafMaterialDefinition;\n}\n\n/** The trunk's detail, plus the extra rings in its Root Flare (`trunk.flareSections`). */\ninterface TrunkDetail extends Detail {\n flareSections: number;\n}\n\n/** Everything a Style decides about a tree: its look (its shading is in names.ts). */\ninterface StyleLook {\n trunk: TrunkDetail;\n /** Detail per branch level; deeper levels reuse the last entry. */\n branches: Detail[];\n bark(type: BarkType): Omit<BarkMaterialDefinition, 'type' | 'color'>;\n leaf(type: LeafType): LeafLook;\n /** Faces around each Fruit (`fruit.sides`): few flat facets in low-poly, smooth in the others. */\n fruitSides: number;\n /** Detail of each Root (`roots.sides`, `roots.sections`). */\n roots: Detail;\n}\n\nconst isNeedleLike = (type: LeafType) => type === 'needle' || type === 'scale';\nconst untexturedLeaf: LeafMaterialDefinition = { roughness: 1, map: null, alphaTest: 0.5 };\nconst untexturedBark = () => ({ roughness: 1, map: null, normalMap: null });\n\n// Low-poly and stylized are calibrated so a Species with density 0.5 and leaf-spray size 0.35 m comes\n// out close to each Style's own broadleaf / conifer Definitions. Realistic draws far more (cheap, 2\n// triangle) cards per twig than its own Definitions: a Species has fewer twigs than the realistic\n// generic trees (the low-poly and stylized triangle budgets cap them at about 40-90), so the cards\n// have to fill the crown. Deeper branch levels get little detail (twigs are thin and many).\nconst LOOKS = {\n 'low-poly': {\n trunk: { sides: 5, sections: 4, flareSections: 2 },\n branches: [{ sides: 4, sections: 2 }, { sides: 3, sections: 1 }],\n bark: untexturedBark,\n fruitSides: 4,\n roots: { sides: 3, sections: 2 },\n leaf: (type) =>\n isNeedleLike(type)\n ? { shape: 'needle', perDensity: 14, sizeScale: 1.86, material: untexturedLeaf }\n : { shape: 'clump', perDensity: 4, sizeScale: 2.86, material: untexturedLeaf },\n },\n stylized: {\n trunk: { sides: 10, sections: 8, flareSections: 3 },\n branches: [{ sides: 6, sections: 3 }, { sides: 4, sections: 1 }, { sides: 3, sections: 1 }],\n bark: untexturedBark,\n fruitSides: 6,\n roots: { sides: 6, sections: 4 },\n // All puffs; smaller and denser for needle / scale foliage.\n leaf: (type) =>\n isNeedleLike(type)\n ? { shape: 'puff', perDensity: 8, sizeScale: 1.7, material: untexturedLeaf }\n : { shape: 'puff', perDensity: 4, sizeScale: 3.14, material: untexturedLeaf },\n },\n realistic: {\n trunk: { sides: 12, sections: 10, flareSections: 3 },\n branches: [{ sides: 8, sections: 6 }, { sides: 5, sections: 4 }, { sides: 3, sections: 2 }],\n // A texture per Bark Type and per Leaf Type (scripts/generate-textures.mjs).\n bark: (type) => ({ roughness: 0.95, ...BARK_TEXTURES[type] }),\n fruitSides: 9,\n roots: { sides: 8, sections: 6 },\n leaf: (type) =>\n isNeedleLike(type)\n ? { shape: 'card', perDensity: 120, sizeScale: 1.7, material: { roughness: 0.7, map: LEAF_TEXTURES[type], alphaTest: 0.4 } }\n : { shape: 'card', perDensity: 80, sizeScale: 2.2, material: { roughness: 0.65, map: LEAF_TEXTURES[type], alphaTest: 0.4 } },\n },\n} satisfies Record<StyleName, StyleLook>;\n\n/** What `Style.apply` accepts: a Species, or a Tree Definition to re-style. */\nexport type StyleSource = SpeciesDefinition | TreeDefinition | TreeDefinitionInput;\n\n/** `{ [key]: value }` for an optional block that is present, `{}` when it is absent (to spread). */\nfunction present<K extends string, V>(key: K, value: V | undefined): { [P in K]?: V } {\n return value === undefined ? {} : ({ [key]: value } as { [P in K]?: V });\n}\n\n/** The Style-neutral content of a source: every non-look field, plus foliage and bark. */\ninterface Neutral {\n /** Definition fields that pass through (shape, Season, Wind, Sculpts, Fruit, Roots, ...). */\n base: Record<string, unknown> & { trunk: object; branches: object[] };\n foliage: SpeciesFoliageDefinition;\n /** A Definition's Ground Tint passes through too: it is not part of a Style's look. */\n bark: SpeciesBarkDefinition & Pick<BarkMaterialDefinition, 'groundTint'>;\n /** A Definition's Material Features pass through too (ADR 0008): they are the app's choice, never a Style's. */\n features: MaterialFeatures;\n}\n\nfunction fromSpecies(species: SpeciesDefinition): Neutral {\n const { id, name, trunk, branches, season, wind, variation, fruit, roots, foliage, bark } = species;\n return {\n base: {\n schemaVersion: CURRENT_SCHEMA_VERSION,\n name,\n species: id,\n trunk,\n branches,\n season,\n wind,\n variation,\n sculpts: [],\n ...present('fruit', fruit),\n ...present('roots', roots),\n },\n foliage,\n bark,\n features: {},\n };\n}\n\nfunction fromDefinition(input: TreeDefinition | TreeDefinitionInput): Neutral {\n const definition = parseDefinition(input);\n const { leaves, materials, ...base } = definition;\n // Definitions not made by `apply` carry no Leaf / Bark Type: guess them from how they are drawn.\n const leafType = leaves.type ?? (leaves.shape === 'needle' || /needle/.test(materials.leaf.map ?? '') ? 'needle' : 'broad');\n const source = LOOKS[styleOfShading(materials.shading)].leaf(leafType);\n return {\n base,\n foliage: {\n type: leafType,\n density: leaves.count / source.perDensity,\n size: leaves.size / source.sizeScale,\n sizeVariation: leaves.sizeVariation,\n start: leaves.start,\n angle: leaves.angle,\n },\n bark: {\n type: materials.bark.type ?? 'furrowed',\n color: materials.bark.color,\n ...present('groundTint', materials.bark.groundTint),\n },\n features: materialFeaturesOf(definition),\n };\n}\n\nfunction draw(name: StyleName, { base, foliage, bark, features }: Neutral): TreeDefinition {\n const look: StyleLook = LOOKS[name];\n const leaf = look.leaf(foliage.type);\n const fruit = base.fruit as TreeDefinition['fruit'];\n const roots = base.roots as TreeDefinition['roots'];\n return parseDefinition({\n ...base,\n ...present('fruit', fruit && { ...fruit, sides: look.fruitSides }),\n ...present('roots', roots && { ...roots, ...look.roots }),\n trunk: { ...base.trunk, ...look.trunk },\n branches: base.branches.map((level, i) => ({ ...level, ...look.branches[Math.min(i, look.branches.length - 1)] })),\n leaves: {\n type: foliage.type,\n count: Math.round(foliage.density * leaf.perDensity),\n shape: leaf.shape,\n size: foliage.size * leaf.sizeScale,\n sizeVariation: foliage.sizeVariation,\n start: foliage.start,\n angle: foliage.angle,\n },\n materials: {\n shading: styleShading(name),\n bark: { type: bark.type, color: bark.color, ...look.bark(bark.type), ...present('groundTint', bark.groundTint) },\n leaf: { ...leaf.material, ...present('crownNormals', features.crownNormals), ...present('translucency', features.translucency) },\n ...present('occlusion', features.occlusion),\n },\n });\n}\n\n/**\n * Applies a built-in Style's look to a Species or a Tree Definition (see `TreeStyle.apply`).\n * Pure: never mutates its inputs.\n */\nexport function applyStyle(name: StyleName, source: StyleSource, overrides?: DefinitionPatch): TreeDefinition {\n const neutral = 'schemaVersion' in source ? fromDefinition(source) : fromSpecies(source);\n const definition = draw(name, neutral);\n return overrides ? extendDefinition(definition, overrides) : definition;\n}\n"],"mappings":"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"}