Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Changelog

## [1.1.1]

- Fix unbounded memory leak when running sketches
- Replace the `jsdom` dependency with a minimal DOM stub

## [1.0.1]

New package name.
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ For streaming frames to external systems, see [examples/ex-p5b-zmq.js](examples/

## Environment

**Node.js only.** p5b uses JSDOM for headless Canvas and native Node.js APIs. Browsers are not supported.
**Node.js only.** p5b uses a custom headless DOM shim with native Node.js APIs and `canvas`. Browsers are not supported.

## Credits

Expand Down
38 changes: 36 additions & 2 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,25 @@ module.exports = [
globals: {
describe: "readonly",
it: "readonly",
expect: "readonly"
expect: "readonly",
createCanvas: "readonly",
background: "readonly",
fill: "readonly",
stroke: "readonly",
rect: "readonly",
circle: "readonly",
frameCount: "readonly",
width: "readonly",
height: "readonly",
createGraphics: "readonly",
loadFont: "readonly",
noStroke: "readonly",
ellipse: "readonly",
image: "readonly"
}
},
rules: {
"no-unused-vars": "off"
}
},
{
Expand All @@ -50,8 +67,25 @@ module.exports = [
globals: {
describe: "readonly",
it: "readonly",
expect: "readonly"
expect: "readonly",
createCanvas: "readonly",
background: "readonly",
fill: "readonly",
stroke: "readonly",
rect: "readonly",
circle: "readonly",
frameCount: "readonly",
width: "readonly",
height: "readonly",
createGraphics: "readonly",
loadFont: "readonly",
noStroke: "readonly",
ellipse: "readonly",
image: "readonly"
}
},
rules: {
"no-unused-vars": "off"
}
},
{
Expand Down
9 changes: 6 additions & 3 deletions examples/lib/p5b-zmq.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,9 @@ class P5bZMQ {
}

async onFrame(pixelBuffer) {
if (pixelBuffer.length !== this.p.width * this.p.height * 4) {
const err = new Error(`Size mismatch: ${pixelBuffer.length} != ${this.p.width * this.p.height * 4}`);
const expectedSize = this.p.width * this.p.height * 4;
if (pixelBuffer.length !== expectedSize) {
const err = new Error(`Size mismatch: ${pixelBuffer.length} != ${expectedSize}`);
if (!this.silent) {
console.error(err.message);
}
Expand All @@ -71,7 +72,9 @@ class P5bZMQ {

this.pending = true;
try {
await this.sock.send(pixelBuffer);
// Copy buffer before async operation since toFrame() reuses the buffer
const bufferCopy = new Uint8Array(pixelBuffer);
await this.sock.send(bufferCopy);
await this.sock.receive();
this.metrics.framesSent++;
} catch (err) {
Expand Down
2 changes: 1 addition & 1 deletion examples/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@10k24/p5b-examples",
"version": "1.0.1",
"version": "1.1.1",
"description": "Examples for p5b",
"private": true,
"type": "commonjs",
Expand Down
170 changes: 170 additions & 0 deletions p5b-dom.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
const canvas = require("canvas");

const noop = () => {};
const spliceFrom = (arr, item) => {
const idx = arr.indexOf(item);
idx > -1 && arr.splice(idx, 1);
};

class P5bDOM {
constructor(width, height) {
this.width = width;
this.height = height;
this._bodyChildren = [];
this._canvases = [];
this._init();
}

getCanvas() {
return global.document.querySelector("canvas");
}

removeTrackedCanvas(canvasEl) {
spliceFrom(this._canvases, canvasEl);
spliceFrom(this._bodyChildren, canvasEl);
}

clear() {
this._bodyChildren.length = 0;
this._canvases.length = 0;
}

_init() {
const bodyChildren = this._bodyChildren;
const allCanvases = this._canvases;

const makeStubElement = (tag) => {
const el = {
tagName: tag.toUpperCase(),
id: "",
style: {},
dataset: {},
classList: { add: noop, remove: noop, contains: () => false, toggle: noop },
addEventListener: noop,
removeEventListener: noop,
dispatchEvent: () => true,
appendChild: (child) => { el.childNodes.push(child); return child; },
removeChild: (child) => {
spliceFrom(el.childNodes, child);
return child;
},
setAttribute: noop,
getAttribute: () => null,
getBoundingClientRect: () => ({ left: 0, top: 0, width: 0, height: 0, right: 0, bottom: 0 }),
parentNode: null,
childNodes: [],
children: [],
innerHTML: "",
textContent: "",
};
return el;
};

const makeCanvas = () => {
const c = canvas.createCanvas(1, 1);
c.classList = { add: noop, remove: noop, contains: () => false, toggle: noop };
c.dataset = {};
c.setAttribute = noop;
c.getAttribute = () => null;
c.addEventListener = noop;
c.removeEventListener = noop;
c.dispatchEvent = () => true;
c.getBoundingClientRect = () => ({ left: 0, top: 0, width: c.width, height: c.height, right: c.width, bottom: c.height });
c.parentNode = null;
c.style = {};
allCanvases.push(c);
return c;
};

const document = {
createElement: (tag) => {
if (tag === "canvas") return makeCanvas();
return makeStubElement(tag);
},
createElementNS: (_ns, tag) => makeStubElement(tag),
body: {
appendChild: (el) => { bodyChildren.push(el); if (el && typeof el === "object") el.parentNode = document.body; return el; },
removeChild: (el) => {
spliceFrom(bodyChildren, el);
if (el && typeof el === "object") el.parentNode = null;
spliceFrom(allCanvases, el);
return el;
},
style: {},
classList: { add: noop, remove: noop, contains: () => false, toggle: noop },
clientWidth: this.width,
clientHeight: this.height,
addEventListener: noop,
removeEventListener: noop,
dispatchEvent: () => true,
},
head: { appendChild: noop, removeChild: noop, getElementsByTagName: () => [] },
querySelector: (sel) => {
if (sel === "canvas") return allCanvases[0] || null;
return null;
},
querySelectorAll: (sel) => {
if (sel === "canvas") return allCanvases.slice();
return [];
},
getElementById: (id) => bodyChildren.find((el) => el.id === id) || null,
getElementsByTagName: (tag) => {
const t = tag.toLowerCase();
if (t === "canvas") return allCanvases.slice();
if (t === "head") return [document.head];
return bodyChildren.filter((el) => el.tagName && el.tagName.toLowerCase() === t);
},
documentElement: { style: {}, classList: { add: noop, remove: noop, contains: () => false }, clientWidth: this.width, clientHeight: this.height },
readyState: "complete",
addEventListener: noop,
removeEventListener: noop,
dispatchEvent: () => true,
createEvent: () => ({ initEvent: noop }),
hasFocus: () => true,
hidden: false,
};

const stubStyle = { getPropertyValue: () => "", display: "block", width: "0px", height: "0px" };

const win = {
document,
screen: { width: this.width, height: this.height },
navigator: { userAgent: "Node.js", languages: ["en"], language: "en", userLanguage: "en", mediaDevices: null },
addEventListener: noop,
removeEventListener: noop,
dispatchEvent: () => true,
requestAnimationFrame: (cb) => setImmediate(cb),
cancelAnimationFrame: (id) => clearImmediate(id),
innerWidth: this.width,
innerHeight: this.height,
devicePixelRatio: 1,
location: { search: "", pathname: "/", href: "http://localhost/", hash: "" },
getComputedStyle: () => stubStyle,
URL: { createObjectURL: () => "", revokeObjectURL: noop },
Event: class Event { constructor(type) { this.type = type; this.bubbles = false; this.cancelable = false; } },
MouseEvent: class MouseEvent { constructor(type) { this.type = type; } },
HTMLCanvasElement: canvas.Canvas,
ImageData: canvas.ImageData,
performance: { now: () => Date.now() },
};

global.window = win;
global.document = document;
global.screen = win.screen;
if (!Object.getOwnPropertyDescriptor(global, "navigator")) {
Object.defineProperty(global, "navigator", {
get: () => global.window.navigator,
configurable: true
});
}
global.HTMLCanvasElement = canvas.Canvas;
global.ImageData = canvas.ImageData;
global.requestAnimationFrame = (cb) => setImmediate(cb);
global.cancelAnimationFrame = (id) => clearImmediate(id);
global.Event = win.Event;
global.MouseEvent = win.MouseEvent;

}
}

module.exports = { P5bDOM };
Loading
Loading