diff --git a/package.json b/package.json index cab34320e0..790e26bb80 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,7 @@ "scripts": { "build": "rolldown -c", "dev": "vite preview/", + "dev:node": "concurrently -n build,server \"rolldown -c -w\" \"node --watch preview/node/sketch.mjs\"", "dev:global": "concurrently -n build,server \"rolldown -c -w\" \"npx vite preview/global/\"", "docs": "documentation build ./src/**/*.js ./src/**/**/*.js --shallow -o ./docs/data.json && node ./utils/convert.mjs", "bench": "vitest bench", @@ -64,6 +65,12 @@ }, "license": "LGPL-2.1", "browser": "./lib/p5.min.js", + "imports": { + "#platform": { + "p5-node": "./src/core/platform/node.js", + "default": "./src/core/platform/browser.js" + } + }, "exports": { ".": { "types": "./types/p5.d.ts", diff --git a/preview/node/sketch.mjs b/preview/node/sketch.mjs new file mode 100644 index 0000000000..116ef183b7 --- /dev/null +++ b/preview/node/sketch.mjs @@ -0,0 +1,13 @@ +// import p5 from "../../dist/app.node.js"; +// import p5 from "../../lib/p5.node.esm.js"; +import webgpu from "../../dist/webgpu/index.js"; + +p5.registerAddon(webgpu); + +const sketch = function (p) { + p.setup = function () { + p.createCanvas(800, 600, p.WEBGPU); + }; +}; + +new p5(sketch); diff --git a/rolldown.config.js b/rolldown.config.js index c1403cce6f..e02a6b1795 100644 --- a/rolldown.config.js +++ b/rolldown.config.js @@ -81,6 +81,19 @@ export default defineConfig([ // }) ] }, + //// Node build //// + { + input: 'src/app.js', + output: { + file: './lib/p5.node.esm.js', + format: 'esm', + banner + }, + resolve: { + conditionNames: ['p5-node', 'import', 'default'] + }, + plugins + }, //// Addon module builds (e.g. WebGPU) //// ...['webgpu'].map(module => ({ input: `src/${module}/index.js`, diff --git a/src/app.js b/src/app.js index bacb900420..a3b8896738 100644 --- a/src/app.js +++ b/src/app.js @@ -64,7 +64,8 @@ p5.registerAddon(strands); import svg from './shape/svg/p5.svg'; p5.registerAddon(svg); -import { waitForDocumentReady, _globalInit } from './core/init'; +import { _globalInit } from './core/init'; +import { waitForDocumentReady } from '#platform'; waitForDocumentReady().then(_globalInit); export default p5; diff --git a/src/core/init.js b/src/core/init.js index 72020beb8e..1b1d5ab989 100644 --- a/src/core/init.js +++ b/src/core/init.js @@ -35,19 +35,3 @@ export const _globalInit = () => { } } }; - -// make a promise that resolves when the document is ready -export const waitForDocumentReady = () => { - if (typeof document !== 'undefined') { - return new Promise((resolve, reject) => { - // if the page is ready, initialize p5 immediately - if (document.readyState === 'complete') { - resolve(); - // if the page is still loading, add an event listener - // and initialize p5 as soon as it finishes loading - } else { - window.addEventListener('load', resolve, false); - } - }); - } -}; diff --git a/src/core/p5.Renderer2D.js b/src/core/p5.Renderer2D.js index 44a8ad9aa0..ae45f18689 100644 --- a/src/core/p5.Renderer2D.js +++ b/src/core/p5.Renderer2D.js @@ -7,6 +7,7 @@ import { Element } from '../dom/p5.Element'; import { MediaElement } from '../dom/p5.MediaElement'; import { RGBP3 } from '../color/color_constants'; import FilterRenderer2D from '../image/filterRenderer2D'; +import { markP5Canvas, setCanvasSize, attachCanvas } from '#platform'; import { Matrix } from '../math/p5.Matrix'; import { PrimitiveToPath2DConverter } from '../shape/custom_shapes'; import { DefaultFill, textCoreConstants } from '../type/textCore'; @@ -26,10 +27,10 @@ class Renderer2D extends Renderer { this.canvas.style.display = 'none'; } - if (!this.elt.id) { - this.elt.id = `defaultCanvas${p5.sketchCount++}`; - } - this.elt.classList.add('p5Canvas'); + markP5Canvas( + this.elt, + this.elt.id || `defaultCanvas${p5.sketchCount++}` + ); // Extend renderer with methods of p5.Element with getters for (const p of Object.getOwnPropertyNames(Element.prototype)) { @@ -43,24 +44,10 @@ class Renderer2D extends Renderer { } // Set canvas size - this.elt.width = w * this._pixelDensity; - this.elt.height = h * this._pixelDensity; - this.elt.style.width = `${w}px`; - this.elt.style.height = `${h}px`; + setCanvasSize(this.elt, w, h, this._pixelDensity); // Attach canvas element to DOM - if (this._pInst._userNode) { - // user input node case - this._pInst._userNode.appendChild(this.elt); - } else { - //create main element - if (document.getElementsByTagName('main').length === 0) { - let m = document.createElement('main'); - document.body.appendChild(m); - } - //append canvas to main - document.getElementsByTagName('main')[0].appendChild(this.elt); - } + attachCanvas(this.elt, this._pInst._userNode); // Get and store drawing context this.drawingContext = this.canvas.getContext('2d', attributes); @@ -139,10 +126,7 @@ class Renderer2D extends Renderer { } } - this.canvas.width = w * this._pixelDensity; - this.canvas.height = h * this._pixelDensity; - this.canvas.style.width = `${w}px`; - this.canvas.style.height = `${h}px`; + setCanvasSize(this.canvas, w, h, this._pixelDensity); this.drawingContext.scale(this._pixelDensity, this._pixelDensity); // reset canvas properties diff --git a/src/core/p5.Renderer3D.js b/src/core/p5.Renderer3D.js index b01b4775e0..4c8a8ea53b 100644 --- a/src/core/p5.Renderer3D.js +++ b/src/core/p5.Renderer3D.js @@ -25,6 +25,7 @@ import { Texture } from '../webgl/p5.Texture'; import { makeFilterShader } from '../core/filterShaders'; import { getStrokeDefs } from '../webgl/enums'; import { markExperimental } from '../core/experimental'; +import { markP5Canvas, setCanvasSize, attachCanvas } from '#platform'; const { STROKE_CAP_ENUM, STROKE_JOIN_ENUM } = getStrokeDefs(() => ''); @@ -44,8 +45,7 @@ export class Renderer3D extends Renderer { // hide if offscreen buffer by default this.canvas.style.display = 'none'; } - this.elt.id = 'defaultCanvas0'; - this.elt.classList.add('p5Canvas'); + markP5Canvas(this.elt, 'defaultCanvas0'); // Set and return p5.Element this.wrappedElt = new Element(this.elt, this._pInst); @@ -69,25 +69,11 @@ export class Renderer3D extends Renderer { this.height = h; // Set canvas size - this.elt.width = w * this._pixelDensity; - this.elt.height = h * this._pixelDensity; - this.elt.style.width = `${w}px`; - this.elt.style.height = `${h}px`; + setCanvasSize(this.elt, w, h, this._pixelDensity); this._updateViewport(); // Attach canvas element to DOM - if (this._pInst._userNode) { - // user input node case - this._pInst._userNode.appendChild(this.elt); - } else { - //create main element - if (document.getElementsByTagName('main').length === 0) { - let m = document.createElement('main'); - document.body.appendChild(m); - } - //append canvas to main - document.getElementsByTagName('main')[0].appendChild(this.elt); - } + attachCanvas(this.elt, this._pInst._userNode); this.isP3D = true; //lets us know we're in 3d mode @@ -1315,10 +1301,7 @@ export class Renderer3D extends Renderer { this.width = w; this.height = h; - this.canvas.width = w * this._pixelDensity; - this.canvas.height = h * this._pixelDensity; - this.canvas.style.width = `${w}px`; - this.canvas.style.height = `${h}px`; + setCanvasSize(this.canvas, w, h, this._pixelDensity); this._updateViewport(); this._updateSize(); diff --git a/src/core/platform/browser.js b/src/core/platform/browser.js new file mode 100644 index 0000000000..f22242d20e --- /dev/null +++ b/src/core/platform/browser.js @@ -0,0 +1,75 @@ +/* +Browser adapter. Everything p5 needs from its host environment should go +through this module, so that non-browser builds can swap in +alternate implementations instead. +*/ + +// make a promise that resolves when the document is ready +export const waitForDocumentReady = () => { + if (typeof document !== 'undefined') { + return new Promise((resolve, reject) => { + // if the page is ready, initialize p5 immediately + if (document.readyState === 'complete') { + resolve(); + // if the page is still loading, add an event listener + // and initialize p5 as soon as it finishes loading + } else { + window.addEventListener('load', resolve, false); + } + }); + } +}; + +export const handleUncaughtErrors = callback => { + const handler = e => { + let error; + if (e instanceof ErrorEvent) { + error = e.error; + } else if (e instanceof PromiseRejectionEvent) { + error = e.reason; + if (!(error instanceof Error)) return; + } + if (error) callback(error); + }; + window.addEventListener('error', handler, false); + window.addEventListener('unhandledrejection', handler, false); +}; + +export const getUserScript = () => { + // TODO: think of a more robust way to get the user's code. Refer to + // https://github.com/processing/p5.js/pull/7293. + const scripts = document.querySelectorAll('script'); + return scripts[scripts.length - 1]; +}; + +export const isCanvasElement = data => data instanceof HTMLCanvasElement; + +// TODO is this the right API? +export const markP5Canvas = (elt, id) => { + elt.id = id; + elt.classList.add('p5Canvas'); +}; + +// TODO is this the right API? +export const setCanvasSize = (elt, w, h, density) => { + elt.width = w * density; + elt.height = h * density; + elt.style.width = `${w}px`; + elt.style.height = `${h}px`; +}; + +// TODO is this the right API? +export const attachCanvas = (elt, userNode) => { + if (userNode) { + // user input node case + userNode.appendChild(elt); + } else { + //create main element + if (document.getElementsByTagName('main').length === 0) { + let m = document.createElement('main'); + document.body.appendChild(m); + } + //append canvas to main + document.getElementsByTagName('main')[0].appendChild(elt); + } +}; diff --git a/src/core/platform/node.js b/src/core/platform/node.js new file mode 100644 index 0000000000..44c232ff5c --- /dev/null +++ b/src/core/platform/node.js @@ -0,0 +1,34 @@ +/* +Node adapter, used in place of `platform.js` by the p5.node build. +*/ + +// There is no document to wait for +export const waitForDocumentReady = () => Promise.resolve(); + +export const handleUncaughtErrors = callback => { + // Node rethrows unhandled promise rejections as uncaught exceptions, so they + // are caught here too + process.on('uncaughtExceptionMonitor', error => { + if (error instanceof Error) callback(error); + }); +}; + +// TODO: maybe read process.argv[1]? +export const getUserScript = () => undefined; + +// This prop is added in the wgpu code so we can identify it here +export const isCanvasElement = data => data?.isP5WGPUCanvas === true; + +// TODO is this the right API? +export const markP5Canvas = () => {}; + +// TODO is this the right API? +// TODO resize the window and surface once ngpu supports it +export const setCanvasSize = (elt, w, h, density) => { + elt.width = w * density; + elt.height = h * density; +}; + +// TODO is this the right API? +// No page to attach to on desktop +export const attachCanvas = () => {}; diff --git a/src/events/acceleration.js b/src/events/acceleration.js index 62ab0dbaa1..5b733cff91 100644 --- a/src/events/acceleration.js +++ b/src/events/acceleration.js @@ -9,11 +9,15 @@ function acceleration(p5, fn, lifecycles) { lifecycles.presetup = function () { const events = ['deviceorientation', 'devicemotion']; - for (const event of events) { - window.addEventListener(event, this[`_on${event}`].bind(this), { - passive: false, - signal: this._removeSignal - }); + // TODO: maybe move to platform-dependent if there's a way to do this in + // node + if (typeof window !== 'undefined') { + for (const event of events) { + window.addEventListener(event, this[`_on${event}`].bind(this), { + passive: false, + signal: this._removeSignal + }); + } } // Initialize device orientation value diff --git a/src/events/keyboard.js b/src/events/keyboard.js index 11cc05f394..ea795dbe1f 100644 --- a/src/events/keyboard.js +++ b/src/events/keyboard.js @@ -18,11 +18,15 @@ function keyboard(p5, fn, lifecycles) { lifecycles.presetup = function () { const events = ['keydown', 'keyup', 'keypress', 'blur']; - for (const event of events) { - window.addEventListener(event, this[`_on${event}`].bind(this), { - passive: false, - signal: this._removeSignal - }); + // TODO: maybe move to platform-dependent once there is a way to receive + // keyboard events in node + if (typeof window !== 'undefined') { + for (const event of events) { + window.addEventListener(event, this[`_on${event}`].bind(this), { + passive: false, + signal: this._removeSignal + }); + } } }; diff --git a/src/events/pointer.js b/src/events/pointer.js index 3bd1b1c975..10d23620c6 100644 --- a/src/events/pointer.js +++ b/src/events/pointer.js @@ -17,20 +17,24 @@ function pointer(p5, fn, lifecycles) { 'dblclick', 'wheel' ]; - for (const event of events) { - window.addEventListener(event, this[`_on${event}`].bind(this), { - passive: false, - signal: this._removeSignal - }); - } + // TODO: maybe move to platform-dependent once there is a way to receive + // pointer events in node + if (typeof window !== 'undefined') { + for (const event of events) { + window.addEventListener(event, this[`_on${event}`].bind(this), { + passive: false, + signal: this._removeSignal + }); + } - window.addEventListener( - 'blur', - () => { - this.mouseIsPressed = false; - }, - { signal: this._removeSignal } - ); + window.addEventListener( + 'blur', + () => { + this.mouseIsPressed = false; + }, + { signal: this._removeSignal } + ); + } }; /** diff --git a/src/friendly_errors/fes_core.js b/src/friendly_errors/fes_core.js index ef6b94770d..b136527c86 100644 --- a/src/friendly_errors/fes_core.js +++ b/src/friendly_errors/fes_core.js @@ -30,6 +30,7 @@ import { getFriendlyStack } from './stacktrace'; import { FES } from './fes'; +import { handleUncaughtErrors } from '#platform'; function fesCore(p5, fn, lifecycles) { // This is a lazily-defined list of p5 symbols that may be @@ -181,7 +182,7 @@ function fesCore(p5, fn, lifecycles) { // if using instance mode, this function would be called with the current // instance as context const instanceMode = context instanceof p5; - context = instanceMode ? context : window; + context = instanceMode ? context : globalThis; const fnNames = entryPoints; if (context.preload && !p5.isPreloadSupported()) { @@ -372,22 +373,13 @@ function fesCore(p5, fn, lifecycles) { defineMisusedAtTopLevelCode(); } - // Try to get the error object from e - let error; - if (e instanceof Error) { - error = e; - } else if (e instanceof ErrorEvent) { - error = e.error; - } else if (e instanceof PromiseRejectionEvent) { - error = e.reason; - if (!(error instanceof Error)) return; - } + const error = e; if (!error) return; let stacktrace = errorStackParser.parse(error); // process the stacktrace from the browser and simplify it to give // friendlyStack. - let [isInternal, friendlyStack] = processStack(error, stacktrace); + let [isInternal, friendlyStack] = processStack(error, stacktrace, p5); // if this is an internal library error, the type of the error is not relevant, // only the user code that lead to it is. @@ -595,8 +587,7 @@ function fesCore(p5, fn, lifecycles) { lifecycles.presetup = function () { checkForUserDefinedFunctions(); - window.addEventListener('error', fesErrorMonitor, false); - window.addEventListener('unhandledrejection', fesErrorMonitor, false); + handleUncaughtErrors(fesErrorMonitor); }; } diff --git a/src/friendly_errors/param_validator.js b/src/friendly_errors/param_validator.js index 8510831344..7e5cd40d9b 100644 --- a/src/friendly_errors/param_validator.js +++ b/src/friendly_errors/param_validator.js @@ -6,6 +6,7 @@ import * as constants from '../core/constants.js'; import * as z from 'zod/mini'; import dataDoc from '../../docs/parameterData.json'; import { FES } from './fes.js'; +import { isCanvasElement } from '#platform'; import { errorStackParser, processStack, @@ -80,7 +81,6 @@ function validateParams(p5, fn, lifecycles) { const webAPIObjects = [ 'AudioNode', - 'HTMLCanvasElement', 'HTMLElement', 'KeyboardEvent', 'MouseEvent', @@ -100,6 +100,9 @@ function validateParams(p5, fn, lifecycles) { } const webAPISchemas = generateWebAPISchemas(webAPIObjects); + webAPISchemas.HTMLCanvasElement = z.custom(isCanvasElement, { + message: 'Expected a HTMLCanvasElement' + }); // Add web API schemas to the schema map. Object.assign(schemaMap, webAPISchemas); @@ -215,8 +218,8 @@ function validateParams(p5, fn, lifecycles) { ); } // JavaScript classes, e.g. Request - else if (baseType.match(/^[A-Z]/) && baseType in window) { - typeSchema = z.instanceof(window[baseType]); + else if (baseType.match(/^[A-Z]/) && baseType in globalThis) { + typeSchema = z.instanceof(globalThis[baseType]); } // Generate a schema for a single parameter that can be of multiple // types / constants, i.e. `String|Number|Array`. @@ -569,7 +572,8 @@ function validateParams(p5, fn, lifecycles) { } else { const [, stacktrace] = processStack( null, - errorStackParser.parse(Error()).slice(3) + errorStackParser.parse(Error()).slice(3), + p5 ); const locationStr = getFriendlyStack(stacktrace, true); FES.log`${locationStr} ${message}`(); diff --git a/src/friendly_errors/sketch_verifier.js b/src/friendly_errors/sketch_verifier.js index 45a40608cd..c5c86d4804 100644 --- a/src/friendly_errors/sketch_verifier.js +++ b/src/friendly_errors/sketch_verifier.js @@ -2,6 +2,7 @@ import { parse } from 'acorn'; import { simple as walk } from 'acorn-walk'; import * as constants from '../core/constants'; import { FES } from './fes'; +import { getUserScript } from '#platform'; // List of functions to ignore as they either are meant to be re-defined or // generate false positive outputs. @@ -207,10 +208,8 @@ export const verifierUtils = { * @returns {Promise} The user's code as a string. */ getUserCode: async function () { - // TODO: think of a more robust way to get the user's code. Refer to - // https://github.com/processing/p5.js/pull/7293. - const scripts = document.querySelectorAll('script'); - const userCodeScript = scripts[scripts.length - 1]; + const userCodeScript = getUserScript(); + if (!userCodeScript) return ''; const userCode = await verifierUtils.fetchScript(userCodeScript); return userCode; diff --git a/src/friendly_errors/stacktrace.js b/src/friendly_errors/stacktrace.js index 015e429705..4d03a49788 100644 --- a/src/friendly_errors/stacktrace.js +++ b/src/friendly_errors/stacktrace.js @@ -261,13 +261,14 @@ export const errorStackParser = new ErrorStackParser(); * @private * @param {Error} error * @param {Array} stacktrace + * @param p5 The p5 global, which has the log cache * * @returns {Array} An array with two elements, [isInternal, friendlyStack] * isInternal: a boolean value indicating whether the error * happened internally * friendlyStack: the filtered (simplified) stacktrace */ -export const processStack = (error, stacktrace) => { +export const processStack = (error, stacktrace, p5) => { // cannot process a stacktrace that doesn't exist if (!stacktrace) return [false, null]; diff --git a/src/webgl/p5.Texture.js b/src/webgl/p5.Texture.js index 032ffeaff8..242880d4ec 100644 --- a/src/webgl/p5.Texture.js +++ b/src/webgl/p5.Texture.js @@ -72,8 +72,7 @@ class Texture { this.isSrcP5Image = obj instanceof Image; this.isSrcP5Graphics = obj instanceof Graphics; this.isSrcP5Renderer = obj instanceof Renderer; - this.isImageData = - typeof ImageData !== 'undefined' && obj instanceof ImageData; + this.isImageData = Boolean(obj?.width && obj?.height && obj?.data); this.isSrcMediaElement = typeof MediaElement !== 'undefined' && obj instanceof MediaElement; this.isSrcHTMLElement = diff --git a/src/webgpu/p5.RendererWebGPU.js b/src/webgpu/p5.RendererWebGPU.js index 7cf98d8e6c..2a68f49f04 100644 --- a/src/webgpu/p5.RendererWebGPU.js +++ b/src/webgpu/p5.RendererWebGPU.js @@ -3162,6 +3162,18 @@ function rendererWebGPU(p5, fn) { } uploadTextureFromSource({ gpuTexture }, source) { + // Raw pixels, e.g. an ImageData + // TODO check if this fixes #8703 + if (source.data) { + this.uploadTextureFromData( + { gpuTexture }, + source.data, + source.width, + source.height + ); + return; + } + const isVideo = source instanceof HTMLVideoElement; // Chrome throws if a video has no decoded frame yet if (isVideo && source.readyState < 2) return; @@ -3200,6 +3212,18 @@ function rendererWebGPU(p5, fn) { this.flushDraw(); } + // Avoiding p5.Image use here for portability + _getEmptyTexture() { + if (!this._emptyTexture) { + this._emptyTexture = new Texture(this, { + width: 1, + height: 1, + data: new Uint8ClampedArray([255, 255, 255, 255]) + }); + } + return this._emptyTexture; + } + setTextureParams(_texture) {} getSampler(texture) {