@threenative/three-native 0.3.10 → 0.3.12

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.
package/src/pass-node.ts CHANGED
@@ -25,10 +25,44 @@ interface IPassTarget {
25
25
  readonly texture: unknown;
26
26
  readonly width: number;
27
27
  readonly height: number;
28
+ /** The pass's colour attachments, in layout order; an offscreen engine target keeps its own list. */
29
+ readonly textures?: readonly IPassAttachment[];
30
+ /** The frame's MSAA sample count, as the engine draws it. */
31
+ readonly samples?: number;
28
32
  setSize(width: number, height: number): void;
29
33
  dispose(): void;
30
34
  }
31
35
 
36
+ /**
37
+ * One colour attachment of the frame pass, as a game reads it (three's Texture): its name, format, type
38
+ * and colour space. The engine owns the GPU texture, so this descriptor names the target the engine
39
+ * draws and the renderer reads back; it is not a sampled texture handle.
40
+ */
41
+ export interface IPassAttachment {
42
+ name: string;
43
+ format: number;
44
+ type: number;
45
+ colorSpace: string;
46
+ }
47
+
48
+ /**
49
+ * The frame pass's render target: three's RenderTarget surface over the colour attachments the engine
50
+ * draws. `textures` is the MRT layout (its own colour first), `width`/`height` the size the engine draws
51
+ * at, and `samples` the frame's MSAA count; `dispose` dispatches three's event.
52
+ */
53
+ export interface IFrameTarget {
54
+ readonly texture: IPassAttachment;
55
+ readonly textures: readonly IPassAttachment[];
56
+ readonly width: number;
57
+ readonly height: number;
58
+ readonly samples: number;
59
+ setSize(width: number, height: number): void;
60
+ dispose(): void;
61
+ addEventListener(type: string, listener: unknown): void;
62
+ removeEventListener(type: string, listener: unknown): void;
63
+ dispatchEvent(event: { type: string }): void;
64
+ }
65
+
32
66
  /** What an offscreen pass needs of a back end: its RenderTarget, and the surface before a first frame. */
33
67
  export interface IPassHost {
34
68
  // quality-allow: three's class name, so a back end passes its class map.
@@ -39,6 +73,100 @@ export interface IPassHost {
39
73
  options: { type: number },
40
74
  ) => IPassTarget;
41
75
  surface?(): ISurface;
76
+ /** The frame's MSAA sample count: the renderer's, which the game may not have made yet. */
77
+ samples?(): number;
78
+ }
79
+
80
+ const RGBA_FORMAT = 1023; // three's RGBAFormat
81
+ const NO_COLOR_SPACE = ""; // three's NoColorSpace
82
+
83
+ /** The colour attachment names of a frame pass, for the renderer's readback by attachment index. */
84
+ const ATTACHMENT_NAMES = Symbol.for("threenative.passAttachmentNames");
85
+
86
+ /** The name of a frame pass's colour attachment `index`, or undefined for any other target. */
87
+ export function frameAttachmentName(target: unknown, index: number): string | undefined {
88
+ if (typeof target !== "object" || target === null) return undefined;
89
+ return (target as { [ATTACHMENT_NAMES]?: readonly string[] })[ATTACHMENT_NAMES]?.[index];
90
+ }
91
+
92
+ /**
93
+ * The frame pass's colour attachments: three's RenderTarget surface over the targets the engine draws.
94
+ * The engine owns their GPU memory, so a resize and a dispose belong to it; this object answers what a
95
+ * game reads (the layout, the size, the sample count) and dispatches three's `dispose` event.
96
+ */
97
+ class FrameTarget implements IFrameTarget {
98
+ readonly texture: IPassAttachment = {
99
+ name: "output",
100
+ format: RGBA_FORMAT,
101
+ type: HALF_FLOAT_TYPE,
102
+ colorSpace: NO_COLOR_SPACE,
103
+ };
104
+ #attachments: IPassAttachment[] = [this.texture];
105
+ readonly #events = new Map<string, Set<unknown>>();
106
+ readonly #host: IPassHost | undefined;
107
+
108
+ constructor(host: IPassHost | undefined) {
109
+ this.#host = host;
110
+ }
111
+
112
+ get textures(): readonly IPassAttachment[] {
113
+ return this.#attachments;
114
+ }
115
+ get width(): number {
116
+ return this.#host?.surface?.()?.width ?? 1;
117
+ }
118
+ get height(): number {
119
+ return this.#host?.surface?.()?.height ?? 1;
120
+ }
121
+ get samples(): number {
122
+ return this.#host?.samples?.() ?? 1;
123
+ }
124
+ // The readback names an attachment by its index in `textures`; a facade has no `indexOf` identity to publish.
125
+ get [ATTACHMENT_NAMES](): readonly string[] {
126
+ return this.#attachments.map((attachment) => attachment.name);
127
+ }
128
+
129
+ /** three's RenderTarget.setSize: the engine resizes its own pass, so the layout size follows it. */
130
+ setSize(_width: number, _height: number): void {}
131
+
132
+ /** three's MRT layout: the pass's output first, then each further named target, in author order. */
133
+ setLayout(names: readonly string[]): void {
134
+ const kept = new Map(this.#attachments.map((attachment) => [attachment.name, attachment]));
135
+ this.#attachments = names.map((name) => kept.get(name) ?? attachment(name));
136
+ }
137
+
138
+ /** three's PassNode.getTexture: a name the pass did not hold becomes a further colour attachment. */
139
+ named(name: string): IPassAttachment {
140
+ let found = this.#attachments.find((attachment) => attachment.name === name);
141
+ if (found === undefined) {
142
+ found = attachment(name);
143
+ this.#attachments.push(found);
144
+ }
145
+ return found;
146
+ }
147
+
148
+ addEventListener(type: string, listener: unknown): void {
149
+ const listeners = this.#events.get(type) ?? new Set<unknown>();
150
+ listeners.add(listener);
151
+ this.#events.set(type, listeners);
152
+ }
153
+ removeEventListener(type: string, listener: unknown): void {
154
+ this.#events.get(type)?.delete(listener);
155
+ }
156
+ dispatchEvent(event: { type: string }): void {
157
+ for (const listener of this.#events.get(event.type) ?? []) {
158
+ if (typeof listener === "function") (listener as (event: unknown) => void)(event);
159
+ else (listener as { handleEvent(event: unknown): void }).handleEvent(event);
160
+ }
161
+ }
162
+
163
+ dispose(): void {
164
+ this.dispatchEvent({ type: "dispose" });
165
+ }
166
+ }
167
+
168
+ function attachment(name: string): IPassAttachment {
169
+ return { name, format: RGBA_FORMAT, type: HALF_FLOAT_TYPE, colorSpace: NO_COLOR_SPACE };
42
170
  }
43
171
 
44
172
  /** Draws `scene` through `camera` into `target`, at the call. */
@@ -53,6 +181,8 @@ interface IPassTsl {
53
181
  readonly vec4?: (...values: unknown[]) => unknown;
54
182
  readonly cameraNear?: IPassMath;
55
183
  readonly cameraFar?: IPassMath;
184
+ /** The engine's mrt(names, ...nodes): a material mrtNode of named outputs. */
185
+ readonly mrt?: (names: string, ...nodes: unknown[]) => object;
56
186
  }
57
187
 
58
188
  /** The node arithmetic getViewZNode composes. */
@@ -68,8 +198,49 @@ interface IMRTSlot {
68
198
  readonly name: string;
69
199
  }
70
200
 
201
+ /**
202
+ * The slot names the engine's scene pass already owns: its colour, depth, velocity and surface targets.
203
+ * A custom slot keeps its own name and cannot take one of these, because the pass answers that name
204
+ * with its own target (getTextureNode).
205
+ */
206
+ const RESERVED_SLOTS: ReadonlySet<string> = new Set([
207
+ "output",
208
+ "depth",
209
+ "velocity",
210
+ "normal",
211
+ "metalness",
212
+ "roughness",
213
+ "diffuseColor",
214
+ "emissive",
215
+ ]);
216
+
217
+ /**
218
+ * Whether a material's `mrtNode` carries this output. The engine's scene pass draws its own colour,
219
+ * depth, velocity, normal and surface targets every frame, so a material writes only the names the pass
220
+ * does not own; a marker value (the pass's own slot) says the same for any other name it reached.
221
+ */
222
+ export function isCustomMrtOutput(name: string, value: unknown): boolean {
223
+ if (RESERVED_SLOTS.has(name)) return false;
224
+ return (value as { isMRTSlot?: boolean } | null)?.isMRTSlot !== true;
225
+ }
226
+
227
+ /** WebGPU's guaranteed colour-attachment count, and what a device's limit reports here when it answers. */
228
+ function maxColorAttachments(): number {
229
+ const limit = (
230
+ globalThis as {
231
+ navigator?: { gpu?: { limits?: { maxColorAttachments?: unknown } } };
232
+ }
233
+ ).navigator?.gpu?.limits?.maxColorAttachments;
234
+ return typeof limit === "number" && Number.isSafeInteger(limit) && limit > 0 ? limit : 8;
235
+ }
236
+
71
237
  interface IMRTNode {
72
238
  readonly isMRTNode: true;
239
+ /** Set on the material form, whose output nodes are a RenderTarget's attachments; the scene pass keeps its slots. */
240
+ readonly isMaterialMrt?: true;
241
+ /** three's MRTNode.outputNodes: the node each named output writes. */
242
+ readonly outputNodes: Readonly<Record<string, unknown>>;
243
+ /** The same record under the facade's earlier name, which the Wasm backend's setter reads. */
73
244
  readonly outputs: Readonly<Record<string, unknown>>;
74
245
  /**
75
246
  * three's per-output blend state. The engine's scene pass keeps the material's own blending on
@@ -120,25 +291,107 @@ export function definePass(
120
291
  const diffuseColor = slot("diffuseColor");
121
292
  const emissive = slot("emissive");
122
293
 
294
+ /** A scene pass output: one of the slots, or `normal` as normalView (or vec4(normalView, 0)). */
295
+ const passOutput = (name: string, value: unknown): boolean =>
296
+ (value as IMRTSlot | null)?.isMRTSlot === true ||
297
+ (name === "normal" &&
298
+ (value === normalView ||
299
+ (value as { __tnNormalView?: unknown } | null)?.__tnNormalView === normalView));
300
+
301
+ /**
302
+ * Outputs that are TSL nodes (not the scene pass's slots): a material's mrtNode, written into a RenderTarget made
303
+ * with `count`, each output to the texture of its name. `output` keeps the material's own colour there. The scene
304
+ * pass draws its own targets every frame, so a record carries them beside the material's nodes (three's templates
305
+ * spell `normal` as normalView there) and the material writes only the nodes: `mrtNode` skips the reserved names.
306
+ */
307
+ function materialMrt(
308
+ outputs: Record<string, unknown>,
309
+ nodes: [string, unknown][],
310
+ engineMrt: NonNullable<IPassTsl["mrt"]>,
311
+ ): IMRTNode {
312
+ // A pass slot object beside material nodes is a wiring error: only the pass draws that target. The normal target
313
+ // as normalView is not a slot object, so it stays the spelling a material's mrt() carries.
314
+ for (const [name, value] of Object.entries(outputs))
315
+ if (value !== output && (value as IMRTSlot | null)?.isMRTSlot === true)
316
+ throw new Error(
317
+ `TN_NATIVE_MRT_UNSUPPORTED: ${name} mixes a scene pass slot with material outputs`,
318
+ );
319
+ if (nodes.some(([name]) => name.includes(",")))
320
+ throw new Error("TN_NATIVE_MRT_UNSUPPORTED: an mrt() output name holds a comma");
321
+ const node = engineMrt(
322
+ nodes.map(([name]) => name).join(","),
323
+ ...nodes.map(([, value]) => value),
324
+ );
325
+ const blendModes: Record<string, unknown> = {};
326
+ // Defined, not assigned: a node may be a proxy whose set trap means `uniform.value = x`.
327
+ return Object.defineProperties(node, {
328
+ isMRTNode: { value: true },
329
+ // A material's mrt(): its output nodes go to a RenderTarget's textures, never to the scene pass's targets.
330
+ isMaterialMrt: { value: true },
331
+ outputs: { value: Object.freeze({ ...outputs }) },
332
+ // The material's blending writes every attachment, as three's does when the renderer has no MRT.
333
+ blendModes: { value: blendModes },
334
+ setBlendMode: {
335
+ value: (name: string, blend: unknown): IMRTNode => {
336
+ blendModes[name] = blend;
337
+ return node as IMRTNode;
338
+ },
339
+ },
340
+ getBlendMode: { value: (name: string): unknown => blendModes[name] },
341
+ has: { value: (name: string): boolean => name in outputs },
342
+ }) as IMRTNode;
343
+ }
344
+
123
345
  function mrt(outputs: Record<string, unknown>): IMRTNode {
346
+ const entries = Object.entries(outputs);
347
+ const limit = maxColorAttachments();
348
+ if (entries.length > limit)
349
+ throw new Error(
350
+ `TN_NATIVE_MRT_UNSUPPORTED: ${entries.length} colour attachments exceed the device limit ${limit}`,
351
+ );
124
352
  const named: Record<string, unknown> = {};
125
- for (const [name, value] of Object.entries(outputs)) {
353
+ const nodes = Object.entries(outputs).filter(([name, value]) => !passOutput(name, value));
354
+ if (nodes.length > 0 && tsl.mrt !== undefined) return materialMrt(outputs, nodes, tsl.mrt);
355
+ for (const [name, value] of entries) {
126
356
  const normal =
127
357
  name === "normal" &&
128
358
  (value === normalView ||
129
359
  (value as { __tnNormalView?: unknown } | null)?.__tnNormalView === normalView);
360
+ if (normal) {
361
+ named[name] = normalView;
362
+ continue;
363
+ }
364
+ const engineSlot = value as IMRTSlot | null;
365
+ // A name the engine's pass owns keeps its exact spelling: its own slot, or the refusal it always gave.
366
+ if (RESERVED_SLOTS.has(name)) {
367
+ if (engineSlot?.isMRTSlot === true && engineSlot.name === name) {
368
+ named[name] = value;
369
+ continue;
370
+ }
371
+ throw new Error(
372
+ `TN_NATIVE_MRT_UNSUPPORTED: ${name} must be one of output, normal: normalView or vec4(normalView, 0), metalness, roughness, diffuseColor, emissive`,
373
+ );
374
+ }
375
+ // An engine target under a custom name is a wiring error, not a node.
130
376
  if (
131
- !normal &&
132
- ((value as IMRTSlot | null)?.isMRTSlot !== true || name !== (value as IMRTSlot).name)
377
+ engineSlot?.isMRTSlot === true ||
378
+ (value !== null && typeof value === "object" && "isMRTSlot" in value)
133
379
  )
134
380
  throw new Error(
135
381
  `TN_NATIVE_MRT_UNSUPPORTED: ${name} must be one of output, normal: normalView or vec4(normalView, 0), metalness, roughness, diffuseColor, emissive`,
136
382
  );
137
- named[name] = normal ? normalView : value;
383
+ // Any other name is a custom colour attachment: three's mrt() takes any node there.
384
+ if (value === null || typeof value !== "object" || Array.isArray(value))
385
+ throw new Error(
386
+ `TN_NATIVE_MRT_UNSUPPORTED: the '${name}' slot must be a shader node, got ${value === null ? "null" : Array.isArray(value) ? "an array" : typeof value}`,
387
+ );
388
+ named[name] = value;
138
389
  }
390
+ const frozen = Object.freeze(named);
139
391
  const node: IMRTNode = Object.freeze({
140
392
  isMRTNode: true as const,
141
- outputs: Object.freeze(named),
393
+ outputNodes: frozen,
394
+ outputs: frozen,
142
395
  blendModes: {} as Record<string, unknown>,
143
396
  setBlendMode(name: string, blend: unknown): IMRTNode {
144
397
  node.blendModes[name] = blend;
@@ -180,10 +433,15 @@ export function definePass(
180
433
  interface IOffscreen {
181
434
  [drawPass](surface: ISurface, draw: PassDraw): void;
182
435
  }
436
+ /** A pass the engine's frame draws: its updateBefore is the frame's hook. */
437
+ interface IPassFrame {
438
+ updateBefore(frame: unknown): unknown;
439
+ }
183
440
  const offscreen = new Set<IOffscreen>();
441
+ const frameNodes = new Set<IPassFrame>();
184
442
  let lastSurface: ISurface | undefined;
185
443
 
186
- class PassNode implements IOffscreen {
444
+ class PassNode implements IOffscreen, IPassFrame {
187
445
  static readonly COLOR = "color";
188
446
  static readonly DEPTH = "depth";
189
447
  readonly isPassNode = true;
@@ -192,6 +450,7 @@ export function definePass(
192
450
  #camera: unknown;
193
451
  #scale = 1;
194
452
  #target: IPassTarget | null = null;
453
+ #frameTarget: FrameTarget | null = null;
195
454
  #offscreen: boolean;
196
455
  #disposed = false;
197
456
  #viewZ = new Map<string, unknown>();
@@ -202,6 +461,7 @@ export function definePass(
202
461
  this.#offscreen = scope !== framePass;
203
462
  if (!this.#offscreen) {
204
463
  onTarget?.(scene, camera);
464
+ frameNodes.add(this);
205
465
  return;
206
466
  }
207
467
  if (scope !== PassNode.COLOR)
@@ -230,9 +490,40 @@ export function definePass(
230
490
  if (!this.#offscreen) onTarget?.(this.#scene, value);
231
491
  }
232
492
 
233
- /** The offscreen pass's real target, so its width and height are the allocated size. */
234
- get renderTarget(): IPassTarget | undefined {
235
- return this.#target ?? undefined;
493
+ /**
494
+ * The pass's target: an offscreen pass's own RenderTarget, or the frame pass's colour attachments.
495
+ * The frame pass draws into the engine's frame, so this answers its layout, size and sample count.
496
+ */
497
+ get renderTarget(): IPassTarget | IFrameTarget | undefined {
498
+ if (this.#offscreen) return this.#target ?? undefined;
499
+ this.#frameTarget ??= new FrameTarget(host);
500
+ return this.#frameTarget;
501
+ }
502
+
503
+ /**
504
+ * The texture of one of the pass's colour attachments, as three's PassNode.getTexture(name) answers it.
505
+ * A name the MRT does not write becomes a further attachment descriptor, as three pushes one.
506
+ */
507
+ getTexture(name = "output"): IPassAttachment {
508
+ if (this.#offscreen)
509
+ throw new Error(
510
+ "TN_NATIVE_PASS_TEXTURE_UNSUPPORTED: an offscreen PassNode's colour is a node (getTextureNode()) with no JS texture",
511
+ );
512
+ if (name === "depth")
513
+ throw new Error(
514
+ "TN_NATIVE_PASS_TEXTURE_UNSUPPORTED: the frame pass's depth is a node (getTextureNode('depth')), not a JS texture",
515
+ );
516
+ const target = this.renderTarget as FrameTarget;
517
+ return name === "output" ? target.texture : target.named(name);
518
+ }
519
+
520
+ /**
521
+ * three's PassNode.updateBefore: the pass's frame. The engine draws the frame pass itself, so this
522
+ * body is the safe point a game wraps to run code at the pass's frame (the water proof reads back
523
+ * the attachment the pass last drew). An offscreen pass draws in updateSecondaryPasses.
524
+ */
525
+ updateBefore(_frame: unknown): unknown {
526
+ return undefined;
236
527
  }
237
528
 
238
529
  setResolutionScale(scale: number): this {
@@ -268,9 +559,20 @@ export function definePass(
268
559
  setMRT(value: IMRTNode | null): this {
269
560
  if (value !== null && value?.isMRTNode !== true)
270
561
  throw new Error("TN_NATIVE_MRT_UNSUPPORTED: setMRT takes mrt()");
562
+ // The material form's output nodes are written into a RenderTarget by the material itself, so a scene pass
563
+ // cannot lay them out: three's setMRT takes the pass's own slots plus the custom colour attachments.
564
+ if (value !== null && value.isMaterialMrt === true)
565
+ throw new Error(
566
+ "TN_NATIVE_MRT_UNSUPPORTED: a material's mrt() writes node outputs; set it on material.mrtNode",
567
+ );
271
568
  if (value !== null && this.#offscreen)
272
569
  throw new Error("TN_NATIVE_MRT_UNSUPPORTED: an offscreen PassNode draws colour only");
273
570
  this.#mrt = value;
571
+ // The pass holds one colour attachment per output the MRT names, its own colour first (three's
572
+ // PassNode pushes a texture per MRT output; the engine draws that same layout).
573
+ const names = value === null ? [] : Object.keys(value.outputNodes);
574
+ this.#frameTarget ??= new FrameTarget(host);
575
+ this.#frameTarget.setLayout(["output", ...names.filter((name) => name !== "output")]);
274
576
  return this;
275
577
  }
276
578
 
@@ -300,6 +602,10 @@ export function definePass(
300
602
  return tsl.texture({ name: "albedo" }, tsl.uv());
301
603
  if (name === "emissive" && this.#mrt?.outputs.emissive === emissive)
302
604
  return tsl.texture({ name: "emissive" }, tsl.uv());
605
+ // The draws that composited over the frame, lit as they were drawn. The engine draws them while the post graph
606
+ // reads this name (Renderer::planAux), so the read is the request and no MRT output names it: the occlusion and
607
+ // the gather belong to the opaque surface, and the composite restores what a translucent sheet drew over it.
608
+ if (name === "translucent") return tsl.texture({ name: "translucent" }, tsl.uv());
303
609
  if (
304
610
  (name === "metalness" || name === "roughness") &&
305
611
  this.#mrt?.outputs.normal === normalView &&
@@ -311,6 +617,9 @@ export function definePass(
311
617
  (name === "roughness" && this.#mrt?.outputs.roughness === roughness)
312
618
  )
313
619
  return tsl.texture({ name }, tsl.uv());
620
+ // A custom slot the MRT names is a further colour target the engine draws (pass-node.ts).
621
+ if (this.#mrt !== null && Object.hasOwn(this.#mrt.outputs, name))
622
+ return tsl.texture({ name }, tsl.uv());
314
623
  throw new Error(
315
624
  `TN_NATIVE_PASS_TEXTURE_UNSUPPORTED: the native scene pass has no '${name}' target`,
316
625
  );
@@ -339,12 +648,26 @@ export function definePass(
339
648
  offscreen.delete(this);
340
649
  this.#target?.dispose();
341
650
  this.#target = null;
651
+ frameNodes.delete(this);
652
+ this.#frameTarget?.dispose();
653
+ this.#frameTarget = null;
342
654
  }
343
655
  }
344
656
 
345
657
  const pass = (scene: unknown, camera: unknown): PassNode =>
346
658
  new PassNode(framePass, scene, camera);
347
659
 
660
+ /**
661
+ * Runs every live frame pass's `updateBefore` at each render, as three's node update system does.
662
+ * The engine draws the frame pass itself, so a game's wrapper runs at the pass's frame point; a
663
+ * wrapper that must run once a frame (the water proof's copy) guards that itself, as three's
664
+ * PassNode does not count frames for it either.
665
+ */
666
+ function updateFramePasses(frame?: { frameId?: number }): void {
667
+ if (frameNodes.size === 0) return;
668
+ for (const node of [...frameNodes]) node.updateBefore(frame);
669
+ }
670
+
348
671
  /**
349
672
  * Draws every live offscreen pass into its target, at the surface size, before the frame that
350
673
  * samples them. A back end calls it once per frame with its drawing buffer and its target draw;
@@ -365,6 +688,7 @@ export function definePass(
365
688
  pass,
366
689
  PassNode,
367
690
  updateSecondaryPasses,
691
+ updateFramePasses,
368
692
  mrt,
369
693
  output,
370
694
  normalView,
@@ -7,6 +7,7 @@
7
7
 
8
8
  const HALF_FLOAT_TYPE = 1016; // three's HalfFloatType
9
9
  const FLOAT_TYPE = 1015; // three's FloatType
10
+ const RG_FORMAT = 1030; // three's RGFormat
10
11
 
11
12
  interface IRenderTargetLike {
12
13
  readonly texture: { readonly type: number };
@@ -27,9 +28,9 @@ function halfToFloat(bits: number): number {
27
28
  return bits & 0x8000 ? -magnitude : magnitude;
28
29
  }
29
30
 
30
- /** Bytes a pixel in the rows `read` returns: a FloatType target is RGBA32Float, any other RGBA16Float. */
31
- export function targetTexelBytes(type: number): number {
32
- return type === FLOAT_TYPE ? 16 : 8;
31
+ /** Bytes a pixel in the rows `read` returns: float32 channels for FloatType, else half; two for RGFormat, else four. */
32
+ export function targetTexelBytes(type: number, format?: number): number {
33
+ return (type === FLOAT_TYPE ? 4 : 2) * (format === RG_FORMAT ? 2 : 4);
33
34
  }
34
35
 
35
36
  /**
@@ -52,16 +53,28 @@ export function pixelsOfType(
52
53
 
53
54
  /** The engine's two calls for a back end's render targets. */
54
55
  export interface IRenderTargetEngine {
55
- /** Draws `root` through `camera` into `target`; throws the engine's refusal. */
56
+ /** Draws `root` through `camera` into `target` (over its contents when the renderer's autoClear is false); throws the engine's refusal. */
56
57
  draw(target: unknown, root: unknown, camera: unknown): void;
57
- /** The region's rows in the target's format (see targetTexelBytes), top row first. */
58
- read(target: unknown, x: number, y: number, width: number, height: number): Promise<Uint8Array>;
58
+ /** Clears `target`'s colour (to the renderer's clear colour) and/or depth. */
59
+ clear(target: unknown, color: boolean, depth: boolean): void;
60
+ /**
61
+ * The region's rows in the target's format (see targetTexelBytes), top row first, of colour
62
+ * attachment `textureIndex` (three's index into `target.textures`).
63
+ */
64
+ read(
65
+ target: unknown,
66
+ x: number,
67
+ y: number,
68
+ width: number,
69
+ height: number,
70
+ textureIndex?: number,
71
+ ): Promise<Uint8Array>;
59
72
  }
60
73
 
61
74
  /**
62
- * Adds three's setRenderTarget, getRenderTarget, getActiveCubeFace, getActiveMipmapLevel and
63
- * readRenderTargetPixelsAsync to a renderer facade's prototype, and routes its render() into the
64
- * current target. `engineOf(renderer)` reaches the engine for that renderer.
75
+ * Adds three's setRenderTarget, getRenderTarget, getActiveCubeFace, getActiveMipmapLevel, clear,
76
+ * clearColor, clearDepth, clearStencil and readRenderTargetPixelsAsync to a renderer facade's prototype,
77
+ * and routes its render() into the current target. `engineOf(renderer)` reaches the engine for that renderer.
65
78
  */
66
79
  export function defineRenderTargets(
67
80
  prototype: { render(scene: unknown, camera: unknown): void },
@@ -96,6 +109,18 @@ export function defineRenderTargets(
96
109
  if (target === null || target === undefined) render.call(this, scene, camera);
97
110
  else engineOf(this).draw(target, scene, camera);
98
111
  },
112
+ // ponytail: on the canvas clear() is a no-op, because the canvas render clears every frame. A target has no stencil.
113
+ clear(this: object, color = true, depth = true): void {
114
+ const target = targets.get(this);
115
+ if (target !== null && target !== undefined) engineOf(this).clear(target, color, depth);
116
+ },
117
+ clearColor(this: { clear(color: boolean, depth: boolean): void }): void {
118
+ this.clear(true, false);
119
+ },
120
+ clearDepth(this: { clear(color: boolean, depth: boolean): void }): void {
121
+ this.clear(false, true);
122
+ },
123
+ clearStencil(): void {},
99
124
  async readRenderTargetPixelsAsync(
100
125
  this: object,
101
126
  target: IRenderTargetLike,
@@ -103,8 +128,16 @@ export function defineRenderTargets(
103
128
  y: number,
104
129
  width: number,
105
130
  height: number,
131
+ textureIndex = 0,
132
+ faceIndex = 0,
106
133
  ): Promise<Uint8Array | Uint16Array | Float32Array> {
107
- const bytes = await engineOf(this).read(target, x, y, width, height);
134
+ if (faceIndex !== 0)
135
+ throw new Error(
136
+ "TN_NATIVE_RENDER_TARGET_UNSUPPORTED: a cube face other than 0 is not read natively",
137
+ );
138
+ const bytes = await engineOf(this).read(target, x, y, width, height, textureIndex);
139
+ // The engine crops tightly, and so does three 0.187.0 (copyTextureToBuffer removes the row
140
+ // padding), so the array a game reads has the same tight stride on both back ends.
108
141
  return pixelsOfType(bytes, target.texture.type);
109
142
  },
110
143
  });