@casmo/tree.js 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/README.md +590 -4
  2. package/dist/effects/custom.d.ts +62 -0
  3. package/dist/effects/custom.d.ts.map +1 -0
  4. package/dist/effects/effects.d.ts +42 -1
  5. package/dist/effects/effects.d.ts.map +1 -1
  6. package/dist/effects/index.d.ts +2 -0
  7. package/dist/effects/index.d.ts.map +1 -1
  8. package/dist/effects/mask.d.ts +9 -1
  9. package/dist/effects/mask.d.ts.map +1 -1
  10. package/dist/effects/tree-id.d.ts.map +1 -1
  11. package/dist/effects-qHx_8Dlk.js +1052 -0
  12. package/dist/effects-qHx_8Dlk.js.map +1 -0
  13. package/dist/effects.js +2 -963
  14. package/dist/forest/Forest.d.ts +80 -4
  15. package/dist/forest/Forest.d.ts.map +1 -1
  16. package/dist/forest/forest-lod.d.ts +70 -0
  17. package/dist/forest/forest-lod.d.ts.map +1 -0
  18. package/dist/forest/impostor-material.d.ts +106 -0
  19. package/dist/forest/impostor-material.d.ts.map +1 -0
  20. package/dist/forest/impostor-season.d.ts +13 -0
  21. package/dist/forest/impostor-season.d.ts.map +1 -0
  22. package/dist/forest/impostor.d.ts +105 -0
  23. package/dist/forest/impostor.d.ts.map +1 -0
  24. package/dist/forest/index.d.ts +1 -0
  25. package/dist/forest/index.d.ts.map +1 -1
  26. package/dist/forest/levels.d.ts +144 -0
  27. package/dist/forest/levels.d.ts.map +1 -0
  28. package/dist/forest/lod.d.ts +106 -0
  29. package/dist/forest/lod.d.ts.map +1 -0
  30. package/dist/forest/nodes.d.ts +42 -1
  31. package/dist/forest/nodes.d.ts.map +1 -1
  32. package/dist/forest/octahedral.d.ts +33 -0
  33. package/dist/forest/octahedral.d.ts.map +1 -0
  34. package/dist/{forest-lg61rhKM.js → forest-CM5DrklM.js} +1723 -340
  35. package/dist/forest-CM5DrklM.js.map +1 -0
  36. package/dist/generator/fruit.d.ts +2 -0
  37. package/dist/generator/fruit.d.ts.map +1 -1
  38. package/dist/generator/index.d.ts +1 -0
  39. package/dist/generator/index.d.ts.map +1 -1
  40. package/dist/generator/light.d.ts +36 -0
  41. package/dist/generator/light.d.ts.map +1 -0
  42. package/dist/index.d.ts +3 -2
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +5 -2
  45. package/dist/index.js.map +1 -1
  46. package/dist/materials/crown-nodes.d.ts +5 -0
  47. package/dist/materials/crown-nodes.d.ts.map +1 -1
  48. package/dist/materials/leaf-translucency-model.d.ts +6 -1
  49. package/dist/materials/leaf-translucency-model.d.ts.map +1 -1
  50. package/dist/materials/material-features.d.ts +12 -0
  51. package/dist/materials/material-features.d.ts.map +1 -1
  52. package/dist/materials/shader-hooks.d.ts +155 -0
  53. package/dist/materials/shader-hooks.d.ts.map +1 -0
  54. package/dist/motion-Qd7xjeZM.js +276 -0
  55. package/dist/motion-Qd7xjeZM.js.map +1 -0
  56. package/dist/nodes-DxgTyF9B.js +436 -0
  57. package/dist/nodes-DxgTyF9B.js.map +1 -0
  58. package/dist/react/Forest.d.ts +17 -3
  59. package/dist/react/Forest.d.ts.map +1 -1
  60. package/dist/react/ScenePipeline.d.ts +63 -0
  61. package/dist/react/ScenePipeline.d.ts.map +1 -0
  62. package/dist/react/SceneShaderHooks.d.ts +25 -0
  63. package/dist/react/SceneShaderHooks.d.ts.map +1 -0
  64. package/dist/react/Tree.d.ts +9 -2
  65. package/dist/react/Tree.d.ts.map +1 -1
  66. package/dist/react/Weather.d.ts +45 -0
  67. package/dist/react/Weather.d.ts.map +1 -0
  68. package/dist/react/Wind.d.ts +12 -1
  69. package/dist/react/Wind.d.ts.map +1 -1
  70. package/dist/react/index.d.ts +7 -1
  71. package/dist/react/index.d.ts.map +1 -1
  72. package/dist/react.js +347 -10
  73. package/dist/react.js.map +1 -1
  74. package/dist/renderer/index.d.ts +6 -0
  75. package/dist/renderer/index.d.ts.map +1 -1
  76. package/dist/scene/antialias.d.ts +35 -0
  77. package/dist/scene/antialias.d.ts.map +1 -0
  78. package/dist/scene/ao.d.ts +46 -0
  79. package/dist/scene/ao.d.ts.map +1 -0
  80. package/dist/scene/bloom.d.ts +19 -0
  81. package/dist/scene/bloom.d.ts.map +1 -0
  82. package/dist/scene/fog.d.ts +49 -0
  83. package/dist/scene/fog.d.ts.map +1 -0
  84. package/dist/scene/godrays.d.ts +37 -0
  85. package/dist/scene/godrays.d.ts.map +1 -0
  86. package/dist/scene/index.d.ts +14 -0
  87. package/dist/scene/index.d.ts.map +1 -0
  88. package/dist/scene/motion-blur.d.ts +23 -0
  89. package/dist/scene/motion-blur.d.ts.map +1 -0
  90. package/dist/scene/pipeline.d.ts +109 -0
  91. package/dist/scene/pipeline.d.ts.map +1 -0
  92. package/dist/scene/settings.d.ts +36 -0
  93. package/dist/scene/settings.d.ts.map +1 -0
  94. package/dist/scene/stack.d.ts +25 -0
  95. package/dist/scene/stack.d.ts.map +1 -0
  96. package/dist/scene/stage.d.ts +52 -0
  97. package/dist/scene/stage.d.ts.map +1 -0
  98. package/dist/scene/suggested.d.ts +12 -0
  99. package/dist/scene/suggested.d.ts.map +1 -0
  100. package/dist/scene/tone-mapping.d.ts +20 -0
  101. package/dist/scene/tone-mapping.d.ts.map +1 -0
  102. package/dist/scene/velocity.d.ts +34 -0
  103. package/dist/scene/velocity.d.ts.map +1 -0
  104. package/dist/scene.js +889 -0
  105. package/dist/scene.js.map +1 -0
  106. package/dist/season/nodes.d.ts +13 -0
  107. package/dist/season/nodes.d.ts.map +1 -1
  108. package/dist/shader-hooks-BFRtlWGI.js +275 -0
  109. package/dist/shader-hooks-BFRtlWGI.js.map +1 -0
  110. package/dist/tree/Tree.d.ts +8 -3
  111. package/dist/tree/Tree.d.ts.map +1 -1
  112. package/dist/tree/index.d.ts.map +1 -1
  113. package/dist/weather/index.d.ts +3 -0
  114. package/dist/weather/index.d.ts.map +1 -0
  115. package/dist/weather/shared.d.ts +43 -0
  116. package/dist/weather/shared.d.ts.map +1 -0
  117. package/dist/weather/snow.d.ts +87 -0
  118. package/dist/weather/snow.d.ts.map +1 -0
  119. package/dist/weather/wetness.d.ts +75 -0
  120. package/dist/weather/wetness.d.ts.map +1 -0
  121. package/dist/weather.js +288 -0
  122. package/dist/weather.js.map +1 -0
  123. package/dist/wind/Wind.d.ts +100 -5
  124. package/dist/wind/Wind.d.ts.map +1 -1
  125. package/dist/wind/burst.d.ts +28 -0
  126. package/dist/wind/burst.d.ts.map +1 -0
  127. package/dist/wind/index.d.ts +3 -2
  128. package/dist/wind/index.d.ts.map +1 -1
  129. package/dist/wind/motion.d.ts +30 -0
  130. package/dist/wind/motion.d.ts.map +1 -0
  131. package/dist/wind/node.d.ts +17 -3
  132. package/dist/wind/node.d.ts.map +1 -1
  133. package/package.json +9 -1
  134. package/dist/effects.js.map +0 -1
  135. package/dist/forest-lg61rhKM.js.map +0 -1
@@ -0,0 +1,1052 @@
1
+ import { o as instanceSlot } from "./nodes-DxgTyF9B.js";
2
+ import { h as treePartOf, m as treeMaskMRT, u as TREE_MASK } from "./motion-Qd7xjeZM.js";
3
+ import { Color, NearestFilter, NoColorSpace, RedIntegerFormat, RenderPipeline, UnsignedByteType, UnsignedIntType, Vector2 } from "three/webgpu";
4
+ import { Break, Fn, If, Loop, abs, dot, float, ivec2, logarithmicDepthToViewZ, luminance, max, mix, mrt, normalView, orthographicDepthToViewZ, output, packNormalToRGB, pass, perspectiveDepthToViewZ, screenCoordinate, select, smoothstep, textureSize, time, uint, uniform, uniformArray, unpackRGBToNormal, uv, vec2, vec3, vec4 } from "three/tsl";
5
+ import { gaussianBlur } from "three/addons/tsl/display/GaussianBlurNode.js";
6
+ // src/effects/tree-id.ts
7
+ /** Name of the Tree ID output in a pass's MRT (`scenePass.getTextureNode(TREE_ID)`), see {@link treeIdMRT}. */
8
+ var TREE_ID = "treeId";
9
+ var MAX_ID = 4294967295;
10
+ var nextId$1 = 1;
11
+ var treeIds = /* @__PURE__ */ new WeakMap();
12
+ var treesById = /* @__PURE__ */ new Map();
13
+ var forgetTree = new FinalizationRegistry((id) => treesById.delete(id));
14
+ var blockOf = /* @__PURE__ */ new WeakMap();
15
+ /** Every live block, by ascending `base`. */
16
+ var blocks = [];
17
+ var forgetBlock = new FinalizationRegistry((block) => blocks.splice(blocks.indexOf(block), 1));
18
+ function reserve(count) {
19
+ if (nextId$1 + count - 1 > MAX_ID) throw new RangeError("Tree IDs exhausted: more than 4294967295 handed out in this session");
20
+ const base = nextId$1;
21
+ nextId$1 += count;
22
+ return base;
23
+ }
24
+ function idOfTree(tree) {
25
+ let id = treeIds.get(tree);
26
+ if (id === void 0) {
27
+ id = reserve(1);
28
+ treeIds.set(tree, id);
29
+ treesById.set(id, new WeakRef(tree));
30
+ forgetTree.register(tree, id);
31
+ }
32
+ return id;
33
+ }
34
+ /** Whether the Variant still draws with the meshes the block was reserved for. */
35
+ function isCurrent(block, variant) {
36
+ return variant.wood.instanceMatrix === block.matrices.deref() && variant.wood.parent !== null;
37
+ }
38
+ function blockOfVariant(variant) {
39
+ const matrices = variant.wood.instanceMatrix;
40
+ let block = blockOf.get(matrices);
41
+ if (!block) {
42
+ block = {
43
+ base: reserve(variant.capacity),
44
+ capacity: variant.capacity,
45
+ variant: new WeakRef(variant),
46
+ matrices: new WeakRef(matrices)
47
+ };
48
+ blockOf.set(matrices, block);
49
+ blocks.push(block);
50
+ forgetBlock.register(matrices, block);
51
+ }
52
+ return block;
53
+ }
54
+ function blockAt(id) {
55
+ let lo = 0;
56
+ let hi = blocks.length - 1;
57
+ while (lo <= hi) {
58
+ const mid = lo + hi >> 1;
59
+ const block = blocks[mid];
60
+ if (id < block.base) hi = mid - 1;
61
+ else if (id >= block.base + block.capacity) lo = mid + 1;
62
+ else return block;
63
+ }
64
+ }
65
+ /**
66
+ * The current Tree ID of a Tree or a Forest tree, or `undefined` for a Forest tree that was removed.
67
+ * IDs are handed out lazily, on first use: by this function or by the first draw with the Tree ID
68
+ * channel, whichever comes first. So asking for a Tree's ID before it is drawn reserves it then
69
+ * (and for a Forest tree the block of its Variant's current meshes). A Forest tree's ID is
70
+ * frame-relative (see {@link treeFromId}).
71
+ */
72
+ function treeIdOf(tree) {
73
+ if ("isTree" in tree) return idOfTree(tree);
74
+ const variant = tree.owner;
75
+ if (!variant || tree.slot < 0 || variant.wood.parent === null) return void 0;
76
+ return blockOfVariant(variant).base + tree.slot;
77
+ }
78
+ /**
79
+ * The Tree or Forest tree with this Tree ID, resolved against the current trees, or `undefined`
80
+ * for 0 (not a tree), an unknown ID or a tree that is gone.
81
+ */
82
+ function treeFromId(id) {
83
+ if (!Number.isInteger(id) || id <= 0) return void 0;
84
+ const tree = treesById.get(id)?.deref();
85
+ if (tree) return tree;
86
+ const block = blockAt(id);
87
+ const variant = block?.variant.deref();
88
+ if (!block || !variant || !isCurrent(block, variant)) return void 0;
89
+ return variant.trees[id - block.base];
90
+ }
91
+ /**
92
+ * The ID the drawn object writes: a Tree's ID for each of its parts, the block base of a Forest
93
+ * Variant's mesh, instanced or drawing a Detail Level (the shader adds the tree's slot), 0 for
94
+ * anything else.
95
+ */
96
+ function drawnId(object) {
97
+ for (let o = object; o; o = o.parent) {
98
+ if (o.isTree) return idOfTree(o);
99
+ const forest = o.parent;
100
+ if (forest?.isForest) {
101
+ const variant = forest.variants.find((v) => v.meshes.includes(o) || v.levels?.meshes.includes(o));
102
+ if (variant) return blockOfVariant(variant).base;
103
+ }
104
+ }
105
+ return 0;
106
+ }
107
+ /** The WebGL2 context when `renderer` runs on three's WebGL2 fallback, `undefined` on WebGPU. */
108
+ function webglOf(renderer) {
109
+ const backend = renderer.backend;
110
+ return backend.isWebGLBackend === true && backend.gl ? {
111
+ backend,
112
+ gl: backend.gl
113
+ } : void 0;
114
+ }
115
+ /** Per Tree ID texture: a framebuffer with just that texture attached, to clear it on its own. */
116
+ var clearTargets = /* @__PURE__ */ new WeakMap();
117
+ /**
118
+ * WebGL2 only (a no-op on WebGPU, which clears integer targets correctly): clears the Tree ID
119
+ * texture to 0. three's WebGL2 fallback clears every colour attachment of a render target with
120
+ * `clearBufferfv`, which is invalid for an integer target: the GL ignores it (logging one
121
+ * `GL_INVALID_OPERATION` warning per frame in the console, from three's own clear, that we cannot
122
+ * avoid without three changing its clear) and the IDs of the last frame would stay wherever nothing
123
+ * is drawn now. So this clears the texture with `clearBufferuiv` through a framebuffer of its own,
124
+ * restoring the GL bindings and state it touches, before the scene pass renders (see
125
+ * {@link treeIdTexture}).
126
+ *
127
+ * Depends on three internals: `renderer.backend.gl` (the WebGL2 context) and
128
+ * `renderer.backend.get(texture)` (`textureGPU`, `glInternalFormat`). A texture three has not
129
+ * allocated yet is skipped: new GL storage starts at 0.
130
+ */
131
+ function clearTreeIdTextureOnWebGL(renderer, texture) {
132
+ const webgl = webglOf(renderer);
133
+ if (!webgl || !webgl.backend.has(texture)) return;
134
+ const { gl } = webgl;
135
+ const { textureGPU, glInternalFormat } = webgl.backend.get(texture);
136
+ if (!textureGPU || glInternalFormat !== gl.R32UI) return;
137
+ let target = clearTargets.get(texture);
138
+ if (!target) {
139
+ const framebuffer = gl.createFramebuffer();
140
+ target = {
141
+ framebuffer,
142
+ attached: null
143
+ };
144
+ clearTargets.set(texture, target);
145
+ texture.addEventListener("dispose", () => {
146
+ gl.deleteFramebuffer(framebuffer);
147
+ clearTargets.delete(texture);
148
+ });
149
+ }
150
+ const previous = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);
151
+ const scissor = gl.isEnabled(gl.SCISSOR_TEST);
152
+ const mask = gl.getParameter(gl.COLOR_WRITEMASK);
153
+ gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, target.framebuffer);
154
+ if (target.attached !== textureGPU) {
155
+ gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0);
156
+ target.attached = textureGPU;
157
+ }
158
+ if (scissor) gl.disable(gl.SCISSOR_TEST);
159
+ gl.colorMask(true, true, true, true);
160
+ gl.clearBufferuiv(gl.COLOR, 0, [
161
+ 0,
162
+ 0,
163
+ 0,
164
+ 0
165
+ ]);
166
+ gl.colorMask(...mask);
167
+ if (scissor) gl.enable(gl.SCISSOR_TEST);
168
+ gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, previous);
169
+ }
170
+ var clearing = /* @__PURE__ */ new WeakSet();
171
+ /**
172
+ * Makes the scene pass clear its Tree ID texture (on WebGL2, see {@link clearTreeIdTextureOnWebGL})
173
+ * right before it renders, every frame, also when nothing is drawn.
174
+ */
175
+ function clearTreeIdsBeforeEachRender(scenePass, texture) {
176
+ if (clearing.has(scenePass)) return;
177
+ clearing.add(scenePass);
178
+ const render = scenePass.updateBefore.bind(scenePass);
179
+ scenePass.updateBefore = (frame) => {
180
+ if (frame.renderer) clearTreeIdTextureOnWebGL(frame.renderer, texture);
181
+ return render(frame);
182
+ };
183
+ }
184
+ /**
185
+ * TSL node: the Tree ID of the tree being drawn (`uint`), 0 for anything that is not a tree. A Tree
186
+ * writes one ID for all its parts (wood, leaves, Fruit); a Forest tree writes its Variant's block
187
+ * base + its slot, at every Detail Level (the instance index on the instanced meshes, the slot from
188
+ * the level list on a Detail Level mesh). A per-object uniform decided from the drawn object, so no material is
189
+ * changed. It ignores the outline's `selection`: every tree gets its ID.
190
+ */
191
+ function createTreeId() {
192
+ const base = uniform(0, "uint").onObjectUpdate((frame, node) => {
193
+ node.value = treePartOf(frame.material) === null ? 0 : drawnId(frame.object);
194
+ });
195
+ return select(base.equal(0), base, base.add(instanceSlot()));
196
+ }
197
+ /**
198
+ * The MRT output that renders each tree's Tree ID ({@link createTreeId}) next to the colour, opt-in
199
+ * next to {@link treeMaskMRT}. Merge it into the MRT of your own scene pass and always call
200
+ * {@link treeIdTexture} on that pass afterwards:
201
+ * `scenePass.setMRT(mrt({ output }).merge(treeMaskMRT()).merge(treeIdMRT())); treeIdTexture(scenePass);`.
202
+ * Note that this turns MSAA off on that scene pass (an integer target cannot be multisampled, see
203
+ * {@link treeIdTexture}). Read IDs back with {@link readTreeId}, or in a shader with exact texel
204
+ * loads (never filtered).
205
+ */
206
+ function treeIdMRT() {
207
+ const node = mrt({ [TREE_ID]: createTreeId() });
208
+ node.setClearColor(TREE_ID, 0, 0);
209
+ return node;
210
+ }
211
+ /**
212
+ * Makes the Tree ID target of a scene pass ({@link treeIdMRT} merged into its MRT) one 32-bit
213
+ * unsigned integer per pixel (`r32uint`, read without filtering) and returns its texture. Call it
214
+ * once after `setMRT`, before the first render.
215
+ *
216
+ * **MSAA is turned off on this scene pass**: an integer target cannot be multisampled, and all the
217
+ * targets of a pass share one sample count, so this sets `scenePass.options.samples = 0`, also with
218
+ * an `antialias: true` renderer (the colour then has aliased edges unless you add FXAA/SMAA after
219
+ * the pass). That is a hard constraint of WebGPU and WebGL2, not a choice of tree.js.
220
+ *
221
+ * On the WebGL2 fallback it also makes the pass clear the Tree ID target to 0 right before every
222
+ * render (three cannot clear integer targets there), so a pixel where nothing is drawn reads 0.
223
+ */
224
+ function treeIdTexture(scenePass) {
225
+ scenePass.options.samples = 0;
226
+ const texture = scenePass.getTexture(TREE_ID);
227
+ texture.format = RedIntegerFormat;
228
+ texture.type = UnsignedIntType;
229
+ texture.minFilter = texture.magFilter = NearestFilter;
230
+ texture.generateMipmaps = false;
231
+ texture.colorSpace = NoColorSpace;
232
+ clearTreeIdsBeforeEachRender(scenePass, texture);
233
+ return texture;
234
+ }
235
+ /**
236
+ * Reads the Tree ID under a point of the canvas from the last render of `scenePass` (with
237
+ * {@link treeIdMRT} in its MRT): `x`, `y` in CSS pixels from the canvas's top left corner, as in
238
+ * `event.offsetX/offsetY`. Resolves to 0 off the canvas or where no tree is drawn. Resolve the ID
239
+ * with {@link treeFromId} right away: IDs are frame-relative.
240
+ */
241
+ async function readTreeId(renderer, scenePass, x, y) {
242
+ const texture = scenePass.getTexture(TREE_ID);
243
+ const target = scenePass.renderTarget;
244
+ const index = target.textures.indexOf(texture);
245
+ if (index < 0) throw new Error("readTreeId: the scene pass has no Tree ID target; merge treeIdMRT() into its MRT");
246
+ const css = renderer.getSize(new Vector2());
247
+ const px = Math.floor(x * target.width / css.x);
248
+ const py = Math.floor(y * target.height / css.y);
249
+ if (!(px >= 0 && py >= 0 && px < target.width && py < target.height)) return 0;
250
+ const flipY = webglOf(renderer) !== void 0;
251
+ const data = await renderer.readRenderTargetPixelsAsync(target, px, flipY ? target.height - 1 - py : py, 1, 1, index);
252
+ return Number(data[0] ?? 0);
253
+ }
254
+ // src/effects/screen.ts
255
+ var DIAGONAL = Math.SQRT1_2;
256
+ /** Eight sample directions around a pixel, unit length: the four axes and the four diagonals. */
257
+ var EIGHT_DIRECTIONS = [
258
+ [1, 0],
259
+ [-1, 0],
260
+ [0, 1],
261
+ [0, -1],
262
+ [DIAGONAL, DIAGONAL],
263
+ [DIAGONAL, -DIAGONAL],
264
+ [-DIAGONAL, DIAGONAL],
265
+ [-DIAGONAL, -DIAGONAL]
266
+ ];
267
+ /** Four sample directions around a pixel: the axes. */
268
+ var FOUR_DIRECTIONS = [
269
+ [1, 0],
270
+ [-1, 0],
271
+ [0, 1],
272
+ [0, -1]
273
+ ];
274
+ /** The size of a texture in pixels, as a `vec2`. */
275
+ function sizeOf(texture) {
276
+ return vec2(textureSize(texture));
277
+ }
278
+ /**
279
+ * The texel `offset` px from the pixel being shaded, clamped to the texture, for exact texel loads
280
+ * (`texture.load(texelAt(texture, offset))`) of unfiltered targets such as the Tree ID.
281
+ */
282
+ function texelAt(texture, offset) {
283
+ return ivec2(screenCoordinate.xy.add(offset).floor().clamp(vec2(0), sizeOf(texture).sub(1)));
284
+ }
285
+ /** The Tree ID at a texel (see {@link texelAt}): 0 where no tree is drawn. */
286
+ function treeIdAt(treeId, texel) {
287
+ return uint(treeId.load(texel).x);
288
+ }
289
+ /** An optional input an effect needs, or an error naming the effect, the input and where to get it. */
290
+ function requireInput(effect, value, name, hint) {
291
+ if (value === void 0) throw new Error(`${effect} needs the \`${name}\` input: ${hint}`);
292
+ return value;
293
+ }
294
+ /**
295
+ * Whether the scene depth `depth` is further from the camera than `than` (both raw values of the
296
+ * scene pass's depth texture). Decided per renderer when the shader is built: a reversed depth
297
+ * buffer (`reversedDepthBuffer`) stores 1 at the near plane and 0 at the far plane, a standard or
298
+ * logarithmic one the other way around.
299
+ */
300
+ var isFurther = Fn(([depth, than], builder) => builder.renderer.reversedDepthBuffer === true ? depth.lessThan(than) : depth.greaterThan(than));
301
+ /**
302
+ * A function turning a raw value of the scene pass's depth texture into view Z (negative, in world
303
+ * units) for `camera` (its near and far are read every render). It follows the renderer's depth
304
+ * buffer: standard, reversed (`reversedDepthBuffer`) or logarithmic (`logarithmicDepthBuffer`,
305
+ * which three only applies to perspective cameras).
306
+ */
307
+ function viewZFromDepth(camera) {
308
+ const lens = camera;
309
+ const near = uniform(0).onRenderUpdate((_, node) => {
310
+ node.value = lens.near;
311
+ });
312
+ const far = uniform(0).onRenderUpdate((_, node) => {
313
+ node.value = lens.far;
314
+ });
315
+ const orthographic = lens.isOrthographicCamera === true;
316
+ const convert = Fn(([depth], builder) => {
317
+ if (orthographic) return orthographicDepthToViewZ(depth, near, far);
318
+ if (builder.renderer.logarithmicDepthBuffer === true) return logarithmicDepthToViewZ(depth, near, far);
319
+ return perspectiveDepthToViewZ(depth, near, far);
320
+ });
321
+ return (depth) => convert(depth);
322
+ }
323
+ // src/effects/inner-lines.ts
324
+ /** Name of the view normal output in a pass's MRT (`scenePass.getTextureNode('normal')`), see {@link treeNormalMRT}. */
325
+ var TREE_NORMAL = "normal";
326
+ /**
327
+ * The MRT output that renders view normals in the `'color'` encoding (`packNormalToRGB(normalView)`,
328
+ * the same as `directionToColor`) to a target named `normal`, for Inner Lines. Merge it into the MRT
329
+ * of your own scene pass and make the target RGBA8:
330
+ * `scenePass.setMRT(mrt({ output }).merge(treeMaskMRT()).merge(treeNormalMRT())); scenePass.getTexture('normal').type = UnsignedByteType;`.
331
+ * If your pipeline already renders normals (GTAO, SSR), pass that texture as the `normal` input instead.
332
+ */
333
+ function treeNormalMRT() {
334
+ return mrt({ [TREE_NORMAL]: packNormalToRGB(normalView) });
335
+ }
336
+ /**
337
+ * Tree Effect: ink lines inside the trees where the surface folds (normal edges) or steps away
338
+ * from the viewer (depth edges), such as around each leaf clump. Only drawn on tree pixels (of
339
+ * every tree, regardless of the outline's `selection`), and only from neighbours that are tree
340
+ * pixels too: the silhouette is left to the outline. Needs the `depth`, `camera` and `normal` inputs
341
+ * (`treeEffectsPass(scene, camera, null, { normal: true })` has them) and throws without them.
342
+ * Works with a standard, reversed (`reversedDepthBuffer`) or logarithmic (`logarithmicDepthBuffer`)
343
+ * depth buffer, and with perspective and orthographic cameras.
344
+ */
345
+ function innerLines(input, options = {}) {
346
+ return liveInnerLines(input, options).node;
347
+ }
348
+ /** {@link innerLines} with its settings as uniforms; the normal encoding is fixed when built. */
349
+ function liveInnerLines(input, options = {}) {
350
+ const normal = requireInput("innerLines", input.normal, "normal", "view normals, e.g. treeNormalMRT() or your own normal MRT (with `normalEncoding`)");
351
+ const depth = requireInput("innerLines", input.depth, "depth", "the scene pass's depth, scenePass.getTextureNode('depth')");
352
+ const camera = requireInput("innerLines", input.camera, "camera", "the camera the scene pass renders with");
353
+ const color = uniform(new Color());
354
+ const thickness = uniform(0);
355
+ const strength = uniform(0);
356
+ const normalLow = uniform(0);
357
+ const normalHigh = uniform(0);
358
+ const depthLow = uniform(0);
359
+ const depthHigh = uniform(0);
360
+ const update = (o) => {
361
+ const n = o.normalThreshold ?? .4;
362
+ const d = o.depthThreshold ?? .02;
363
+ color.value.set(o.color ?? "#1d2a14");
364
+ thickness.value = o.thickness ?? 1;
365
+ strength.value = o.strength ?? 1;
366
+ normalLow.value = n * .75;
367
+ normalHigh.value = n * 1.25;
368
+ depthLow.value = d * .5;
369
+ depthHigh.value = d * 1.5;
370
+ };
371
+ update(options);
372
+ const toViewZ = viewZFromDepth(camera);
373
+ const viewZ = (at) => toViewZ(depth.sample(at).r);
374
+ const direction = input.normalEncoding === "direction";
375
+ const normalAt = (at) => {
376
+ const n = normal.sample(at).rgb;
377
+ return (direction ? n : unpackRGBToNormal(n)).normalize();
378
+ };
379
+ const { mask } = input;
380
+ const step = vec2(thickness).div(sizeOf(mask));
381
+ const centre = uv();
382
+ const n0 = normalAt(centre);
383
+ const z0 = viewZ(centre);
384
+ let edge = float(0);
385
+ for (const [x, y] of FOUR_DIRECTIONS) {
386
+ const at = centre.add(step.mul(vec2(x, y)));
387
+ const normalEdge = smoothstep(normalLow, normalHigh, float(1).sub(dot(n0, normalAt(at))));
388
+ const depthEdge = smoothstep(depthLow, depthHigh, abs(viewZ(at).sub(z0)).div(abs(z0)));
389
+ edge = max(edge, max(normalEdge, depthEdge).mul(mask.sample(at).r));
390
+ }
391
+ const line = edge.mul(mask.sample(centre).r).mul(strength);
392
+ return {
393
+ node: vec4(mix(input.color.rgb, color, line), input.color.a),
394
+ update
395
+ };
396
+ }
397
+ // src/effects/pass.ts
398
+ /**
399
+ * Creates `pass(scene, camera)` with MRT `{ output, treeMask }` (plus the opt-in `channels`, e.g.
400
+ * `{ treeId: true }`, `{ normal: true }`) and returns it with the texture nodes of every target (and the depth and camera) as the effects' inputs.
401
+ * `selection`: the trees to outline (default `null` = all trees), see `createTreeMask`. If your
402
+ * pipeline already has a scene pass, merge `treeMaskMRT` (and `treeIdMRT`) into it instead.
403
+ */
404
+ function treeEffectsPass(scene, camera, selection = null, channels = {}) {
405
+ const scenePass = pass(scene, camera);
406
+ let outputs = mrt({ output }).merge(treeMaskMRT(selection));
407
+ if (channels.treeId) outputs = outputs.merge(treeIdMRT());
408
+ if (channels.normal) outputs = outputs.merge(treeNormalMRT());
409
+ scenePass.setMRT(outputs);
410
+ scenePass.getTexture(TREE_MASK).type = UnsignedByteType;
411
+ const input = {
412
+ pass: scenePass,
413
+ color: scenePass.getTextureNode("output"),
414
+ mask: scenePass.getTextureNode(TREE_MASK),
415
+ depth: scenePass.getTextureNode("depth"),
416
+ camera
417
+ };
418
+ if (channels.treeId) {
419
+ treeIdTexture(scenePass);
420
+ input.treeId = scenePass.getTextureNode(TREE_ID);
421
+ }
422
+ if (channels.normal) {
423
+ scenePass.getTexture(TREE_NORMAL).type = UnsignedByteType;
424
+ input.normal = scenePass.getTextureNode(TREE_NORMAL);
425
+ input.normalEncoding = "color";
426
+ }
427
+ return input;
428
+ }
429
+ // src/effects/outline.ts
430
+ /**
431
+ * Tree Effect: an outline along the silhouettes of the selected trees (the `selection` of the
432
+ * tree mask, see `createTreeMask`; all trees by default), around the outside of the canopy and
433
+ * the gaps in it. The line is drawn on the inside of the silhouette, so only tree pixels change.
434
+ * With `betweenTrees`, it is also drawn where a tree overlaps another one behind it.
435
+ */
436
+ function treeOutline(input, options = {}) {
437
+ return liveTreeOutline(input, options).node;
438
+ }
439
+ /** {@link treeOutline} with its settings as uniforms. */
440
+ function liveTreeOutline(input, options = {}) {
441
+ const color = uniform(new Color());
442
+ const thickness = uniform(0);
443
+ const strength = uniform(0);
444
+ const update = (o) => {
445
+ color.value.set(o.color ?? "#1d2a14");
446
+ thickness.value = o.thickness ?? 2;
447
+ strength.value = o.strength ?? 1;
448
+ };
449
+ update(options);
450
+ const { mask } = input;
451
+ const step = vec2(thickness).div(sizeOf(mask));
452
+ const centre = uv();
453
+ const behind = options.betweenTrees === true ? otherTreeBehind(input, thickness) : null;
454
+ let outside = float(0);
455
+ for (const [x, y] of EIGHT_DIRECTIONS) {
456
+ const notSelected = float(1).sub(mask.sample(centre.add(step.mul(vec2(x, y)))).b);
457
+ outside = outside.add(behind ? max(notSelected, behind(x, y)) : notSelected);
458
+ }
459
+ const edge = outside.mul(3 / EIGHT_DIRECTIONS.length).clamp(0, 1).mul(mask.sample(centre).b).mul(strength);
460
+ return {
461
+ node: vec4(mix(input.color.rgb, color, edge), input.color.a),
462
+ update
463
+ };
464
+ }
465
+ /**
466
+ * For `betweenTrees`: a function giving, per direction, 1 where the neighbour at `thickness` px is a
467
+ * different tree (another nonzero Tree ID) that is further from the camera than this pixel, 0
468
+ * elsewhere, so the line lies on the front tree's side. IDs and depths are read with exact texel
469
+ * loads; "further" follows the renderer's depth buffer (standard, reversed or logarithmic).
470
+ */
471
+ function otherTreeBehind(input, thickness) {
472
+ const how = "use treeEffectsPass(scene, camera, selection, { treeId: true }), which has both";
473
+ const treeId = requireInput("treeOutline with betweenTrees", input.treeId, "treeId", how);
474
+ const depth = requireInput("treeOutline with betweenTrees", input.depth, "depth", how);
475
+ const here = texelAt(treeId, vec2(0));
476
+ const id = treeIdAt(treeId, here);
477
+ const z = depth.load(here).x;
478
+ return (x, y) => {
479
+ const there = texelAt(treeId, vec2(x, y).mul(thickness));
480
+ const other = treeIdAt(treeId, there);
481
+ const further = isFurther(depth.load(there).x, z);
482
+ return select(other.notEqual(uint(0)).and(other.notEqual(id)).and(further), float(1), float(0));
483
+ };
484
+ }
485
+ // src/effects/glow.ts
486
+ /** The blur radius of leaf glow settings (part of a Tree Effects graph's shape). */
487
+ function glowRadius(options) {
488
+ return options.radius ?? 6;
489
+ }
490
+ /**
491
+ * Tree Effect: a soft glow of the leaves. The bright (sunlit) leaf pixels are blurred and added
492
+ * back onto the tree pixels (leaves and the wood between them), never onto the rest of the scene.
493
+ */
494
+ function leafGlow(input, options = {}) {
495
+ return liveLeafGlow(input, options).node;
496
+ }
497
+ /** {@link leafGlow} with its settings as uniforms; `radius` is fixed when built. */
498
+ function liveLeafGlow(input, options = {}) {
499
+ const color = uniform(new Color());
500
+ const intensity = uniform(0);
501
+ const low = uniform(0);
502
+ const high = uniform(0);
503
+ const update = (o) => {
504
+ const threshold = o.threshold ?? .15;
505
+ color.value.set(o.color ?? "#ffffff");
506
+ intensity.value = o.intensity ?? .6;
507
+ low.value = threshold;
508
+ high.value = threshold * 2 + .05;
509
+ };
510
+ update(options);
511
+ const bright = smoothstep(low, high, luminance(input.color.rgb));
512
+ const leaves = vec4(input.color.rgb.mul(input.mask.g).mul(bright), 1);
513
+ const glow = gaussianBlur(leaves, null, glowRadius(options), { resolutionScale: .5 }).rgb.mul(color).mul(intensity).mul(input.mask.r);
514
+ return {
515
+ node: vec4(input.color.rgb.add(glow), input.color.a),
516
+ update
517
+ };
518
+ }
519
+ // src/effects/grade.ts
520
+ var MID_GREY = .18;
521
+ /**
522
+ * Tree Effect: colour grading (exposure, tint, saturation, contrast) of the tree pixels only.
523
+ * Returns the graded colour where the tree mask is set and `input.color` unchanged elsewhere.
524
+ */
525
+ function treeColorGrade(input, options = {}) {
526
+ return liveTreeColorGrade(input, options).node;
527
+ }
528
+ /** {@link treeColorGrade} with its settings as uniforms. */
529
+ function liveTreeColorGrade(input, options = {}) {
530
+ const tint = uniform(new Color());
531
+ const exposure = uniform(0);
532
+ const saturation = uniform(0);
533
+ const contrast = uniform(0);
534
+ const update = (o) => {
535
+ tint.value.set(o.tint ?? "#ffffff");
536
+ exposure.value = o.exposure ?? 1;
537
+ saturation.value = o.saturation ?? 1;
538
+ contrast.value = o.contrast ?? 1;
539
+ };
540
+ update(options);
541
+ const tinted = input.color.rgb.mul(tint).mul(exposure);
542
+ const contrasted = mix(vec3(luminance(tinted)), tinted, saturation).max(0).div(MID_GREY).pow(vec3(contrast)).mul(MID_GREY);
543
+ return {
544
+ node: select(input.mask.r.greaterThan(.5), vec4(contrasted, input.color.a), input.color),
545
+ update
546
+ };
547
+ }
548
+ // src/effects/highlight.ts
549
+ /** The most trees highlighted at once; the rest of the list is ignored (with one console warning). */
550
+ var MAX_HIGHLIGHTED = 64;
551
+ /**
552
+ * The current Tree ID of a highlighted entry, or `undefined` to skip it: a removed or undrawn
553
+ * Forest tree, a Tree that is disposed or in no scene, or anything that is not a Tree or Forest tree.
554
+ */
555
+ function idOfHighlighted(entry) {
556
+ if (!entry || typeof entry !== "object") return void 0;
557
+ if ("isTree" in entry) return entry.isTree && entry.parent !== null ? treeIdOf(entry) : void 0;
558
+ if (!("slot" in entry) || !("owner" in entry)) return void 0;
559
+ return treeIdOf(entry);
560
+ }
561
+ /**
562
+ * Tree Effect: marks the trees in `highlighted` (Trees and Forest trees; mutable, read every frame)
563
+ * by brightening and tinting their pixels and drawing a ring just outside them, the one Tree Effect
564
+ * that also changes pixels next to a tree. At most 64 trees (the rest is ignored with one warning); removed, disposed
565
+ * and undrawn trees are skipped. Needs the Tree ID input (`treeEffectsPass` with `{ treeId: true }`).
566
+ */
567
+ function treeHighlight(input, highlighted, options = {}) {
568
+ return liveTreeHighlight(input, highlighted, options).node;
569
+ }
570
+ /** {@link treeHighlight} with its settings as uniforms. */
571
+ function liveTreeHighlight(input, highlighted, options = {}) {
572
+ const treeId = requireInput("treeHighlight", input.treeId, "treeId", "use treeEffectsPass(scene, camera, selection, { treeId: true }), or merge treeIdMRT() into your scene pass and pass its texture node");
573
+ const color = uniform(new Color());
574
+ const outlineColor = uniform(new Color());
575
+ const tint = uniform(0);
576
+ const brightness = uniform(0);
577
+ const thickness = uniform(0);
578
+ const strength = uniform(0);
579
+ const pulse = uniform(0);
580
+ const update = (o) => {
581
+ color.value.set(o.color ?? "#ffe066");
582
+ outlineColor.value.set(o.outlineColor ?? "#ffd23f");
583
+ tint.value = o.tint ?? .25;
584
+ brightness.value = o.brightness ?? 1.25;
585
+ thickness.value = o.thickness ?? 2;
586
+ strength.value = o.strength ?? 1;
587
+ pulse.value = o.pulse ?? 0;
588
+ };
589
+ update(options);
590
+ const count = uniform(0, "uint");
591
+ const ids = uniformArray(new Array(MAX_HIGHLIGHTED).fill(0), "uint");
592
+ let refreshed = -1;
593
+ let warned = false;
594
+ const refresh = (renderId) => {
595
+ if (renderId === refreshed) return;
596
+ refreshed = renderId;
597
+ let n = 0;
598
+ for (const entry of highlighted) {
599
+ const id = idOfHighlighted(entry);
600
+ if (id === void 0) continue;
601
+ if (n === MAX_HIGHLIGHTED) {
602
+ if (!warned) console.warn(`Highlight: at most ${MAX_HIGHLIGHTED} trees are highlighted at once; the rest are ignored`);
603
+ warned = true;
604
+ break;
605
+ }
606
+ ids.array[n++] = id;
607
+ }
608
+ ids.array.fill(0, n);
609
+ count.value = n;
610
+ };
611
+ count.onRenderUpdate((frame) => {
612
+ refresh(frame.renderId);
613
+ });
614
+ ids.onRenderUpdate((frame) => refresh(frame.renderId));
615
+ /** 1 where the tree drawn at `offset` px from this pixel is highlighted, else 0. */
616
+ const isHighlighted = Fn(([offset]) => {
617
+ const id = treeIdAt(treeId, texelAt(treeId, offset));
618
+ const hit = float(0).toVar();
619
+ If(id.notEqual(uint(0)), () => {
620
+ Loop({
621
+ start: uint(0),
622
+ end: count,
623
+ type: "uint",
624
+ condition: "<"
625
+ }, ({ i }) => {
626
+ If(ids.element(i).equal(id), () => {
627
+ hit.assign(1);
628
+ Break();
629
+ });
630
+ });
631
+ });
632
+ return hit;
633
+ });
634
+ const onHighlighted = isHighlighted(vec2(0));
635
+ let besideHighlighted = float(0);
636
+ for (const [x, y] of EIGHT_DIRECTIONS) besideHighlighted = max(besideHighlighted, isHighlighted(vec2(x, y).mul(thickness).round()));
637
+ const ring = besideHighlighted.mul(float(1).sub(onHighlighted));
638
+ const swing = float(.75).add(float(.25).mul(time.mul(pulse).mul(2 * Math.PI).cos()));
639
+ const lifted = input.color.rgb.mul(float(1).add(brightness.sub(1).mul(swing)));
640
+ const marked = mix(lifted, color, tint.mul(swing).clamp(0, 1));
641
+ const rgb = mix(input.color.rgb, marked, onHighlighted.mul(strength));
642
+ const node = vec4(mix(rgb, outlineColor, ring.mul(strength)), input.color.a);
643
+ return {
644
+ node: select(count.equal(uint(0)), input.color, node),
645
+ update
646
+ };
647
+ }
648
+ // src/effects/suggested.ts
649
+ /** The suggested combination of Tree Effects for each built-in Style. */
650
+ var SUGGESTED_TREE_EFFECTS = {
651
+ "low-poly": {
652
+ grade: {
653
+ saturation: 1.15,
654
+ contrast: 1.1
655
+ },
656
+ innerLines: {
657
+ color: "#18230f",
658
+ thickness: 1,
659
+ strength: .8
660
+ },
661
+ outline: {
662
+ color: "#18230f",
663
+ thickness: 2,
664
+ strength: .9,
665
+ betweenTrees: true
666
+ }
667
+ },
668
+ stylized: {
669
+ grade: {
670
+ saturation: .95,
671
+ contrast: 1.08,
672
+ tint: "#fff1e0"
673
+ },
674
+ glow: {
675
+ color: "#fff6c8",
676
+ intensity: .45,
677
+ threshold: .3,
678
+ radius: 8
679
+ },
680
+ innerLines: {
681
+ color: "#2b3a1c",
682
+ thickness: 1,
683
+ strength: .45,
684
+ normalThreshold: .5
685
+ },
686
+ outline: {
687
+ color: "#2b3a1c",
688
+ thickness: 2,
689
+ strength: .6
690
+ }
691
+ },
692
+ realistic: {
693
+ grade: {
694
+ exposure: 1.05,
695
+ contrast: 1.08,
696
+ saturation: .95,
697
+ tint: "#fff5e6"
698
+ },
699
+ glow: {
700
+ color: "#e8ffc0",
701
+ intensity: .35,
702
+ threshold: .12,
703
+ radius: 4
704
+ }
705
+ }
706
+ };
707
+ // src/effects/custom.ts
708
+ var nextId = 1;
709
+ /**
710
+ * Internal: the custom Tree Effects of a pipeline (`TreeEffects`, the Scene Pipeline) with their
711
+ * latest options. It decides their part of the graph's shape and of the scene pass's channels, and
712
+ * builds them into a graph at their places.
713
+ */
714
+ var CustomTreeEffectList = class {
715
+ entries = [];
716
+ /** The custom effects, in the order they were added. */
717
+ get effects() {
718
+ return this.entries.map((entry) => entry.effect);
719
+ }
720
+ add(effect, options) {
721
+ if (this.find(effect)) throw new Error("This custom Tree Effect is already added; use updateEffect() to change its options");
722
+ this.entries.push({
723
+ effect,
724
+ options,
725
+ id: nextId++,
726
+ live: null
727
+ });
728
+ }
729
+ /** Stores the options (used on rebuilds) and sets them on the built effect. */
730
+ update(effect, options) {
731
+ const entry = this.find(effect);
732
+ if (!entry) throw new Error("This custom Tree Effect is not added; add it with addEffect() first");
733
+ entry.options = options;
734
+ entry.live?.update(options);
735
+ }
736
+ /** Whether the effect was there. */
737
+ remove(effect) {
738
+ const entry = this.find(effect);
739
+ if (entry) this.entries.splice(this.entries.indexOf(entry), 1);
740
+ return !!entry;
741
+ }
742
+ /** The channels the custom effects declare. */
743
+ channels() {
744
+ return {
745
+ treeId: this.entries.some((entry) => entry.effect.channels?.treeId === true),
746
+ normal: this.entries.some((entry) => entry.effect.channels?.normal === true)
747
+ };
748
+ }
749
+ /** Their part of a graph's shape: which effects, in which order and at which places. */
750
+ shape() {
751
+ return this.entries.map((entry) => `${entry.id}@${placeOf(entry.effect)}`).join();
752
+ }
753
+ /** Builds the custom effects placed before `name` (or at the `'end'`) onto `input.color` and returns the resulting colour. */
754
+ buildBefore(name, input) {
755
+ let color = input.color;
756
+ for (const entry of this.entries) {
757
+ if (placeOf(entry.effect) !== name) continue;
758
+ entry.live = entry.effect.build(inputFor(entry.effect, {
759
+ ...input,
760
+ color
761
+ }), entry.options);
762
+ color = entry.live.node;
763
+ }
764
+ return color;
765
+ }
766
+ find(effect) {
767
+ return this.entries.find((entry) => entry.effect === effect);
768
+ }
769
+ };
770
+ function placeOf(effect) {
771
+ return effect.before ?? "highlight";
772
+ }
773
+ /** The input an effect may read: colour, mask, depth and camera, and only the channels it declares. */
774
+ function inputFor(effect, input) {
775
+ const { treeId, normal, normalEncoding, ...always } = input;
776
+ return {
777
+ ...always,
778
+ ...effect.channels?.treeId && treeId && { treeId },
779
+ ...effect.channels?.normal && normal && {
780
+ normal,
781
+ normalEncoding
782
+ }
783
+ };
784
+ }
785
+ // src/effects/effects.ts
786
+ /**
787
+ * Applies a combination of Tree Effects to `input` and returns the resulting colour node, for use in
788
+ * your own post-processing pipeline (`pipeline.outputNode = applyTreeEffects(...)`, or feed it into
789
+ * more effects). Order: colour grade, leaf glow, inner lines, outline, highlight (always on top).
790
+ * Empty settings return `input.color`. `highlighted`: the trees the Highlight marks (mutable, read every frame).
791
+ */
792
+ function applyTreeEffects(input, settings, highlighted = []) {
793
+ return liveTreeEffects(input, settings, highlighted).node;
794
+ }
795
+ /**
796
+ * The shape of a combination: what its graph is built from (the effects that are on, the glow
797
+ * radius, the outline's `betweenTrees` and the normal encoding of Inner Lines). Settings of the same
798
+ * shape only differ in uniforms.
799
+ */
800
+ function treeEffectsShape(settings, input, custom) {
801
+ const outline = settings.outline ? drawsBetweenTrees(settings) ? "between" : "outline" : null;
802
+ const innerLines = settings.innerLines ? input.normalEncoding ?? "color" : null;
803
+ const shape = [
804
+ !!settings.grade,
805
+ settings.glow ? glowRadius(settings.glow) : null,
806
+ outline,
807
+ innerLines,
808
+ !!settings.highlight
809
+ ];
810
+ const customShape = custom?.shape();
811
+ return JSON.stringify(customShape ? [...shape, customShape] : shape);
812
+ }
813
+ /** Whether the outline is also drawn between trees: part of the shape, and it needs the Tree ID channel. */
814
+ function drawsBetweenTrees(settings) {
815
+ return settings.outline?.betweenTrees === true;
816
+ }
817
+ /**
818
+ * {@link applyTreeEffects} with every colour and number as a uniform; `update()` needs the same shape.
819
+ * Internal (not in the /effects index): shared with the Scene Pipeline (`src/scene`). `custom`: the
820
+ * app's own Tree Effects, built in at their places (their `update()` is the list's, not this one's).
821
+ */
822
+ function liveTreeEffects(input, settings, highlighted, custom) {
823
+ const updates = [];
824
+ let color = input.color;
825
+ const before = (name) => {
826
+ if (custom) color = custom.buildBefore(name, {
827
+ ...input,
828
+ color
829
+ });
830
+ };
831
+ before("grade");
832
+ if (settings.grade) {
833
+ const grade = liveTreeColorGrade({
834
+ color,
835
+ mask: input.mask
836
+ }, settings.grade);
837
+ updates.push((s) => grade.update(s.grade));
838
+ color = grade.node;
839
+ }
840
+ before("glow");
841
+ if (settings.glow) {
842
+ const glow = liveLeafGlow({
843
+ color,
844
+ mask: input.mask
845
+ }, settings.glow);
846
+ updates.push((s) => glow.update(s.glow));
847
+ color = glow.node;
848
+ }
849
+ before("innerLines");
850
+ if (settings.innerLines) {
851
+ const lines = liveInnerLines({
852
+ ...input,
853
+ color
854
+ }, settings.innerLines);
855
+ updates.push((s) => lines.update(s.innerLines));
856
+ color = lines.node;
857
+ }
858
+ before("outline");
859
+ if (settings.outline) {
860
+ const outline = liveTreeOutline({
861
+ ...input,
862
+ color
863
+ }, settings.outline);
864
+ updates.push((s) => outline.update(s.outline));
865
+ color = outline.node;
866
+ }
867
+ before("highlight");
868
+ if (settings.highlight) {
869
+ const highlight = liveTreeHighlight({
870
+ ...input,
871
+ color
872
+ }, highlighted, settings.highlight);
873
+ updates.push((s) => highlight.update(s.highlight));
874
+ color = highlight.node;
875
+ }
876
+ before("end");
877
+ return {
878
+ node: color,
879
+ update: (s) => updates.forEach((update) => update(s))
880
+ };
881
+ }
882
+ /** The settings of a choice; throws for an unknown Style. Internal, shared with the Scene Pipeline. */
883
+ function resolveTreeEffects(choice) {
884
+ if (choice === null) return {};
885
+ if (typeof choice !== "string") return choice;
886
+ const settings = SUGGESTED_TREE_EFFECTS[choice];
887
+ if (!settings) throw new Error(`No suggested Tree Effects for Style "${choice}"`);
888
+ return settings;
889
+ }
890
+ /**
891
+ * The extra channels the scene pass needs for `settings` (with the `treeId` option and the channels
892
+ * the custom effects declare). Only this set decides the scene pass's MRT: settings that need the
893
+ * same channels keep it.
894
+ */
895
+ function channelsFor(settings, options, custom) {
896
+ const declared = custom?.channels();
897
+ return {
898
+ treeId: options.treeId === true || drawsBetweenTrees(settings) || !!settings.highlight || declared?.treeId === true,
899
+ normal: !!settings.innerLines || declared?.normal === true
900
+ };
901
+ }
902
+ /** A key that is equal for equal sets of channels. */
903
+ function channelsKey(channels) {
904
+ return Object.entries(channels).filter(([, on]) => on === true).map(([name]) => name).sort().join();
905
+ }
906
+ /**
907
+ * A ready-made post-processing pipeline (`RenderPipeline`) with the Tree Effects: render with
908
+ * `effects.render()` instead of `renderer.render(scene, camera)`. Switch the combination with
909
+ * `effects.set('stylized')` (e.g. a preview). For your own pipeline, use {@link treeEffectsPass}
910
+ * and {@link applyTreeEffects} instead.
911
+ */
912
+ var TreeEffects = class {
913
+ renderer;
914
+ scene;
915
+ camera;
916
+ options;
917
+ pipeline;
918
+ /** The trees the Highlight marks (the `highlighted` option, or an empty list): change it in place. */
919
+ highlighted;
920
+ nodes = [];
921
+ current = {};
922
+ custom = new CustomTreeEffectList();
923
+ graph = null;
924
+ input;
925
+ constructor(renderer, scene, camera, options = {}) {
926
+ this.renderer = renderer;
927
+ this.scene = scene;
928
+ this.camera = camera;
929
+ this.options = options;
930
+ this.pipeline = new RenderPipeline(renderer);
931
+ this.highlighted = options.highlighted ?? [];
932
+ this.set(options.effects ?? null);
933
+ }
934
+ /**
935
+ * The scene pass (colour + tree mask, plus the channels the settings need, such as the Tree ID).
936
+ *
937
+ * It is replaced by a new one (a new object, the old one disposed) when {@link set} needs another
938
+ * set of channels, and only then; read it again after such a `set()` rather than keeping it.
939
+ * Swapping only the MRT of one PassNode is not feasible with three: a PassNode can add targets
940
+ * (`getTexture`) but has no way to remove one, and its sample count is fixed per target, so
941
+ * turning a channel off (or the Tree ID off, which brings MSAA back) needs a new pass. Either way
942
+ * the scene's materials recompile, because the MRT changes; settings that need the same channels
943
+ * keep this pass and its MRT.
944
+ */
945
+ get scenePass() {
946
+ return this.input.pass;
947
+ }
948
+ /** The active combination (`{}` = none). */
949
+ get settings() {
950
+ return this.current;
951
+ }
952
+ /**
953
+ * Switches to a Style's suggested combination, custom settings, or none (`null`). With the same
954
+ * effects on (and the same glow radius) only the colours and numbers change, without a recompile;
955
+ * otherwise a new graph is built and the old one freed.
956
+ */
957
+ set(effects) {
958
+ this.current = resolveTreeEffects(effects);
959
+ this.rebuild();
960
+ }
961
+ /** The app's own Tree Effects, in the order they were added (see {@link addEffect}). */
962
+ get customEffects() {
963
+ return this.custom.effects;
964
+ }
965
+ /**
966
+ * Adds a Tree Effect of the app's own (see {@link CustomTreeEffect}) with its options, at the place
967
+ * it names among the built-in effects. It stays through {@link set} until {@link removeEffect}.
968
+ * Builds a new graph, and a new scene pass if it declares a channel that is not on yet.
969
+ */
970
+ addEffect(effect, ...[options]) {
971
+ this.custom.add(effect, options);
972
+ this.rebuild();
973
+ }
974
+ /** Changes the options of an added custom effect live, through its `update()` (no new graph, no recompile). */
975
+ updateEffect(effect, options) {
976
+ this.custom.update(effect, options);
977
+ }
978
+ /** Removes a custom effect (nothing happens if it is not added); its channels go when nothing else needs them. */
979
+ removeEffect(effect) {
980
+ if (this.custom.remove(effect)) this.rebuild();
981
+ }
982
+ /** Brings the scene pass and the graph in line with the settings and the custom effects. */
983
+ rebuild() {
984
+ const channels = channelsFor(this.current, this.options, this.custom);
985
+ const key = channelsKey(channels);
986
+ if (this.input?.channels !== key) {
987
+ this.disposeNodes();
988
+ this.input?.pass.pass.dispose();
989
+ this.input = {
990
+ channels: key,
991
+ pass: treeEffectsPass(this.scene, this.camera, this.options.selection ?? null, channels)
992
+ };
993
+ this.graph = null;
994
+ }
995
+ const shape = treeEffectsShape(this.current, this.scenePass, this.custom);
996
+ if (this.graph?.shape === shape) {
997
+ this.graph.effects.update(this.current);
998
+ return;
999
+ }
1000
+ this.disposeNodes();
1001
+ const live = liveTreeEffects(this.scenePass, this.current, this.highlighted, this.custom);
1002
+ this.graph = {
1003
+ shape,
1004
+ effects: live
1005
+ };
1006
+ this.nodes = collectEffectNodes(live.node, this.scenePass.color);
1007
+ this.pipeline.outputNode = live.node;
1008
+ this.pipeline.needsUpdate = true;
1009
+ }
1010
+ /**
1011
+ * GPU picking: the Tree or Forest tree under a point of the canvas (CSS pixels from its top left
1012
+ * corner, as `event.offsetX/offsetY`) in the last render, or `undefined` where no tree is drawn.
1013
+ * Needs the Tree ID channel: throws when it is off (create the effects with `treeId: true`).
1014
+ */
1015
+ pick(x, y) {
1016
+ const { pass, treeId } = this.scenePass;
1017
+ if (!treeId) throw new Error("TreeEffects.pick() needs the Tree ID channel: create the effects with the `treeId: true` option");
1018
+ return readTreeId(this.renderer, pass, x, y).then(treeFromId);
1019
+ }
1020
+ /** Renders the scene with the effects (call instead of `renderer.render(scene, camera)`). */
1021
+ render() {
1022
+ this.pipeline.render();
1023
+ }
1024
+ dispose() {
1025
+ this.disposeNodes();
1026
+ this.scenePass.pass.dispose();
1027
+ this.pipeline.dispose();
1028
+ }
1029
+ disposeNodes() {
1030
+ for (const node of this.nodes) node.dispose();
1031
+ this.nodes = [];
1032
+ }
1033
+ };
1034
+ /** The render-target owning nodes (blur) in an effects graph, to dispose them on change. */
1035
+ function collectEffectNodes(output, stop) {
1036
+ const found = /* @__PURE__ */ new Set();
1037
+ const visit = (node, seen) => {
1038
+ if (seen.has(node) || node === stop) return;
1039
+ seen.add(node);
1040
+ if (node.isGaussianBlurNode) found.add(node);
1041
+ for (const child of node.getChildren()) visit(child, seen);
1042
+ };
1043
+ visit(output, /* @__PURE__ */ new Set());
1044
+ return [...found];
1045
+ }
1046
+ /** Shorthand for `new TreeEffects(renderer, scene, camera, options)`. */
1047
+ function createTreeEffects(renderer, scene, camera, options) {
1048
+ return new TreeEffects(renderer, scene, camera, options);
1049
+ }
1050
+ export { treeIdMRT as C, treeFromId as S, treeIdTexture as T, TREE_NORMAL as _, collectEffectNodes as a, TREE_ID as b, resolveTreeEffects as c, SUGGESTED_TREE_EFFECTS as d, treeHighlight as f, treeEffectsPass as g, treeOutline as h, channelsKey as i, treeEffectsShape as l, leafGlow as m, applyTreeEffects as n, createTreeEffects as o, treeColorGrade as p, channelsFor as r, liveTreeEffects as s, TreeEffects as t, CustomTreeEffectList as u, innerLines as v, treeIdOf as w, readTreeId as x, treeNormalMRT as y };
1051
+
1052
+ //# sourceMappingURL=effects-qHx_8Dlk.js.map