@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/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { _ as FRUIT_TYPES, a as extendDefinition, c as TreeDefinitionError, d as DEFAULT_FRUIT, f as DEFAULT_FRUIT_AMOUNT, g as CURRENT_SCHEMA_VERSION, h as BARK_TYPES, l as DEFAULT_BRANCH_LEVEL, m as coneCurve, n as styleLabel, o as fetchDefinition, p as DEFAULT_FRUIT_COLOR, r as styleOfShading, s as parseDefinition, t as STYLE_NAMES, u as DEFAULT_DEFINITION, v as LEAF_TYPES, y as MAX_BRANCH_LEVELS } from "./names-C6-wuJ29.js";
2
- import { A as hashTreeData, B as sampleTrack, C as loadTexture, D as clampGrowth, E as textureReady, F as fruitTracks, G as wrapSeason, H as segmentWeight, I as hexToLinear, K as createRandom, L as leafSeason, M as evaluateSeason, N as fruitSeason, O as growPositions, P as fruitSeasonAttribute, R as leafSeasonAttribute, S as getTextureOptions, T as setTextureOptions, U as srgbToLinear, V as seasonShift, W as woodSeasonAttribute, _ as createBarkMaterial, b as BARK_REPEAT, c as Tree, d as sceneWind, f as applySeasonToLeafMaterial, g as assertWebGPURenderer, h as UnsupportedRendererError, i as ForestVariant, j as KEYFRAME_EPSILON, k as hashGeometry, l as WindResponse, m as createSeasonNodes, n as Forest, o as loadStyle, p as createFruitSeasonNodes, r as ForestTree, s as createTree, t as createForest, u as Wind, v as createLeafMaterial, w as resolveTextureUrl, x as DEFAULT_TEXTURE_BASE_PATH, y as isFlatShading, z as partSeasonAt } from "./forest-DTrD8puH.js";
1
+ import { A as treeScale, B as hexToLinear, C as loadTexture, D as groundTintAmount, E as textureReady, F as KEYFRAME_EPSILON, G as seasonShift, H as leafSeasonAttribute, I as evaluateSeason, J as woodSeasonAttribute, K as segmentWeight, L as fruitSeason, M as hashTreeData, N as crownDistance, O as clampGrowth, P as crownNormal, R as fruitSeasonAttribute, S as getTextureOptions, T as setTextureOptions, U as partSeasonAt, V as leafSeason, W as sampleTrack, X as createRandom, Y as wrapSeason, _ as createBarkMaterial, b as BARK_REPEAT, c as Tree, d as sceneWind, f as applySeasonToLeafMaterial, g as assertWebGPURenderer, h as UnsupportedRendererError, i as ForestVariant, j as hashGeometry, k as growPositions, l as WindResponse, m as createSeasonNodes, n as Forest, o as loadStyle, p as createFruitSeasonNodes, q as srgbToLinear, r as ForestTree, s as createTree, t as createForest, u as Wind, v as createLeafMaterial, w as resolveTextureUrl, x as DEFAULT_TEXTURE_BASE_PATH, y as isFlatShading, z as fruitTracks } from "./forest-lg61rhKM.js";
2
+ import { C as CURRENT_SCHEMA_VERSION, E as MAX_BRANCH_LEVELS, S as BARK_TYPES, T as LEAF_TYPES, _ as DEFAULT_GROUND_TINT, a as SUGGESTED_MATERIAL_FEATURES, b as DEFAULT_TRANSLUCENCY, c as extendDefinition, d as TreeDefinitionError, f as DEFAULT_BRANCH_LEVEL, g as DEFAULT_FRUIT_COLOR, h as DEFAULT_FRUIT_AMOUNT, l as fetchDefinition, m as DEFAULT_FRUIT, n as styleLabel, o as materialFeaturesOf, p as DEFAULT_DEFINITION, r as styleOfShading, s as withMaterialFeatures, t as STYLE_NAMES, u as parseDefinition, v as DEFAULT_OCCLUSION, w as FRUIT_TYPES, x as coneCurve, y as DEFAULT_ROOTS } from "./names-BE9he6CS.js";
3
3
  import { t as SEASON_PROFILES } from "./profiles-BAiyeFlh.js";
4
4
  import { BufferAttribute, BufferGeometry, Color, DoubleSide, Group, Mesh, MeshStandardMaterial } from "three/webgpu";
5
5
  import { GLTFExporter } from "three/addons/exporters/GLTFExporter.js";
@@ -23,7 +23,11 @@ function compact(buffers, indices, flat) {
23
23
  ];
24
24
  if (!buffers.visible(a) || !buffers.visible(b) || !buffers.visible(c)) continue;
25
25
  if (area2(positions, a, b, c) < MIN_AREA2) continue;
26
- for (const v of [
26
+ for (const v of buffers.crownNormals?.flipped[a] ? [
27
+ a,
28
+ c,
29
+ b
30
+ ] : [
27
31
  a,
28
32
  b,
29
33
  c
@@ -45,15 +49,48 @@ function compact(buffers, indices, flat) {
45
49
  geometry.setAttribute("normal", new BufferAttribute(pick(buffers.normals, 3), 3));
46
50
  geometry.setAttribute("uv", new BufferAttribute(pick(buffers.uvs, 2), 2));
47
51
  if (buffers.colors) geometry.setAttribute("color", new BufferAttribute(pick(buffers.colors, 3), 3));
52
+ if (buffers.occlusion) geometry.setAttribute(OCCLUSION, new BufferAttribute(pick(buffers.occlusion, 1), 1));
53
+ if (buffers.crownNormals) geometry.setAttribute(CROWN_NORMAL, new BufferAttribute(pick(buffers.crownNormals.normals, 3), 3));
48
54
  geometry.setIndex(new BufferAttribute(Uint32Array.from(kept), 1));
49
55
  if (flat) {
50
56
  geometry = geometry.toNonIndexed();
51
57
  geometry.computeVertexNormals();
52
58
  }
59
+ if (buffers.crownNormals) {
60
+ blendNormals(geometry, buffers.crownNormals.amount);
61
+ geometry.deleteAttribute(CROWN_NORMAL);
62
+ }
53
63
  geometry.computeBoundingBox();
54
64
  geometry.computeBoundingSphere();
55
65
  return geometry;
56
66
  }
67
+ /** The geometry attribute GLTFExporter writes as the `_OCCLUSION` vertex attribute. */
68
+ var OCCLUSION = "_occlusion";
69
+ /** Scratch attribute: the Crown Volume normal per vertex, removed once the normals are blended. */
70
+ var CROWN_NORMAL = "crownNormal";
71
+ /** `normalize(mix(normal, crown normal, amount))`, as the leaf material's normalNode; the crown's where they cancel out. */
72
+ function blendNormals(geometry, amount) {
73
+ const normal = geometry.getAttribute("normal");
74
+ const crown = geometry.getAttribute(CROWN_NORMAL);
75
+ for (let v = 0; v < normal.count; v++) {
76
+ const c = [
77
+ crown.getX(v),
78
+ crown.getY(v),
79
+ crown.getZ(v)
80
+ ];
81
+ let x = normal.getX(v) + (c[0] - normal.getX(v)) * amount;
82
+ let y = normal.getY(v) + (c[1] - normal.getY(v)) * amount;
83
+ let z = normal.getZ(v) + (c[2] - normal.getZ(v)) * amount;
84
+ const length = Math.sqrt(x * x + y * y + z * z);
85
+ if (length > 1e-4) [x, y, z] = [
86
+ x / length,
87
+ y / length,
88
+ z / length
89
+ ];
90
+ else [x, y, z] = c;
91
+ normal.setXYZ(v, x, y, z);
92
+ }
93
+ }
57
94
  function area2(p, a, b, c) {
58
95
  const u = [
59
96
  p[b * 3] - p[a * 3],
@@ -70,27 +107,48 @@ function area2(p, a, b, c) {
70
107
  const z = u[0] * w[1] - u[1] * w[0];
71
108
  return x * x + y * y + z * z;
72
109
  }
73
- /** Wood: grown positions; the bark's base-to-tip darkening (smooth shading) as vertex colours. */
74
- function bakeWood(definition, wood, growth) {
110
+ /**
111
+ * Wood: grown positions; the bark's base-to-tip darkening (smooth shading) as vertex colours.
112
+ * With a Ground Tint the vertex colours carry the whole bark colour (the material is white), tinted
113
+ * near the ground on the grown positions, like the bark colorNode.
114
+ */
115
+ function bakeWood(definition, wood, growth, occlusion) {
75
116
  const flat = isFlatShading(definition.materials.shading);
117
+ const { color, groundTint } = definition.materials.bark;
118
+ const positions = growPositions(wood, growth);
76
119
  let colors = null;
77
- if (!flat) {
120
+ if (!flat || groundTint) {
78
121
  colors = new Float32Array(wood.positions.length);
122
+ const bark = groundTint ? hexToLinear(color) : [
123
+ 1,
124
+ 1,
125
+ 1
126
+ ];
127
+ const tint = groundTint ? hexToLinear(groundTint.color) : [
128
+ 1,
129
+ 1,
130
+ 1
131
+ ];
79
132
  for (let v = 0; v < colors.length / 3; v++) {
80
- const shade = .75 + .25 * Math.sqrt(Math.min(Math.max(wood.uvs[v * 2 + 1], 0), 1));
81
- colors.fill(shade, v * 3, v * 3 + 3);
133
+ const shade = flat ? 1 : .75 + .25 * Math.sqrt(Math.min(Math.max(wood.uvs[v * 2 + 1], 0), 1));
134
+ const amount = groundTint ? groundTintAmount(groundTint, positions[v * 3 + 1]) : 0;
135
+ for (let c = 0; c < 3; c++) colors[v * 3 + c] = bark[c] * shade * (1 - amount) + tint[c] * amount;
82
136
  }
83
137
  }
84
138
  return compact({
85
- positions: growPositions(wood, growth),
139
+ positions,
86
140
  normals: wood.normals,
87
141
  uvs: wood.uvs,
88
- colors,
142
+ ...occlusion.of(wood, colors),
89
143
  visible: () => true
90
144
  }, wood.indices, flat);
91
145
  }
92
- /** Leaves: grown positions; fallen leaves dropped; Season (or blossom) colour × the Seed's tint as vertex colours. */
93
- function bakeLeaves(definition, leaves, growth, season) {
146
+ /**
147
+ * Leaves: grown positions; fallen leaves dropped; Season (or blossom) colour × the Seed's tint as vertex
148
+ * colours. Also returns the mean colour of the shown leaves (linear, before any occlusion), the colour
149
+ * Leaf Translucency glows in.
150
+ */
151
+ function bakeLeaves(definition, leaves, growth, season, occlusion, crown, amount) {
94
152
  const count = leaves.positions.length / 3;
95
153
  const aSeason = leaves.attributes.aSeason.array;
96
154
  const shown = new Uint8Array(count);
@@ -100,19 +158,109 @@ function bakeLeaves(definition, leaves, growth, season) {
100
158
  shown[v] = state.visible ? 1 : 0;
101
159
  for (let c = 0; c < 3; c++) colors[v * 3 + c] = state.color[c] * (leaves.colors?.[v * 3 + c] ?? 1);
102
160
  }
103
- return compact({
104
- positions: growPositions(leaves, growth),
105
- normals: leaves.normals,
106
- uvs: leaves.uvs,
107
- colors,
108
- visible: (v) => shown[v] === 1
109
- }, leaves.indices, isFlatShading(definition.materials.shading));
161
+ const meanColor = meanShownColor(colors, shown);
162
+ const positions = growPositions(leaves, growth);
163
+ const crownNormals = amount ? bakedCrownNormals(leaves, positions, growth, crown, amount, definition.leaves.shape === "card") : void 0;
164
+ return {
165
+ geometry: compact({
166
+ positions,
167
+ normals: crownNormals ? orient(leaves.normals, crownNormals.flipped) : leaves.normals,
168
+ uvs: leaves.uvs,
169
+ ...occlusion.of(leaves, colors),
170
+ visible: (v) => shown[v] === 1,
171
+ crownNormals
172
+ }, leaves.indices, isFlatShading(definition.materials.shading)),
173
+ meanColor
174
+ };
175
+ }
176
+ /** Mean of the colours of the shown vertices (each channel at most 1); black when none is shown. */
177
+ function meanShownColor(colors, shown) {
178
+ const sum = [
179
+ 0,
180
+ 0,
181
+ 0
182
+ ];
183
+ let count = 0;
184
+ shown.forEach((on, v) => {
185
+ if (!on) return;
186
+ for (let c = 0; c < 3; c++) sum[c] += colors[v * 3 + c];
187
+ count++;
188
+ });
189
+ return sum.map((c) => Math.min(c / Math.max(count, 1), 1));
190
+ }
191
+ /**
192
+ * Crown Normals for the leaves: the Crown Volume's normal at each grown vertex (the Volume scaled by
193
+ * the Growth scale, as in the material), and which leaf cards to turn around. A card (`leaves.shape`
194
+ * 'card') is flat and double-sided with one normal for both sides: turning it (normal and winding
195
+ * together) changes nothing else, but makes its front face the crown's outside, so in engines that flip
196
+ * the normal of back faces the blended normal of every card points out. Decided per card at its attachment
197
+ * point (`aOrigin`, shared by its vertices). Solid leaf shapes are closed: their front faces are already
198
+ * their outside, and they keep their winding.
199
+ */
200
+ function bakedCrownNormals(leaves, grown, growth, crown, amount, cards) {
201
+ const count = grown.length / 3;
202
+ const scale = treeScale(growth);
203
+ const origin = leaves.attributes.aOrigin.array;
204
+ const n = leaves.normals;
205
+ const normals = new Float32Array(count * 3);
206
+ const flipped = new Uint8Array(count);
207
+ for (let v = 0; v < count; v++) {
208
+ const i = v * 3;
209
+ normals.set(crownNormal(crown, [
210
+ grown[i] / scale,
211
+ grown[i + 1] / scale,
212
+ grown[i + 2] / scale
213
+ ]), i);
214
+ if (!cards) continue;
215
+ const out = crownNormal(crown, [
216
+ origin[i],
217
+ origin[i + 1],
218
+ origin[i + 2]
219
+ ]);
220
+ flipped[v] = n[i] * out[0] + n[i + 1] * out[1] + n[i + 2] * out[2] < 0 ? 1 : 0;
221
+ }
222
+ return {
223
+ normals,
224
+ amount,
225
+ flipped
226
+ };
227
+ }
228
+ /** The normals with those of `flipped` vertices reversed. */
229
+ function orient(normals, flipped) {
230
+ const out = normals.slice();
231
+ flipped.forEach((flip, v) => {
232
+ if (flip) for (let c = 0; c < 3; c++) out[v * 3 + c] = -out[v * 3 + c];
233
+ });
234
+ return out;
235
+ }
236
+ function bakedOcclusion(strength, inColors) {
237
+ return { of: (part, colors) => {
238
+ const ao = part.attributes.aOcclusion?.array;
239
+ if (strength === null || !ao) return {
240
+ occlusion: null,
241
+ colors
242
+ };
243
+ const occlusion = Float32Array.from(ao, (a) => 1 - strength * (1 - a));
244
+ if (!inColors) return {
245
+ occlusion,
246
+ colors
247
+ };
248
+ return {
249
+ occlusion,
250
+ colors: darken(colors ?? new Float32Array(part.positions.length).fill(1), occlusion)
251
+ };
252
+ } };
253
+ }
254
+ /** Each vertex's colour times its occlusion (in place). */
255
+ function darken(colors, occlusion) {
256
+ for (let i = 0; i < colors.length; i++) colors[i] *= occlusion[Math.floor(i / 3)];
257
+ return colors;
110
258
  }
111
259
  /**
112
260
  * Fruit: each Fruit scaled about its attachment point by the Fruit amount (dropped when not
113
261
  * shown), then grown; the Fruit colour × the Seed's tint as vertex colours. Same order as the shader.
114
262
  */
115
- function bakeFruit(definition, fruit, growth, season) {
263
+ function bakeFruit(definition, fruit, growth, season, occlusion) {
116
264
  const count = fruit.positions.length / 3;
117
265
  if (count === 0) return null;
118
266
  const aSeason = fruit.attributes.aSeason.array;
@@ -136,7 +284,7 @@ function bakeFruit(definition, fruit, growth, season) {
136
284
  }, growth),
137
285
  normals: fruit.normals,
138
286
  uvs: fruit.uvs,
139
- colors,
287
+ ...occlusion.of(fruit, colors),
140
288
  visible: (v) => shown[v] === 1
141
289
  }, fruit.indices, isFlatShading(definition.materials.shading));
142
290
  }
@@ -150,7 +298,8 @@ function bakedMap(texture, repeat) {
150
298
  /**
151
299
  * Freezes a tree at a Growth and Season (default: the tree's own) into a static `Group` of
152
300
  * meshes `wood`, `leaves` and `fruit` (a mesh with nothing to show is left out) with standard PBR
153
- * materials: no node materials, no Growth/Season/Wind attributes, no animation. The result is
301
+ * materials: no node materials, no Growth/Season/Wind attributes, no animation. Material Features
302
+ * are baked in (see the top of this module). The result is
154
303
  * independent of `tree`; call `disposeBakedTree` when done with it.
155
304
  */
156
305
  function bakeTree(tree, options = {}) {
@@ -160,6 +309,9 @@ function bakeTree(tree, options = {}) {
160
309
  const season = wrapSeason(options.season ?? tree.season);
161
310
  const bark = definition.materials.bark;
162
311
  const flat = isFlatShading(definition.materials.shading);
312
+ const features = tree.materialFeatures;
313
+ const occlusion = bakedOcclusion(features.occlusion?.strength ?? null, options.occlusionInVertexColors ?? false);
314
+ const extras = materialFeatureExtras(features, tree.data.crown, growth, options.occlusionInVertexColors ?? false);
163
315
  const group = new Group();
164
316
  group.name = definition.name || "Tree";
165
317
  group.userData = {
@@ -167,11 +319,11 @@ function bakeTree(tree, options = {}) {
167
319
  growth,
168
320
  season
169
321
  };
170
- const woodGeometry = bakeWood(definition, data.wood, growth);
322
+ const woodGeometry = bakeWood(definition, data.wood, growth, occlusion);
171
323
  if (woodGeometry) {
172
324
  const material = new MeshStandardMaterial({
173
325
  name: "bark",
174
- color: new Color(bark.color),
326
+ color: new Color(bark.groundTint ? 16777215 : bark.color),
175
327
  roughness: bark.roughness,
176
328
  metalness: 0,
177
329
  vertexColors: woodGeometry.hasAttribute("color"),
@@ -179,9 +331,10 @@ function bakeTree(tree, options = {}) {
179
331
  map: bakedMap(source.map, BARK_REPEAT),
180
332
  normalMap: bakedMap(source.normalMap, BARK_REPEAT)
181
333
  });
334
+ if (extras) material.userData = { treejs: extras };
182
335
  group.add(bakedMesh("wood", woodGeometry, material));
183
336
  }
184
- const leafGeometry = bakeLeaves(definition, data.leaves, growth, season);
337
+ const { geometry: leafGeometry, meanColor } = bakeLeaves(definition, data.leaves, growth, season, occlusion, data.crown, features.crownNormals);
185
338
  if (leafGeometry) {
186
339
  const map = bakedMap(tree.leaves.material.map);
187
340
  const material = new MeshStandardMaterial({
@@ -195,9 +348,15 @@ function bakeTree(tree, options = {}) {
195
348
  map,
196
349
  alphaTest: map ? definition.materials.leaf.alphaTest : 0
197
350
  });
351
+ if (extras) material.userData = { treejs: extras };
352
+ const { translucency } = features;
353
+ if (translucency) diffuseTransmission.set(material, {
354
+ factor: translucency.strength,
355
+ color: meanColor
356
+ });
198
357
  group.add(bakedMesh("leaves", leafGeometry, material));
199
358
  }
200
- const fruitGeometry = bakeFruit(definition, data.fruit, growth, season);
359
+ const fruitGeometry = bakeFruit(definition, data.fruit, growth, season, occlusion);
201
360
  if (fruitGeometry) {
202
361
  const material = new MeshStandardMaterial({
203
362
  name: "fruit",
@@ -211,6 +370,53 @@ function bakeTree(tree, options = {}) {
211
370
  }
212
371
  return group;
213
372
  }
373
+ function materialFeatureExtras(features, crown, growth, occlusionInVertexColors) {
374
+ const { crownNormals, translucency, occlusion } = features;
375
+ if (!crownNormals && !translucency && !occlusion) return null;
376
+ const scale = treeScale(growth);
377
+ const { center, radii } = crown;
378
+ return {
379
+ ...crownNormals ? { crownNormals } : {},
380
+ ...translucency ? { translucency: { ...translucency } } : {},
381
+ ...occlusion ? { occlusion: {
382
+ strength: occlusion.strength,
383
+ strengthApplied: true,
384
+ inVertexColors: occlusionInVertexColors
385
+ } } : {},
386
+ crown: {
387
+ center: [
388
+ center[0] * scale,
389
+ center[1] * scale,
390
+ center[2] * scale
391
+ ],
392
+ radii: [
393
+ radii[0] * scale,
394
+ radii[1] * scale,
395
+ radii[2] * scale
396
+ ]
397
+ }
398
+ };
399
+ }
400
+ /** Leaf Translucency of a baked leaf material, written as `KHR_materials_diffuse_transmission` on export. */
401
+ var diffuseTransmission = /* @__PURE__ */ new WeakMap();
402
+ /** GLTFExporter plugin: Leaf Translucency as `KHR_materials_diffuse_transmission` (factor = strength, colour = the leaf colour). */
403
+ var DiffuseTransmissionExtension = class {
404
+ writer;
405
+ name = "KHR_materials_diffuse_transmission";
406
+ constructor(writer) {
407
+ this.writer = writer;
408
+ }
409
+ async writeMaterialAsync(material, materialDef) {
410
+ const transmission = diffuseTransmission.get(material);
411
+ if (!transmission) return;
412
+ const extensions = materialDef.extensions ??= {};
413
+ extensions[this.name] = {
414
+ diffuseTransmissionFactor: transmission.factor,
415
+ diffuseTransmissionColorFactor: transmission.color
416
+ };
417
+ this.writer.extensionsUsed[this.name] = true;
418
+ }
419
+ };
214
420
  function bakedMesh(name, geometry, material) {
215
421
  const mesh = new Mesh(geometry, material);
216
422
  mesh.name = name;
@@ -232,11 +438,11 @@ async function exportBakedTree(tree, options = {}) {
232
438
  await tree.ready;
233
439
  const baked = bakeTree(tree, options);
234
440
  try {
235
- return await new GLTFExporter().parseAsync(baked, { binary: options.binary ?? true });
441
+ return await new GLTFExporter().register((writer) => new DiffuseTransmissionExtension(writer)).parseAsync(baked, { binary: options.binary ?? true });
236
442
  } finally {
237
443
  disposeBakedTree(baked);
238
444
  }
239
445
  }
240
- export { BARK_TYPES, CURRENT_SCHEMA_VERSION, DEFAULT_BRANCH_LEVEL, DEFAULT_DEFINITION, DEFAULT_FRUIT, DEFAULT_FRUIT_AMOUNT, DEFAULT_FRUIT_COLOR, DEFAULT_TEXTURE_BASE_PATH, FRUIT_TYPES, Forest, ForestTree, ForestVariant, KEYFRAME_EPSILON, LEAF_TYPES, MAX_BRANCH_LEVELS, SEASON_PROFILES, STYLE_NAMES, Tree, TreeDefinitionError, UnsupportedRendererError, Wind, WindResponse, applySeasonToLeafMaterial, assertWebGPURenderer, bakeTree, coneCurve, createBarkMaterial, createForest, createFruitSeasonNodes, createLeafMaterial, createRandom, createSeasonNodes, createTree, disposeBakedTree, evaluateSeason, exportBakedTree, extendDefinition, fetchDefinition, fruitSeason, fruitSeasonAttribute, fruitTracks, getTextureOptions, hashGeometry, hashTreeData, hexToLinear, leafSeason, leafSeasonAttribute, loadStyle, loadTexture, parseDefinition, partSeasonAt, resolveTextureUrl, sampleTrack, sceneWind, seasonShift, segmentWeight, setTextureOptions, srgbToLinear, styleLabel, styleOfShading, textureReady, woodSeasonAttribute, wrapSeason };
446
+ export { BARK_TYPES, CURRENT_SCHEMA_VERSION, DEFAULT_BRANCH_LEVEL, DEFAULT_DEFINITION, DEFAULT_FRUIT, DEFAULT_FRUIT_AMOUNT, DEFAULT_FRUIT_COLOR, DEFAULT_GROUND_TINT, DEFAULT_OCCLUSION, DEFAULT_ROOTS, DEFAULT_TEXTURE_BASE_PATH, DEFAULT_TRANSLUCENCY, FRUIT_TYPES, Forest, ForestTree, ForestVariant, KEYFRAME_EPSILON, LEAF_TYPES, MAX_BRANCH_LEVELS, SEASON_PROFILES, STYLE_NAMES, SUGGESTED_MATERIAL_FEATURES, Tree, TreeDefinitionError, UnsupportedRendererError, Wind, WindResponse, applySeasonToLeafMaterial, assertWebGPURenderer, bakeTree, coneCurve, createBarkMaterial, createForest, createFruitSeasonNodes, createLeafMaterial, createRandom, createSeasonNodes, createTree, crownDistance, crownNormal, disposeBakedTree, evaluateSeason, exportBakedTree, extendDefinition, fetchDefinition, fruitSeason, fruitSeasonAttribute, fruitTracks, getTextureOptions, hashGeometry, hashTreeData, hexToLinear, leafSeason, leafSeasonAttribute, loadStyle, loadTexture, materialFeaturesOf, parseDefinition, partSeasonAt, resolveTextureUrl, sampleTrack, sceneWind, seasonShift, segmentWeight, setTextureOptions, srgbToLinear, styleLabel, styleOfShading, textureReady, withMaterialFeatures, woodSeasonAttribute, wrapSeason };
241
447
 
242
448
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/bake/index.ts"],"sourcesContent":["import {\n BufferAttribute,\n BufferGeometry,\n Color,\n DoubleSide,\n Group,\n Mesh,\n MeshStandardMaterial,\n type Texture,\n} from 'three/webgpu';\nimport { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';\nimport type { TreeDefinition } from '../definition';\nimport type { GeometryBuffers } from '../generator';\nimport { clampGrowth, growPositions } from '../growth';\nimport { BARK_REPEAT } from '../materials/maps';\nimport { isFlatShading } from '../materials/shading';\nimport { fruitSeason, leafSeason, partSeasonAt, wrapSeason } from '../season';\nimport type { Tree } from '../tree';\n\n/**\n * Baked Tree: one tree frozen at a Seed, Growth and Season as plain static geometry with\n * standard PBR materials (`MeshStandardMaterial`, no node materials, no custom attributes), for\n * glTF export and other tools. Growth and Season are evaluated on the CPU with the same models the\n * shaders run (`growPositions`, `leafSeason`, `fruitSeason`); Wind is left out (a Baked Tree stands still).\n */\n\n/** Growth and Season to bake at; each defaults to the tree's current value. */\nexport interface BakeOptions {\n growth?: number;\n season?: number;\n}\n\n/** A triangle with (almost) no area is a part that has not sprouted yet: it is dropped. */\nconst MIN_AREA2 = 1e-16;\n\ninterface BakedBuffers {\n positions: Float32Array;\n normals: Float32Array;\n uvs: Float32Array;\n colors: Float32Array | null;\n /** Per vertex: whether it is shown at all. */\n visible: (v: number) => boolean;\n}\n\n/**\n * Keeps the triangles whose three vertices are visible and that have an area, and only the\n * vertices those triangles use. Returns null when nothing is left (glTF forbids empty meshes).\n */\nfunction compact(buffers: BakedBuffers, indices: Uint32Array, flat: boolean): BufferGeometry | null {\n const { positions } = buffers;\n const kept: number[] = [];\n const remap = new Int32Array(positions.length / 3).fill(-1);\n let count = 0;\n for (let t = 0; t < indices.length; t += 3) {\n const [a, b, c] = [indices[t]!, indices[t + 1]!, indices[t + 2]!];\n if (!buffers.visible(a) || !buffers.visible(b) || !buffers.visible(c)) continue;\n if (area2(positions, a, b, c) < MIN_AREA2) continue;\n for (const v of [a, b, c]) {\n if (remap[v] === -1) remap[v] = count++;\n kept.push(remap[v]!);\n }\n }\n if (kept.length === 0) return null;\n\n const pick = (source: Float32Array, size: number) => {\n const out = new Float32Array(count * size);\n remap.forEach((to, from) => {\n if (to >= 0) out.set(source.subarray(from * size, from * size + size), to * size);\n });\n return out;\n };\n let geometry = new BufferGeometry();\n geometry.setAttribute('position', new BufferAttribute(pick(positions, 3), 3));\n geometry.setAttribute('normal', new BufferAttribute(pick(buffers.normals, 3), 3));\n geometry.setAttribute('uv', new BufferAttribute(pick(buffers.uvs, 2), 2));\n if (buffers.colors) geometry.setAttribute('color', new BufferAttribute(pick(buffers.colors, 3), 3));\n geometry.setIndex(new BufferAttribute(Uint32Array.from(kept), 1));\n if (flat) {\n // glTF has no flat-shading switch: split the vertices and give each face its own normal.\n geometry = geometry.toNonIndexed();\n geometry.computeVertexNormals();\n }\n geometry.computeBoundingBox();\n geometry.computeBoundingSphere();\n return geometry;\n}\n\nfunction area2(p: Float32Array, a: number, b: number, c: number): number {\n const u = [p[b * 3]! - p[a * 3]!, p[b * 3 + 1]! - p[a * 3 + 1]!, p[b * 3 + 2]! - p[a * 3 + 2]!];\n const w = [p[c * 3]! - p[a * 3]!, p[c * 3 + 1]! - p[a * 3 + 1]!, p[c * 3 + 2]! - p[a * 3 + 2]!];\n const x = u[1]! * w[2]! - u[2]! * w[1]!;\n const y = u[2]! * w[0]! - u[0]! * w[2]!;\n const z = u[0]! * w[1]! - u[1]! * w[0]!;\n return x * x + y * y + z * z;\n}\n\n/** Wood: grown positions; the bark's base-to-tip darkening (smooth shading) as vertex colours. */\nfunction bakeWood(definition: TreeDefinition, wood: GeometryBuffers, growth: number): BufferGeometry | null {\n const flat = isFlatShading(definition.materials.shading);\n let colors: Float32Array | null = null;\n if (!flat) {\n // Same as the bark colorNode: mix(base * 0.75, base, sqrt(clamp(uv.y))).\n colors = new Float32Array(wood.positions.length);\n for (let v = 0; v < colors.length / 3; v++) {\n const shade = 0.75 + 0.25 * Math.sqrt(Math.min(Math.max(wood.uvs[v * 2 + 1]!, 0), 1));\n colors.fill(shade, v * 3, v * 3 + 3);\n }\n }\n return compact(\n { positions: growPositions(wood, growth), normals: wood.normals, uvs: wood.uvs, colors, visible: () => true },\n wood.indices,\n flat,\n );\n}\n\n/** Leaves: grown positions; fallen leaves dropped; Season (or blossom) colour × the Seed's tint as vertex colours. */\nfunction bakeLeaves(definition: TreeDefinition, leaves: GeometryBuffers, growth: number, season: number): BufferGeometry | null {\n const count = leaves.positions.length / 3;\n const aSeason = leaves.attributes.aSeason!.array;\n const shown = new Uint8Array(count);\n const colors = new Float32Array(count * 3);\n for (let v = 0; v < count; v++) {\n const state = leafSeason(definition.season, season, partSeasonAt(aSeason, v));\n shown[v] = state.visible ? 1 : 0;\n for (let c = 0; c < 3; c++) colors[v * 3 + c] = state.color[c]! * (leaves.colors?.[v * 3 + c] ?? 1);\n }\n return compact(\n { positions: growPositions(leaves, growth), normals: leaves.normals, uvs: leaves.uvs, colors, visible: (v) => shown[v] === 1 },\n leaves.indices,\n isFlatShading(definition.materials.shading),\n );\n}\n\n/**\n * Fruit: each Fruit scaled about its attachment point by the Fruit amount (dropped when not\n * shown), then grown; the Fruit colour × the Seed's tint as vertex colours. Same order as the shader.\n */\nfunction bakeFruit(definition: TreeDefinition, fruit: GeometryBuffers, growth: number, season: number): BufferGeometry | null {\n const count = fruit.positions.length / 3;\n if (count === 0) return null;\n const aSeason = fruit.attributes.aSeason!.array;\n const aOrigin = fruit.attributes.aOrigin!.array;\n const shown = new Uint8Array(count);\n const colors = new Float32Array(count * 3);\n const scaled = new Float32Array(count * 3);\n for (let v = 0; v < count; v++) {\n const state = fruitSeason(definition.season, season, partSeasonAt(aSeason, v));\n shown[v] = state.visible ? 1 : 0;\n for (let c = 0; c < 3; c++) {\n const i = v * 3 + c;\n colors[i] = state.color[c]! * (fruit.colors?.[i] ?? 1);\n scaled[i] = aOrigin[i]! + (fruit.positions[i]! - aOrigin[i]!) * state.scale;\n }\n }\n return compact(\n {\n positions: growPositions({ ...fruit, positions: scaled }, growth),\n normals: fruit.normals,\n uvs: fruit.uvs,\n colors,\n visible: (v) => shown[v] === 1,\n },\n fruit.indices,\n isFlatShading(definition.materials.shading),\n );\n}\n\n/** A loaded texture for the baked material (a copy, so the tree's shared texture is untouched); null without image data. */\nfunction bakedMap(texture: Texture | null | undefined, repeat?: readonly [number, number]): Texture | null {\n if (!texture?.image) return null;\n const copy = texture.clone();\n if (repeat) copy.repeat.set(...repeat);\n return copy;\n}\n\n/**\n * Freezes a tree at a Growth and Season (default: the tree's own) into a static `Group` of\n * meshes `wood`, `leaves` and `fruit` (a mesh with nothing to show is left out) with standard PBR\n * materials: no node materials, no Growth/Season/Wind attributes, no animation. The result is\n * independent of `tree`; call `disposeBakedTree` when done with it.\n */\nexport function bakeTree(tree: Tree, options: BakeOptions = {}): Group {\n const { definition, data } = tree;\n const source = tree.wood.material as MeshStandardMaterial; // MeshStandardNodeMaterial: same props\n const growth = clampGrowth(options.growth ?? tree.growth);\n const season = wrapSeason(options.season ?? tree.season);\n const bark = definition.materials.bark;\n const flat = isFlatShading(definition.materials.shading);\n\n const group = new Group();\n group.name = definition.name || 'Tree';\n group.userData = { seed: tree.seed, growth, season };\n\n const woodGeometry = bakeWood(definition, data.wood, growth);\n if (woodGeometry) {\n const material = new MeshStandardMaterial({\n name: 'bark',\n color: new Color(bark.color),\n roughness: bark.roughness,\n metalness: 0,\n vertexColors: woodGeometry.hasAttribute('color'),\n flatShading: flat,\n map: bakedMap(source.map, BARK_REPEAT),\n normalMap: bakedMap(source.normalMap, BARK_REPEAT),\n });\n group.add(bakedMesh('wood', woodGeometry, material));\n }\n\n const leafGeometry = bakeLeaves(definition, data.leaves, growth, season);\n if (leafGeometry) {\n const map = bakedMap(tree.leaves.material.map);\n const material = new MeshStandardMaterial({\n name: 'leaves',\n color: 0xffffff,\n roughness: definition.materials.leaf.roughness,\n metalness: 0,\n vertexColors: true,\n flatShading: flat,\n side: DoubleSide,\n map,\n alphaTest: map ? definition.materials.leaf.alphaTest : 0,\n });\n group.add(bakedMesh('leaves', leafGeometry, material));\n }\n\n const fruitGeometry = bakeFruit(definition, data.fruit, growth, season);\n if (fruitGeometry) {\n const material = new MeshStandardMaterial({\n name: 'fruit',\n color: 0xffffff,\n roughness: tree.fruit.material.roughness,\n metalness: 0,\n vertexColors: true,\n flatShading: flat,\n });\n group.add(bakedMesh('fruit', fruitGeometry, material));\n }\n return group;\n}\n\nfunction bakedMesh(name: string, geometry: BufferGeometry, material: MeshStandardMaterial): Mesh {\n const mesh = new Mesh(geometry, material);\n mesh.name = name;\n mesh.castShadow = mesh.receiveShadow = true;\n return mesh;\n}\n\n/** Frees the geometries, materials and texture copies of a baked tree. */\nexport function disposeBakedTree(baked: Group): void {\n baked.traverse((object) => {\n if (!(object instanceof Mesh)) return;\n object.geometry.dispose();\n const material = object.material as MeshStandardMaterial;\n material.map?.dispose();\n material.normalMap?.dispose();\n material.dispose();\n });\n}\n\nexport interface ExportBakedTreeOptions extends BakeOptions {\n /** `.glb` (ArrayBuffer, default) or `.gltf` JSON with embedded buffers. */\n binary?: boolean;\n}\n\n/**\n * Bakes a tree (see {@link bakeTree}) and writes it as glTF 2.0: a `.glb` ArrayBuffer by default,\n * or the `.gltf` JSON object with `binary: false`. Waits for the tree's textures first. In Node,\n * three's GLTFExporter needs a `FileReader` global.\n */\nexport function exportBakedTree(tree: Tree, options?: ExportBakedTreeOptions & { binary?: true }): Promise<ArrayBuffer>;\nexport function exportBakedTree(tree: Tree, options: ExportBakedTreeOptions & { binary: false }): Promise<Record<string, unknown>>;\nexport function exportBakedTree(tree: Tree, options?: ExportBakedTreeOptions): Promise<ArrayBuffer | Record<string, unknown>>;\nexport async function exportBakedTree(\n tree: Tree,\n options: ExportBakedTreeOptions = {},\n): Promise<ArrayBuffer | Record<string, unknown>> {\n await tree.ready;\n const baked = bakeTree(tree, options);\n try {\n const result = await new GLTFExporter().parseAsync(baked, { binary: options.binary ?? true });\n return result as ArrayBuffer | Record<string, unknown>;\n } finally {\n disposeBakedTree(baked);\n }\n}\n"],"mappings":";;;;;;;AAiCA,IAAM,YAAY;;;;;AAelB,SAAS,QAAQ,SAAuB,SAAsB,MAAsC;CAClG,MAAM,EAAE,cAAc;CACtB,MAAM,OAAiB,CAAC;CACxB,MAAM,QAAQ,IAAI,WAAW,UAAU,SAAS,CAAC,CAAC,CAAC,KAAK,EAAE;CAC1D,IAAI,QAAQ;CACZ,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK,GAAG;EAC1C,MAAM,CAAC,GAAG,GAAG,KAAK;GAAC,QAAQ;GAAK,QAAQ,IAAI;GAAK,QAAQ,IAAI;EAAG;EAChE,IAAI,CAAC,QAAQ,QAAQ,CAAC,KAAK,CAAC,QAAQ,QAAQ,CAAC,KAAK,CAAC,QAAQ,QAAQ,CAAC,GAAG;EACvE,IAAI,MAAM,WAAW,GAAG,GAAG,CAAC,IAAI,WAAW;EAC3C,KAAK,MAAM,KAAK;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QAAQ,CAAC;CACvD;CAEA,MAAM,gBAAgB,UAAU,YAAY,KAAK,OAAO,QAAQ,MAAM;CACtE,IAAI,eAAe;EACjB,MAAM,WAAW,IAAI,qBAAqB;GACxC,MAAM;GACN,OAAO;GACP,WAAW,KAAK,MAAM,SAAS;GAC/B,WAAW;GACX,cAAc;GACd,aAAa;EACf,CAAC;EACD,MAAM,IAAI,UAAU,SAAS,eAAe,QAAQ,CAAC;CACvD;CACA,OAAO;AACT;AAEA,SAAS,UAAU,MAAc,UAA0B,UAAsC;CAC/F,MAAM,OAAO,IAAI,KAAK,UAAU,QAAQ;CACxC,KAAK,OAAO;CACZ,KAAK,aAAa,KAAK,gBAAgB;CACvC,OAAO;AACT;;AAGA,SAAgB,iBAAiB,OAAoB;CACnD,MAAM,UAAU,WAAW;EACzB,IAAI,EAAE,kBAAkB,OAAO;EAC/B,OAAO,SAAS,QAAQ;EACxB,MAAM,WAAW,OAAO;EACxB,SAAS,KAAK,QAAQ;EACtB,SAAS,WAAW,QAAQ;EAC5B,SAAS,QAAQ;CACnB,CAAC;AACH;AAeA,eAAsB,gBACpB,MACA,UAAkC,CAAC,GACa;CAChD,MAAM,KAAK;CACX,MAAM,QAAQ,SAAS,MAAM,OAAO;CACpC,IAAI;EAEF,OAAO,MADc,IAAI,aAAa,CAAC,CAAC,WAAW,OAAO,EAAE,QAAQ,QAAQ,UAAU,KAAK,CAAC;CAE9F,UAAU;EACR,iBAAiB,KAAK;CACxB;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/bake/index.ts"],"sourcesContent":["import {\n BufferAttribute,\n BufferGeometry,\n Color,\n DoubleSide,\n Group,\n type Material,\n Mesh,\n MeshStandardMaterial,\n type Texture,\n} from 'three/webgpu';\nimport { GLTFExporter, type GLTFExporterPlugin, type GLTFWriter } from 'three/addons/exporters/GLTFExporter.js';\nimport type { MaterialFeatures, TranslucencyDefinition, TreeDefinition } from '../definition';\nimport { crownNormal, type CrownVolume, type GeometryBuffers } from '../generator';\nimport { clampGrowth, growPositions, treeScale } from '../growth';\nimport { groundTintAmount } from '../materials/ground-tint';\nimport { BARK_REPEAT } from '../materials/maps';\nimport { isFlatShading } from '../materials/shading';\nimport { fruitSeason, hexToLinear, leafSeason, partSeasonAt, wrapSeason } from '../season';\nimport type { Tree } from '../tree';\n\n/**\n * Baked Tree: one tree frozen at a Seed, Growth and Season as plain static geometry with\n * standard PBR materials (`MeshStandardMaterial`, no node materials), for glTF export and other tools.\n * Growth and Season are evaluated on the CPU with the same models the shaders run (`growPositions`,\n * `leafSeason`, `fruitSeason`); Wind is left out (a Baked Tree stands still).\n *\n * Material Features (ADR 0008) are baked into standard glTF channels: Crown Normals blended into the normals,\n * Structural Occlusion as a `_occlusion` attribute (glTF `_OCCLUSION`, strength already applied; optionally also in the vertex\n * colours), Leaf Translucency as `KHR_materials_diffuse_transmission` (written by `exportBakedTree`),\n * and the settings with the Crown Volume in `userData.treejs` of the leaf and bark materials (glTF\n * `extras`). With no Material Feature set, the result is exactly as without them.\n */\n\n/** Growth and Season to bake at; each defaults to the tree's current value. */\nexport interface BakeOptions {\n growth?: number;\n season?: number;\n /**\n * With Structural Occlusion (`materials.occlusion`): also multiply the occlusion into the vertex\n * colours (`COLOR_0`), for engines that only read vertex colours. It then darkens direct light too.\n * Default false: `COLOR_0` is as without the feature, and the occlusion is only in `_OCCLUSION`.\n */\n occlusionInVertexColors?: boolean;\n}\n\n/** A triangle with (almost) no area is a part that has not sprouted yet: it is dropped. */\nconst MIN_AREA2 = 1e-16;\n\ninterface BakedBuffers {\n positions: Float32Array;\n normals: Float32Array;\n uvs: Float32Array;\n colors: Float32Array | null;\n /** Structural Occlusion per vertex (0 = occluded, 1 = open), written as `_OCCLUSION`; null without it. */\n occlusion: Float32Array | null;\n /** Per vertex: whether it is shown at all. */\n visible: (v: number) => boolean;\n /** Crown Normals: the normals are blended towards these Crown Volume normals (per vertex) by `amount`. */\n crownNormals?: BakedCrownNormals;\n}\n\ninterface BakedCrownNormals {\n normals: Float32Array;\n amount: number;\n /** Per vertex: its card is turned to face the crown's outside (winding reversed, `normals` already flipped). */\n flipped: Uint8Array;\n}\n\n/**\n * Keeps the triangles whose three vertices are visible and that have an area, and only the\n * vertices those triangles use. Returns null when nothing is left (glTF forbids empty meshes).\n */\nfunction compact(buffers: BakedBuffers, indices: Uint32Array, flat: boolean): BufferGeometry | null {\n const { positions } = buffers;\n const kept: number[] = [];\n const remap = new Int32Array(positions.length / 3).fill(-1);\n let count = 0;\n for (let t = 0; t < indices.length; t += 3) {\n const [a, b, c] = [indices[t]!, indices[t + 1]!, indices[t + 2]!];\n if (!buffers.visible(a) || !buffers.visible(b) || !buffers.visible(c)) continue;\n if (area2(positions, a, b, c) < MIN_AREA2) continue;\n for (const v of buffers.crownNormals?.flipped[a] ? [a, c, b] : [a, b, c]) {\n if (remap[v] === -1) remap[v] = count++;\n kept.push(remap[v]!);\n }\n }\n if (kept.length === 0) return null;\n\n const pick = (source: Float32Array, size: number) => {\n const out = new Float32Array(count * size);\n remap.forEach((to, from) => {\n if (to >= 0) out.set(source.subarray(from * size, from * size + size), to * size);\n });\n return out;\n };\n let geometry = new BufferGeometry();\n geometry.setAttribute('position', new BufferAttribute(pick(positions, 3), 3));\n geometry.setAttribute('normal', new BufferAttribute(pick(buffers.normals, 3), 3));\n geometry.setAttribute('uv', new BufferAttribute(pick(buffers.uvs, 2), 2));\n if (buffers.colors) geometry.setAttribute('color', new BufferAttribute(pick(buffers.colors, 3), 3));\n if (buffers.occlusion) geometry.setAttribute(OCCLUSION, new BufferAttribute(pick(buffers.occlusion, 1), 1));\n if (buffers.crownNormals) geometry.setAttribute(CROWN_NORMAL, new BufferAttribute(pick(buffers.crownNormals.normals, 3), 3));\n geometry.setIndex(new BufferAttribute(Uint32Array.from(kept), 1));\n if (flat) {\n // glTF has no flat-shading switch: split the vertices and give each face its own normal.\n geometry = geometry.toNonIndexed();\n geometry.computeVertexNormals();\n }\n if (buffers.crownNormals) {\n // After the split, so under flat shading the facet normals are blended and the facets stay visible below 1.\n blendNormals(geometry, buffers.crownNormals.amount);\n geometry.deleteAttribute(CROWN_NORMAL);\n }\n geometry.computeBoundingBox();\n geometry.computeBoundingSphere();\n return geometry;\n}\n\n/** The geometry attribute GLTFExporter writes as the `_OCCLUSION` vertex attribute. */\nconst OCCLUSION = '_occlusion';\n/** Scratch attribute: the Crown Volume normal per vertex, removed once the normals are blended. */\nconst CROWN_NORMAL = 'crownNormal';\n\n/** `normalize(mix(normal, crown normal, amount))`, as the leaf material's normalNode; the crown's where they cancel out. */\nfunction blendNormals(geometry: BufferGeometry, amount: number): void {\n const normal = geometry.getAttribute('normal');\n const crown = geometry.getAttribute(CROWN_NORMAL);\n for (let v = 0; v < normal.count; v++) {\n const c = [crown.getX(v), crown.getY(v), crown.getZ(v)];\n let x = normal.getX(v) + (c[0]! - normal.getX(v)) * amount;\n let y = normal.getY(v) + (c[1]! - normal.getY(v)) * amount;\n let z = normal.getZ(v) + (c[2]! - normal.getZ(v)) * amount;\n const length = Math.sqrt(x * x + y * y + z * z);\n if (length > 1e-4) [x, y, z] = [x / length, y / length, z / length];\n else [x, y, z] = c as [number, number, number];\n normal.setXYZ(v, x, y, z);\n }\n}\n\nfunction area2(p: Float32Array, a: number, b: number, c: number): number {\n const u = [p[b * 3]! - p[a * 3]!, p[b * 3 + 1]! - p[a * 3 + 1]!, p[b * 3 + 2]! - p[a * 3 + 2]!];\n const w = [p[c * 3]! - p[a * 3]!, p[c * 3 + 1]! - p[a * 3 + 1]!, p[c * 3 + 2]! - p[a * 3 + 2]!];\n const x = u[1]! * w[2]! - u[2]! * w[1]!;\n const y = u[2]! * w[0]! - u[0]! * w[2]!;\n const z = u[0]! * w[1]! - u[1]! * w[0]!;\n return x * x + y * y + z * z;\n}\n\n/**\n * Wood: grown positions; the bark's base-to-tip darkening (smooth shading) as vertex colours.\n * With a Ground Tint the vertex colours carry the whole bark colour (the material is white), tinted\n * near the ground on the grown positions, like the bark colorNode.\n */\nfunction bakeWood(definition: TreeDefinition, wood: GeometryBuffers, growth: number, occlusion: BakedOcclusion): BufferGeometry | null {\n const flat = isFlatShading(definition.materials.shading);\n const { color, groundTint } = definition.materials.bark;\n const positions = growPositions(wood, growth);\n let colors: Float32Array | null = null;\n if (!flat || groundTint) {\n // Same as the bark colorNode: mix(base * 0.75, base, sqrt(clamp(uv.y))), then the Ground Tint.\n colors = new Float32Array(wood.positions.length);\n const bark = groundTint ? hexToLinear(color) : [1, 1, 1];\n const tint = groundTint ? hexToLinear(groundTint.color) : [1, 1, 1];\n for (let v = 0; v < colors.length / 3; v++) {\n const shade = flat ? 1 : 0.75 + 0.25 * Math.sqrt(Math.min(Math.max(wood.uvs[v * 2 + 1]!, 0), 1));\n const amount = groundTint ? groundTintAmount(groundTint, positions[v * 3 + 1]!) : 0;\n for (let c = 0; c < 3; c++) colors[v * 3 + c] = bark[c]! * shade * (1 - amount) + tint[c]! * amount;\n }\n }\n return compact({ positions, normals: wood.normals, uvs: wood.uvs, ...occlusion.of(wood, colors), visible: () => true }, wood.indices, flat);\n}\n\n/**\n * Leaves: grown positions; fallen leaves dropped; Season (or blossom) colour × the Seed's tint as vertex\n * colours. Also returns the mean colour of the shown leaves (linear, before any occlusion), the colour\n * Leaf Translucency glows in.\n */\nfunction bakeLeaves(\n definition: TreeDefinition,\n leaves: GeometryBuffers,\n growth: number,\n season: number,\n occlusion: BakedOcclusion,\n crown: CrownVolume,\n amount: number | undefined,\n): { geometry: BufferGeometry | null; meanColor: [number, number, number] } {\n const count = leaves.positions.length / 3;\n const aSeason = leaves.attributes.aSeason!.array;\n const shown = new Uint8Array(count);\n const colors = new Float32Array(count * 3);\n for (let v = 0; v < count; v++) {\n const state = leafSeason(definition.season, season, partSeasonAt(aSeason, v));\n shown[v] = state.visible ? 1 : 0;\n for (let c = 0; c < 3; c++) colors[v * 3 + c] = state.color[c]! * (leaves.colors?.[v * 3 + c] ?? 1);\n }\n const meanColor = meanShownColor(colors, shown);\n const positions = growPositions(leaves, growth);\n const crownNormals = amount ? bakedCrownNormals(leaves, positions, growth, crown, amount, definition.leaves.shape === 'card') : undefined;\n const geometry = compact(\n {\n positions,\n normals: crownNormals ? orient(leaves.normals, crownNormals.flipped) : leaves.normals,\n uvs: leaves.uvs,\n ...occlusion.of(leaves, colors),\n visible: (v) => shown[v] === 1,\n crownNormals,\n },\n leaves.indices,\n isFlatShading(definition.materials.shading),\n );\n return { geometry, meanColor };\n}\n\n/** Mean of the colours of the shown vertices (each channel at most 1); black when none is shown. */\nfunction meanShownColor(colors: Float32Array, shown: Uint8Array): [number, number, number] {\n const sum: [number, number, number] = [0, 0, 0];\n let count = 0;\n shown.forEach((on, v) => {\n if (!on) return;\n for (let c = 0; c < 3; c++) sum[c]! += colors[v * 3 + c]!;\n count++;\n });\n return sum.map((c) => Math.min(c / Math.max(count, 1), 1)) as [number, number, number];\n}\n\n/**\n * Crown Normals for the leaves: the Crown Volume's normal at each grown vertex (the Volume scaled by\n * the Growth scale, as in the material), and which leaf cards to turn around. A card (`leaves.shape`\n * 'card') is flat and double-sided with one normal for both sides: turning it (normal and winding\n * together) changes nothing else, but makes its front face the crown's outside, so in engines that flip\n * the normal of back faces the blended normal of every card points out. Decided per card at its attachment\n * point (`aOrigin`, shared by its vertices). Solid leaf shapes are closed: their front faces are already\n * their outside, and they keep their winding.\n */\nfunction bakedCrownNormals(\n leaves: GeometryBuffers,\n grown: Float32Array,\n growth: number,\n crown: CrownVolume,\n amount: number,\n cards: boolean,\n): BakedCrownNormals {\n const count = grown.length / 3;\n const scale = treeScale(growth);\n const origin = leaves.attributes.aOrigin!.array;\n const n = leaves.normals;\n const normals = new Float32Array(count * 3);\n const flipped = new Uint8Array(count);\n for (let v = 0; v < count; v++) {\n const i = v * 3;\n normals.set(crownNormal(crown, [grown[i]! / scale, grown[i + 1]! / scale, grown[i + 2]! / scale]), i);\n if (!cards) continue;\n const out = crownNormal(crown, [origin[i]!, origin[i + 1]!, origin[i + 2]!]);\n flipped[v] = n[i]! * out[0] + n[i + 1]! * out[1] + n[i + 2]! * out[2] < 0 ? 1 : 0;\n }\n return { normals, amount, flipped };\n}\n\n/** The normals with those of `flipped` vertices reversed. */\nfunction orient(normals: Float32Array, flipped: Uint8Array): Float32Array {\n const out = normals.slice();\n flipped.forEach((flip, v) => {\n if (flip) for (let c = 0; c < 3; c++) out[v * 3 + c] = -out[v * 3 + c]!;\n });\n return out;\n}\n\n/**\n * Structural Occlusion as baked, for one part with its vertex colours (null: none): `occlusion` is\n * `mix(1, aOcclusion, strength)` per vertex (what the material's aoNode shows), null when the tree has\n * none. With `inColors` the colours come back multiplied by it (in place; a part without colours gets\n * the occlusion as grey ones), else unchanged.\n */\ninterface BakedOcclusion {\n of(part: GeometryBuffers, colors: Float32Array | null): { occlusion: Float32Array | null; colors: Float32Array | null };\n}\n\nfunction bakedOcclusion(strength: number | null, inColors: boolean): BakedOcclusion {\n return {\n of: (part, colors) => {\n const ao = part.attributes.aOcclusion?.array;\n if (strength === null || !ao) return { occlusion: null, colors };\n const occlusion = Float32Array.from(ao, (a) => 1 - strength * (1 - a));\n if (!inColors) return { occlusion, colors };\n return { occlusion, colors: darken(colors ?? new Float32Array(part.positions.length).fill(1), occlusion) };\n },\n };\n}\n\n/** Each vertex's colour times its occlusion (in place). */\nfunction darken(colors: Float32Array, occlusion: Float32Array): Float32Array {\n for (let i = 0; i < colors.length; i++) colors[i]! *= occlusion[Math.floor(i / 3)]!;\n return colors;\n}\n\n/**\n * Fruit: each Fruit scaled about its attachment point by the Fruit amount (dropped when not\n * shown), then grown; the Fruit colour × the Seed's tint as vertex colours. Same order as the shader.\n */\nfunction bakeFruit(\n definition: TreeDefinition,\n fruit: GeometryBuffers,\n growth: number,\n season: number,\n occlusion: BakedOcclusion,\n): BufferGeometry | null {\n const count = fruit.positions.length / 3;\n if (count === 0) return null;\n const aSeason = fruit.attributes.aSeason!.array;\n const aOrigin = fruit.attributes.aOrigin!.array;\n const shown = new Uint8Array(count);\n const colors = new Float32Array(count * 3);\n const scaled = new Float32Array(count * 3);\n for (let v = 0; v < count; v++) {\n const state = fruitSeason(definition.season, season, partSeasonAt(aSeason, v));\n shown[v] = state.visible ? 1 : 0;\n for (let c = 0; c < 3; c++) {\n const i = v * 3 + c;\n colors[i] = state.color[c]! * (fruit.colors?.[i] ?? 1);\n scaled[i] = aOrigin[i]! + (fruit.positions[i]! - aOrigin[i]!) * state.scale;\n }\n }\n return compact(\n {\n positions: growPositions({ ...fruit, positions: scaled }, growth),\n normals: fruit.normals,\n uvs: fruit.uvs,\n ...occlusion.of(fruit, colors),\n visible: (v) => shown[v] === 1,\n },\n fruit.indices,\n isFlatShading(definition.materials.shading),\n );\n}\n\n/** A loaded texture for the baked material (a copy, so the tree's shared texture is untouched); null without image data. */\nfunction bakedMap(texture: Texture | null | undefined, repeat?: readonly [number, number]): Texture | null {\n if (!texture?.image) return null;\n const copy = texture.clone();\n if (repeat) copy.repeat.set(...repeat);\n return copy;\n}\n\n/**\n * Freezes a tree at a Growth and Season (default: the tree's own) into a static `Group` of\n * meshes `wood`, `leaves` and `fruit` (a mesh with nothing to show is left out) with standard PBR\n * materials: no node materials, no Growth/Season/Wind attributes, no animation. Material Features\n * are baked in (see the top of this module). The result is\n * independent of `tree`; call `disposeBakedTree` when done with it.\n */\nexport function bakeTree(tree: Tree, options: BakeOptions = {}): Group {\n const { definition, data } = tree;\n const source = tree.wood.material as MeshStandardMaterial; // MeshStandardNodeMaterial: same props\n const growth = clampGrowth(options.growth ?? tree.growth);\n const season = wrapSeason(options.season ?? tree.season);\n const bark = definition.materials.bark;\n const flat = isFlatShading(definition.materials.shading);\n // The features as the tree shows them now (values tuned live included).\n const features = tree.materialFeatures;\n const occlusion = bakedOcclusion(features.occlusion?.strength ?? null, options.occlusionInVertexColors ?? false);\n const extras = materialFeatureExtras(features, tree.data.crown, growth, options.occlusionInVertexColors ?? false);\n\n const group = new Group();\n group.name = definition.name || 'Tree';\n group.userData = { seed: tree.seed, growth, season };\n\n const woodGeometry = bakeWood(definition, data.wood, growth, occlusion);\n if (woodGeometry) {\n const material = new MeshStandardMaterial({\n name: 'bark',\n color: new Color(bark.groundTint ? 0xffffff : bark.color),\n roughness: bark.roughness,\n metalness: 0,\n vertexColors: woodGeometry.hasAttribute('color'),\n flatShading: flat,\n map: bakedMap(source.map, BARK_REPEAT),\n normalMap: bakedMap(source.normalMap, BARK_REPEAT),\n });\n if (extras) material.userData = { treejs: extras };\n group.add(bakedMesh('wood', woodGeometry, material));\n }\n\n const { geometry: leafGeometry, meanColor } = bakeLeaves(definition, data.leaves, growth, season, occlusion, data.crown, features.crownNormals);\n if (leafGeometry) {\n const map = bakedMap(tree.leaves.material.map);\n const material = new MeshStandardMaterial({\n name: 'leaves',\n color: 0xffffff,\n roughness: definition.materials.leaf.roughness,\n metalness: 0,\n vertexColors: true,\n flatShading: flat,\n side: DoubleSide,\n map,\n alphaTest: map ? definition.materials.leaf.alphaTest : 0,\n });\n if (extras) material.userData = { treejs: extras };\n const { translucency } = features;\n // The transmission colour is the leaves' own colour (without the occlusion of `occlusionInVertexColors`).\n if (translucency) diffuseTransmission.set(material, { factor: translucency.strength, color: meanColor });\n group.add(bakedMesh('leaves', leafGeometry, material));\n }\n\n const fruitGeometry = bakeFruit(definition, data.fruit, growth, season, occlusion);\n if (fruitGeometry) {\n const material = new MeshStandardMaterial({\n name: 'fruit',\n color: 0xffffff,\n roughness: tree.fruit.material.roughness,\n metalness: 0,\n vertexColors: true,\n flatShading: flat,\n });\n group.add(bakedMesh('fruit', fruitGeometry, material));\n }\n return group;\n}\n\n/**\n * The `treejs` object in the extras of the baked leaf and bark materials: the Material Feature\n * settings and the Crown Volume, for engines that rebuild the effects in their own shaders. The Crown\n * Volume is in the Baked Tree's space (scaled by its Growth, like the geometry). Null when the tree has\n * no Material Feature, so its glTF is as without them.\n */\nexport interface MaterialFeatureExtras {\n /** Crown Normals amount; the baked `NORMAL` already has them blended in. */\n crownNormals?: number;\n /** Leaf Translucency settings (also written as `KHR_materials_diffuse_transmission`). */\n translucency?: TranslucencyDefinition;\n occlusion?: {\n /** The Structural Occlusion strength the tree had. */\n strength: number;\n /**\n * Always true: the baked `_OCCLUSION` is final, `mix(1, aOcclusion, strength)`, with the strength\n * already applied. Use it as AO as it is; do not apply `strength` again.\n */\n strengthApplied: true;\n /** Whether `COLOR_0` is also multiplied by `_OCCLUSION` (`occlusionInVertexColors`). */\n inVertexColors: boolean;\n };\n crown: CrownVolume;\n}\n\nfunction materialFeatureExtras(\n features: MaterialFeatures,\n crown: CrownVolume,\n growth: number,\n occlusionInVertexColors: boolean,\n): MaterialFeatureExtras | null {\n const { crownNormals, translucency, occlusion } = features;\n if (!crownNormals && !translucency && !occlusion) return null;\n const scale = treeScale(growth);\n const { center, radii } = crown;\n return {\n ...(crownNormals ? { crownNormals } : {}),\n ...(translucency ? { translucency: { ...translucency } } : {}),\n ...(occlusion ? { occlusion: { strength: occlusion.strength, strengthApplied: true, inVertexColors: occlusionInVertexColors } } : {}),\n crown: { center: [center[0] * scale, center[1] * scale, center[2] * scale], radii: [radii[0] * scale, radii[1] * scale, radii[2] * scale] },\n };\n}\n\n/** Leaf Translucency of a baked leaf material, written as `KHR_materials_diffuse_transmission` on export. */\nconst diffuseTransmission = new WeakMap<Material, { factor: number; color: [number, number, number] }>();\n\n/** GLTFExporter plugin: Leaf Translucency as `KHR_materials_diffuse_transmission` (factor = strength, colour = the leaf colour). */\nclass DiffuseTransmissionExtension implements GLTFExporterPlugin {\n readonly name = 'KHR_materials_diffuse_transmission';\n constructor(private readonly writer: GLTFWriter) {}\n\n async writeMaterialAsync(material: Material, materialDef: Record<string, unknown>): Promise<void> {\n const transmission = diffuseTransmission.get(material);\n if (!transmission) return;\n const extensions = (materialDef.extensions ??= {}) as Record<string, unknown>;\n extensions[this.name] = { diffuseTransmissionFactor: transmission.factor, diffuseTransmissionColorFactor: transmission.color };\n (this.writer as unknown as { extensionsUsed: Record<string, boolean> }).extensionsUsed[this.name] = true;\n }\n}\n\nfunction bakedMesh(name: string, geometry: BufferGeometry, material: MeshStandardMaterial): Mesh {\n const mesh = new Mesh(geometry, material);\n mesh.name = name;\n mesh.castShadow = mesh.receiveShadow = true;\n return mesh;\n}\n\n/** Frees the geometries, materials and texture copies of a baked tree. */\nexport function disposeBakedTree(baked: Group): void {\n baked.traverse((object) => {\n if (!(object instanceof Mesh)) return;\n object.geometry.dispose();\n const material = object.material as MeshStandardMaterial;\n material.map?.dispose();\n material.normalMap?.dispose();\n material.dispose();\n });\n}\n\nexport interface ExportBakedTreeOptions extends BakeOptions {\n /** `.glb` (ArrayBuffer, default) or `.gltf` JSON with embedded buffers. */\n binary?: boolean;\n}\n\n/**\n * Bakes a tree (see {@link bakeTree}) and writes it as glTF 2.0: a `.glb` ArrayBuffer by default,\n * or the `.gltf` JSON object with `binary: false`. Waits for the tree's textures first. In Node,\n * three's GLTFExporter needs a `FileReader` global.\n */\nexport function exportBakedTree(tree: Tree, options?: ExportBakedTreeOptions & { binary?: true }): Promise<ArrayBuffer>;\nexport function exportBakedTree(tree: Tree, options: ExportBakedTreeOptions & { binary: false }): Promise<Record<string, unknown>>;\nexport function exportBakedTree(tree: Tree, options?: ExportBakedTreeOptions): Promise<ArrayBuffer | Record<string, unknown>>;\nexport async function exportBakedTree(\n tree: Tree,\n options: ExportBakedTreeOptions = {},\n): Promise<ArrayBuffer | Record<string, unknown>> {\n await tree.ready;\n const baked = bakeTree(tree, options);\n try {\n const exporter = new GLTFExporter().register((writer) => new DiffuseTransmissionExtension(writer));\n const result = await exporter.parseAsync(baked, { binary: options.binary ?? true });\n return result as ArrayBuffer | Record<string, unknown>;\n } finally {\n disposeBakedTree(baked);\n }\n}\n"],"mappings":";;;;;;;AA+CA,IAAM,YAAY;;;;;AA0BlB,SAAS,QAAQ,SAAuB,SAAsB,MAAsC;CAClG,MAAM,EAAE,cAAc;CACtB,MAAM,OAAiB,CAAC;CACxB,MAAM,QAAQ,IAAI,WAAW,UAAU,SAAS,CAAC,CAAC,CAAC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B,SAAS,WAAW,QAAQ;EAC5B,SAAS,QAAQ;CACnB,CAAC;AACH;AAeA,eAAsB,gBACpB,MACA,UAAkC,CAAC,GACa;CAChD,MAAM,KAAK;CACX,MAAM,QAAQ,SAAS,MAAM,OAAO;CACpC,IAAI;EAGF,OAAO,MAFU,IAAI,aAAa,CAAC,CAAC,UAAU,WAAW,IAAI,6BAA6B,MAAM,CAC3E,CAAA,CAAS,WAAW,OAAO,EAAE,QAAQ,QAAQ,UAAU,KAAK,CAAC;CAEpF,UAAU;EACR,iBAAiB,KAAK;CACxB;AACF"}
@@ -0,0 +1,20 @@
1
+ import type { Node } from 'three/webgpu';
2
+ import type { CrownVolume } from '../generator';
3
+ /** The Crown Volume measured at a point of the tree, in TSL (fragment stage). */
4
+ export interface CrownNodes {
5
+ /**
6
+ * Unit outward normal of the Volume's ellipsoid through the point, in tree space (twin of `crownNormal`).
7
+ * Straight up at the centre. Turn it into view space with `transformNormalToView` (a Forest first
8
+ * rotates it by the instance).
9
+ */
10
+ normal: Node<'vec3'>;
11
+ /** How far the point sits from the centre in units of the ellipsoid: 0 centre, 1 shell (twin of `crownDistance`). */
12
+ distance: Node<'float'>;
13
+ }
14
+ /**
15
+ * The Crown Volume (GLOSSARY) measured at the grown tree-space position (Growth `growth`, before Wind,
16
+ * so Wind doesn't make it flicker). The Volume scales with the tree's Growth scale, as the vertices do,
17
+ * so a sapling is measured against its own, smaller crown. Shared by the Material Features.
18
+ */
19
+ export declare function crownNodes(crown: CrownVolume, growth: Node<'float'>): CrownNodes;
20
+ //# sourceMappingURL=crown-nodes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crown-nodes.d.ts","sourceRoot":"","sources":["../../src/materials/crown-nodes.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAGhD,iFAAiF;AACjF,MAAM,WAAW,UAAU;IACzB;;;;OAIG;IACH,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;IACrB,qHAAqH;IACrH,QAAQ,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;CACzB;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,GAAG,UAAU,CAShF"}
@@ -0,0 +1,17 @@
1
+ import type { MeshStandardNodeMaterial, Node } from 'three/webgpu';
2
+ import type { CrownVolume } from '../generator';
3
+ /**
4
+ * Crown Normals (GLOSSARY): blends the leaf material's normal from the leaf's own normal towards the
5
+ * Crown Volume's normal at that point, by `amount` (0..1, a uniform: Definitions that differ only in it
6
+ * share one shader, and a Tree tunes it live). Only call it when the feature is on (amount > 0); without
7
+ * it the material keeps its own normal.
8
+ *
9
+ * - `growth`: the Growth node of the material's `positionNode` (the Volume scales with it).
10
+ * - `toObject`: turns a tree-space normal into the mesh's own space (a Forest rotates it by the
11
+ * instance, as it does the Growth and Wind displacement); default: tree space is object space.
12
+ *
13
+ * The leaf normal is the material's view-space normal: the screen-space facet normal under flat
14
+ * shading (so facets stay visible below 1), the smooth one facing the viewer otherwise.
15
+ */
16
+ export declare function applyCrownNormals(material: MeshStandardNodeMaterial, amount: Node<'float'>, crown: CrownVolume, growth: Node<'float'>, toObject?: (normal: Node<'vec3'>) => Node<'vec3'>): void;
17
+ //# sourceMappingURL=crown-normals.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crown-normals.d.ts","sourceRoot":"","sources":["../../src/materials/crown-normals.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,wBAAwB,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AACnE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAGhD;;;;;;;;;;;;GAYG;AACH,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE,wBAAwB,EAClC,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,EACrB,KAAK,EAAE,WAAW,EAClB,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,EACrB,QAAQ,GAAE,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,IAAI,CAAC,MAAM,CAAsB,GACpE,IAAI,CAKN"}
@@ -0,0 +1,13 @@
1
+ import type { Node } from 'three/webgpu';
2
+ import type { GroundTintDefinition } from '../definition';
3
+ /**
4
+ * Ground Tint (GLOSSARY): how far the bark blends towards `tint.color` at tree-space height `y`
5
+ * (on the grown tree): `strength` at and below the ground, easing (smoothstep) to 0 at `height`.
6
+ */
7
+ export declare function groundTintAmount(tint: GroundTintDefinition, y: number): number;
8
+ /**
9
+ * The TSL twin of {@link groundTintAmount}, applied to a bark colour node: `mix(bark, tint, amount)`.
10
+ * The height is the grown tree-space position (Growth `growth`, before Wind), from the vertex stage.
11
+ */
12
+ export declare function applyGroundTint(bark: Node<'vec3'> | Node<'color'>, tint: GroundTintDefinition, growth: Node<'float'>): Node<'vec3'>;
13
+ //# sourceMappingURL=ground-tint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ground-tint.d.ts","sourceRoot":"","sources":["../../src/materials/ground-tint.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AAG1D;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,oBAAoB,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAG9E;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,oBAAoB,EAAE,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,CAInI"}
@@ -1,13 +1,19 @@
1
1
  import { type MeshStandardNodeMaterial } from 'three/webgpu';
2
+ import type { Node } from 'three/webgpu';
2
3
  import type { TreeDefinition } from '../definition';
3
4
  import type { TextureOptions } from '../textures';
4
5
  export { createShadedMaterial } from './shading';
6
+ export { applyCrownNormals } from './crown-normals';
7
+ export { crownNodes, type CrownNodes } from './crown-nodes';
5
8
  /**
6
9
  * Bark material: a TSL node material (ADR 0002). Growth/Season/Wind uniforms and
7
10
  * per-Style variants hook in here in later tickets (#5-#10). `materials.bark.map` / `.normalMap`
8
11
  * load through `textures` (base path / URL overrides, see `TextureOptions`).
12
+ *
13
+ * `growth`: the Growth node the material's `positionNode` grows the tree with (default: fully grown).
14
+ * A Ground Tint (`materials.bark.groundTint`) is measured on that grown position; without one it is unused.
9
15
  */
10
- export declare function createBarkMaterial(definition: TreeDefinition, textures?: TextureOptions): MeshStandardNodeMaterial;
16
+ export declare function createBarkMaterial(definition: TreeDefinition, textures?: TextureOptions, growth?: Node<'float'>): MeshStandardNodeMaterial;
11
17
  /**
12
18
  * Leaf material: a TSL node material lit from both sides. `.color` is the Season Profile's
13
19
  * leaf colour at Season 0 (what exporters see); `Tree` adds the Season nodes
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/materials/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,KAAK,wBAAwB,EAAE,MAAM,cAAc,CAAC;AAEzE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAEpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAIlD,OAAO,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAC;AAEjD;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,cAAc,EAAE,QAAQ,CAAC,EAAE,cAAc,GAAG,wBAAwB,CAalH;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,cAAc,EAAE,QAAQ,CAAC,EAAE,cAAc,GAAG,wBAAwB,CAWlH;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,cAAc,GAAG,wBAAwB,CASxF"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/materials/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,KAAK,wBAAwB,EAAE,MAAM,cAAc,CAAC;AAEzE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAEpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAKlD,OAAO,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAC;AACjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,KAAK,UAAU,EAAE,MAAM,eAAe,CAAC;AAE5D;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAChC,UAAU,EAAE,cAAc,EAC1B,QAAQ,CAAC,EAAE,cAAc,EACzB,MAAM,GAAE,IAAI,CAAC,OAAO,CAAY,GAC/B,wBAAwB,CAe1B;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,UAAU,EAAE,cAAc,EAAE,QAAQ,CAAC,EAAE,cAAc,GAAG,wBAAwB,CAWlH;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,cAAc,GAAG,wBAAwB,CASxF"}
@@ -0,0 +1,14 @@
1
+ import { type MeshStandardNodeMaterial, type Node } from 'three/webgpu';
2
+ import type { CrownVolume } from '../generator';
3
+ import { type LeafTranslucencyValues } from './leaf-translucency';
4
+ /**
5
+ * Gives a leaf material Leaf Translucency (`materials.leaf.translucency` as uniforms, a Material Feature, ADR 0008):
6
+ * its lighting model becomes the translucent one (the physical model with the term for flat and standard
7
+ * shading, the soft toon model with the same term for toon). The material keeps its class and every node.
8
+ * Only call it when the feature is set: without it the leaf material keeps today's lighting model.
9
+ *
10
+ * `crown` is the tree's Crown Volume (`TreeData.crown`); `growth` the Growth node the material's
11
+ * `positionNode` grows with (a Tree's Growth uniform, or a Forest's per-instance Growth).
12
+ */
13
+ export declare function applyLeafTranslucency(material: MeshStandardNodeMaterial, values: LeafTranslucencyValues, crown: CrownVolume, growth: Node<'float'>): void;
14
+ //# sourceMappingURL=leaf-translucency-model.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"leaf-translucency-model.d.ts","sourceRoot":"","sources":["../../src/materials/leaf-translucency-model.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,wBAAwB,EAC7B,KAAK,IAAI,EAEV,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,EAOL,KAAK,sBAAsB,EAC5B,MAAM,qBAAqB,CAAC;AA4B7B;;;;;;;;GAQG;AACH,wBAAgB,qBAAqB,CACnC,QAAQ,EAAE,wBAAwB,EAClC,MAAM,EAAE,sBAAsB,EAC9B,KAAK,EAAE,WAAW,EAClB,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,GACpB,IAAI,CAON"}