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