MCPcopy Index your code
hub / github.com/processing/p5.js / readPixelsWebGL

Function readPixelsWebGL

src/webgl/utils.js:20–74  ·  view source on GitHub ↗
(
  pixels,
  gl,
  framebuffer,
  x,
  y,
  width,
  height,
  format,
  type,
  flipY,
)

Source from the content-addressed store, hash-verified

18 * WebGL context read into it
19 */
20export function readPixelsWebGL(
21 pixels,
22 gl,
23 framebuffer,
24 x,
25 y,
26 width,
27 height,
28 format,
29 type,
30 flipY,
31) {
32 // Record the currently bound framebuffer so we can go back to it after, and
33 // bind the framebuffer we want to read from
34 const prevFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
35 gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
36
37 const channels = format === gl.RGBA ? 4 : 3;
38
39 // Make a pixels buffer if it doesn't already exist
40 const len = width * height * channels;
41 const TypedArrayClass = type === gl.UNSIGNED_BYTE ? Uint8Array : Float32Array;
42 if (!(pixels instanceof TypedArrayClass) || pixels.length !== len) {
43 pixels = new TypedArrayClass(len);
44 }
45
46 gl.readPixels(
47 x,
48 flipY ? flipY - y - height : y,
49 width,
50 height,
51 format,
52 type,
53 pixels,
54 );
55
56 // Re-bind whatever was previously bound
57 gl.bindFramebuffer(gl.FRAMEBUFFER, prevFramebuffer);
58
59 if (flipY) {
60 // WebGL pixels are inverted compared to 2D pixels, so we have to flip
61 // the resulting rows. Adapted from https://stackoverflow.com/a/41973289
62 const halfHeight = Math.floor(height / 2);
63 const tmpRow = new TypedArrayClass(width * channels);
64 for (let y = 0; y < halfHeight; y++) {
65 const topOffset = y * width * 4;
66 const bottomOffset = (height - y - 1) * width * 4;
67 tmpRow.set(pixels.subarray(topOffset, topOffset + width * 4));
68 pixels.copyWithin(topOffset, bottomOffset, bottomOffset + width * 4);
69 pixels.set(tmpRow, bottomOffset);
70 }
71 }
72
73 return pixels;
74}
75
76/**
77 * @private

Callers 3

loadPixelsMethod · 0.90
readFramebufferPixelsMethod · 0.90
readFramebufferRegionMethod · 0.90

Calls 2

bindFramebufferMethod · 0.45
setMethod · 0.45

Tested by

no test coverage detected