/** * Pi.js Type Definitions * Version: pi-2.3 * Author: Andy Stubbs * License: Apache-2.0 */ /** * Commands, screen commands, and settings added by separately loaded plugins. A plugin's * declaration file augments these interfaces with `declare module "pijs-web/lite"`, * so importing the plugin adds its commands to the API. */ export interface PluginCommands {} export interface PluginScreenCommands {} export interface PluginOptions {} declare namespace Pi { /** * Standard JavaScript Error object. * * Standard JavaScript Error object passed to error callbacks (e.g., onError callbacks in loadImage, loadSpritesheet). Contains error information including message and potentially other error details. * * The Error object may contain additional properties depending on the error source. For image loading errors, it may include network-related information. */ interface Error { /** * Error message describing what went wrong. */ message: string; /** * Error type name (e.g., 'Error', 'TypeError', 'NetworkError'). */ name?: string; /** * Error stack trace (if available). */ stack?: string; } /** * Font information object. * * Font information object containing properties of a loaded font. Returned in the array from getAvailableFonts(). */ interface FontInfo { /** * Font identifier/number. */ id: number; /** * Character width in pixels. */ width: number; /** * Character height in pixels. */ height: number; } /** * Individual frame metadata within a spritesheet. * * Frame data object containing position, dimensions, and bounding box information for a single frame in a spritesheet. Part of the frames array in SpritesheetData. */ interface FrameData { /** * Frame index (0-based). */ index: number; /** * X coordinate of frame in spritesheet image. */ x: number; /** * Y coordinate of frame in spritesheet image. */ y: number; /** * Width of the frame in pixels. */ width: number; /** * Height of the frame in pixels. */ height: number; /** * Left edge X coordinate. */ left: number; /** * Top edge Y coordinate. */ top: number; /** * Right edge X coordinate. */ right: number; /** * Bottom edge Y coordinate. */ bottom: number; /** * Screen dimensions/aspect ratio string. */ screen?: string; /** * Foreground color (palette index, color value, etc.). */ color?: any; /** * Background color. */ bgColor?: any; /** * Default color palette array. */ defaultPal?: Array; } /** * Settings object for the set() command. * * Options object used with the set() command to apply multiple settings in a single call. Any command registered as a "setX" command is available as an option with the lowercased name (e.g., setColor => { "color": ... }). */ interface Options extends PluginOptions { /** * Sets the canvas background color. */ bgColor?: any; /** * Sets the current blend mode used for rendering. */ blend?: string; /** * Sets a custom character bitmap in the current font. */ char?: { "charCode": number | string; "data": any[] | string }; /** * Sets the current foreground color used for drawing. */ color?: any; /** * Sets the background color of the screen's container element. */ containerBgColor?: any; /** * Sets the default anchor point for images when drawing on the current screen. */ defaultAnchor?: { "x": number; "y": number }; /** * Sets the default foreground color used by new screens. */ defaultColor?: any; /** * Sets the default font for new screens. */ defaultFont?: number; /** * Sets the default color palette for newly created screens. */ defaultPal?: Array; /** * Sets or clears the shader used to present the screen to the canvas. */ displayShader?: number | null; /** * Updates uniforms on the active display shader. */ displayShaderUniforms?: ShaderUniforms; /** * Sets the font for the current screen. */ font?: number; /** * Configures color noise ranges and optional seed for blending. */ noise?: { "noise"?: number | any[]; "seed"?: number }; /** * Replaces the current palette with a new set of colors. */ pal?: Array; /** * Updates one or more palette colors at specific indices. */ palColors?: { "indices": Array; "colors": Array }; /** * Sets the print cursor position using column and row coordinates. */ pos?: { "col"?: number; "row"?: number }; /** * Sets the print cursor position using pixel coordinates. */ posPx?: { "x"?: number; "y"?: number }; /** * Sets the scale factor for printed text. */ printSize?: { "scaleWidth"?: number; "scaleHeight"?: number; "padX"?: number; "padY"?: number }; /** * Sets the active screen for graphics commands. */ screen?: number | Screen; /** * Enables or disables word breaking for text wrapping. */ wordBreak?: boolean; } /** * Color object representing RGBA color values. * * Color object returned by getPixel(), getColor(), getPalColor(), and other color-related functions. Contains RGBA color components, a unique key, and array representation. */ interface PiColor { /** * Unique 32-bit integer key for the color (packed RGBA format). */ key: number; /** * Red component (0-255). */ r: number; /** * Green component (0-255). */ g: number; /** * Blue component (0-255). */ b: number; /** * Alpha component (0-255). */ a: number; /** * Array representation [r, g, b, a]. */ array: Array; } /** * Plugin API object for extending Pi.js functionality. * * Plugin API object passed to plugin initialization functions. Provides access to Pi.js internals for registering commands, adding screen data, and extending functionality. */ interface PluginAPI { /** * During init, register a new command. */ addCommand: ( name: string, fn: ( ...args: any[] ) => any, isScreen: boolean, parameterNames: string[], isScreenOptional?: boolean ) => void; /** * During init, add persistent data to each screen. */ addScreenDataItem: ( name: string, defaultValue: any ) => void; /** * During init, add a dynamic data getter for screens. */ addScreenDataItemGetter: ( name: string, getterFn: Function ) => void; /** * During init, register a function to run when screens are created. */ addScreenInitFunction: ( initFn: Function ) => void; /** * During init, register a function to run after isRemoved is set, before renderer cleanup; it cancels work without redrawing. */ addScreenPreCleanupFunction: ( cleanupFn: ( screenData: any ) => void ) => void; /** * During init, register a function to run when screens are destroyed. */ addScreenCleanupFunction: ( cleanupFn: Function ) => void; /** * Return the active screen data, or throw if none unless isScreenOptional is true. */ getActiveScreen: ( fnName: string, isScreenOptional?: boolean ) => any; /** * Get data for a specific screen by name. */ getScreenData: ( fnName: string, screenId: string ) => any; /** * Get array of all screen data objects. */ getAllScreensData: () => any[]; /** * Resize an offscreen screen to integer dimensions. */ resizeOffscreenScreen: ( screenData: any, width: number, height: number ) => void; /** * Get the main Pi.js API object. */ getApi: () => Pi.API; /** * Access to utility functions. */ readonly utils: object; /** * Increment resource wait counter (for async operations). */ wait: () => void; /** * Decrement resource wait counter. */ done: () => void; /** * During init, register a clearEvents handler for a specific event type. */ registerClearEvents: ( name: string, handler: Function ) => void; /** * During init, publish one service object for plugins that depend on this plugin. */ provideService: ( service: object ) => void; /** * Return the service of an initialized plugin named in this plugin's dependencies. */ getService: ( pluginName: string ) => any; } /** * Character grid position coordinates. * * Position coordinates in character grid units (column and row). Used for text cursor positioning and character-based operations. The grid size is determined by the current font size and print scale. */ interface Position { /** * Column position (0-indexed). */ col: number; /** * Row position (0-indexed). */ row: number; } /** * Pixel position coordinates. * * Exact pixel coordinates for positioning. Used when precise pixel-level positioning is required, as opposed to character grid coordinates. */ interface PositionPx { /** * X coordinate in pixels. */ x: number; /** * Y coordinate in pixels. */ y: number; } /** * Image source accepted by a sampler2D custom uniform. * * Accepts the same direct image inputs as drawImage, registered names, and screens. */ type ShaderImageInput = string | HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | ImageData | OffscreenCanvas | Screen; /** * Copied lifecycle and diagnostic information for a custom shader. */ interface ShaderInfo { /** * Shader handle id. */ id: number; /** * Full GLSL ES 3.00 fragment source. */ fragmentSource: string; /** * Copied default custom uniform values. */ uniforms: ShaderUniforms; /** * Number of screens that have compiled and cached the shader. */ compiledScreenCount: number; /** * Total queued framebuffer passes using the shader across all screens. */ queuedPassCount: number; /** * Number of screens currently using this shader for display presentation. */ displayScreenCount: number; /** * Selected-screen details when a current screen is available. */ screen?: ShaderScreenInfo; } /** * Flat numeric or boolean data for vector, matrix, and uniform-array values. * * Matrices use WebGL column-major order. */ type ShaderNumericData = number[] | boolean[] | Float32Array | Int32Array | Uint32Array; /** * Custom shader lifecycle details for one screen. */ interface ShaderScreenInfo { /** * Whether this screen has compiled and cached the shader. */ compiled: boolean; /** * Number of queued framebuffer passes using the shader on this screen. */ queuedPassCount: number; /** * Whether this shader is the screen's active display shader. */ displayActive: boolean; /** * Reflected active uniforms, empty until the shader is compiled on this screen. */ uniforms: ShaderUniformInfo[]; } /** * Reflected information about one active GLSL uniform. */ interface ShaderUniformInfo { /** * Uniform name with any trailing array [0] removed. */ name: string; /** * Readable GLSL ES type name, or unknown for an unsupported reflected type. */ type: string; /** * Uniform array length, or 1 for a non-array uniform. */ size: number; /** * Whether Pi.js owns and supplies this built-in uniform. */ reserved: boolean; } /** * Custom shader uniform values keyed by GLSL uniform name. * * Unknown names and reserved Pi.js built-in uniform names are ignored. */ type ShaderUniforms = Record; /** * Value accepted for one reflected custom shader uniform. * * The GLSL declaration determines how the value is interpreted. */ type ShaderUniformValue = number | boolean | ShaderNumericData | ShaderImageInput | ShaderImageInput[]; /** * Width and height dimensions object. * * Size object containing width and height dimensions. Used in resize callbacks and other operations that need dimension information. */ interface Size { /** * Width in pixels. */ width: number; /** * Height in pixels. */ height: number; } /** * Spritesheet metadata including frame information. * * Spritesheet data object containing frame count and detailed frame information. Returned by getSpritesheetData(). */ interface SpritesheetData { /** * Total number of frames in the spritesheet. */ frameCount: number; /** * Array of FrameData objects, one for each frame in the spritesheet. */ frames: Array; } interface Screen extends PluginScreenCommands { /** * Appends new colors to the current palette and returns their indices. * * Adds colors that do not already exist in the palette, returning the indices of the newly added entries. * @param colors Array of colors to add (names, hex, RGB[A]). * @returns Array of indices for colors that were added to the palette. */ addPalColors( params: { "colors": Array } ): Array; addPalColors( colors: Array ): Array; /** * Applies a custom shader to the screen at the current point in draw order. * * Applies a custom fragment shader to the current screen pixels. Pi.js drawing commands write into the logical framebuffer at the screen's resolution. applyShader samples that framebuffer through u_texture, runs your shader over every pixel, and replaces those pixels with the result. Drawing that happens after applyShader appears on top. Call it more than once to stack effects. * * This is part of drawing, not presentation. It changes the actual screen pixels, works on onscreen and offscreen screens, and always processes the full logical framebuffer even inside a view. After drawing, Pi.js presents the logical framebuffer to the canvas. Use setDisplayShader for a presentation effect that does not change logical pixels. For applyShader, u_sourceSize and u_outputSize are both the logical screen size. * * Write the fragment shader with createShader. Pi.js supplies a fullscreen-quad vertex stage, so you only write GLSL ES 3.00 fragment source. A good shader: * * - Starts with "#version 300 es" and a precision qualifier such as precision mediump float * - Declares in vec2 v_texCoord, uniform sampler2D u_texture, and out vec4 fragColor * - Reads the current screen with texture(u_texture, v_texCoord) * - Writes a complete premultiplied color; the shader replaces pixels and does not blend * - Declares built-in uniforms only when needed: u_texture (sampler2D), u_sourceSize (vec2), u_outputSize (vec2), u_time (float seconds), and u_frame (int) * - Keeps RGB between zero and alpha, with zero RGB at zero alpha * * Framebuffers, u_texture, custom sampler2D images, and fragment outputs use premultiplied RGBA: RGB is multiplied by alpha. For opacity, multiply all four channels. For inversion, use vec4(color.a - color.rgb, color.a). Unpremultiply with a zero-alpha guard before straight-color math, then premultiply the result before output. * * v_texCoord uses bottom-left/y-up UVs. Custom sampler2D images match the same orientation as u_texture. Drawing coordinates remain top-left/y-down. Convert UVs to screen pixels with vec2(uv.x, 1.0 - uv.y) * u_sourceSize. * * Per-call uniforms merge over createShader defaults for that invocation only. Built-in names cannot be overridden from JavaScript. Sampler images are captured when applyShader is called. A custom sampler cannot be the same screen the shader is applied to. Known uniform values with an invalid type or component count throw synchronously. Video sources refresh when decoded data is available; first use without a decoded frame throws IMAGE_NOT_READY, otherwise the last valid upload is retained. No video rendering loop is created. * @param shaderHandle Shader handle returned by createShader. * @param uniforms Optional per-call uniform overrides for this invocation. * @returns This function does not return a value. */ applyShader( params: { "shaderHandle": number; "uniforms"?: ShaderUniforms } ): void; applyShader( shaderHandle: number, uniforms?: ShaderUniforms ): void; /** * Draws an arc on the screen. * * This function renders a circular arc segment to the active canvas. * * The angles are measured in degrees, clockwise from the positive x-axis. Equal start and end angles draw nothing. A difference of 360 degrees or more draws one complete outline matching circle(). Shorter differences wrap clockwise from the starting angle to the ending angle. * * The angles must be finite numbers; any other value throws a TypeError with code INVALID_PARAMETER. * @param x The x coordinate of the center point of the arc's circle. * @param y The y coordinate of the center point of the arc's circle. * @param radius The radius of the arc's circle. * @param angle1 The starting angle in degrees. * @param angle2 The ending angle in degrees. * @returns This function does not return a value. */ arc( params: { "x": number; "y": number; "radius": number; "angle1": number; "angle2": number } ): void; arc( x: number, y: number, radius: number, angle1: number, angle2: number ): void; /** * Draws a bezier curve on the screen. * * This function renders a cubic Bezier curve to the active canvas. * * A Bezier curve is defined by four control points: two endpoints and two control points that influence the curve's shape. * @param x1 The x coordinate of the first control point (starting point). * @param y1 The y coordinate of the first control point (starting point). * @param x2 The x coordinate of the second control point. * @param y2 The y coordinate of the second control point. * @param x3 The x coordinate of the third control point. * @param y3 The y coordinate of the third control point. * @param x4 The x coordinate of the fourth control point (ending point). * @param y4 The y coordinate of the fourth control point (ending point). * @returns This function does not return a value. */ bezier( params: { "x1": number; "y1": number; "x2": number; "y2": number; "x3": number; "y3": number; "x4": number; "y4": number } ): void; bezier( x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, x4: number, y4: number ): void; /** * Blits an image element directly onto the screen using replace batch mode. * * Blits an Image or Canvas element directly onto the screen. Unlike drawImage, this function accepts an image element directly (not a name) and uses replace batch mode for faster rendering. The angle parameter is in radians (not degrees). * * Note: The official recommended method for drawing images is the drawImage command as it has more safety with parameter validation and is still pretty fast. So unless you really need the extra performance boost or you do not want to do any blending with the screen then you should stick with the drawImage command. * @param img Image or Canvas element to blit (not a name string). * @param x X (horizontal) coordinate (default 0). * @param y Y (vertical) coordinate (default 0). * @param color Optional color multiplier. Can be a palette index or color value (string, array, object, number). Defaults to white. * @param anchorX X (horizontal) rotation point (0.0-1.0). Defaults to screen's default anchor. * @param anchorY Y (vertical) rotation point (0.0-1.0). Defaults to screen's default anchor. * @param scaleX Scale factor X (default 1). * @param scaleY Scale factor Y (default 1). * @param angleRad Rotation angle in radians (default 0). * @returns This function does not return a value. */ blitImage( params: { "img": HTMLImageElement | HTMLCanvasElement; "x"?: number; "y"?: number; "color"?: any; "anchorX"?: number; "anchorY"?: number; "scaleX"?: number; "scaleY"?: number; "angleRad"?: number } ): void; blitImage( img: HTMLImageElement | HTMLCanvasElement, x?: number, y?: number, color?: any, anchorX?: number, anchorY?: number, scaleX?: number, scaleY?: number, angleRad?: number ): void; /** * Blits a frame from a spritesheet onto the screen using replace batch mode. * * Blits a specific frame from a previously loaded spritesheet. Unlike drawSprite, this function uses replace batch mode for faster rendering. The angle parameter is in radians (not degrees). * * Note: The official recommended method for drawing sprites is the drawSprite command as it has more safety with parameter validation and is still pretty fast. So unless you really need the extra performance boost or you do not want to do any blending with the screen then you should stick with the drawSprite command. * @param name Spritesheet name. * @param frame Frame index to draw (default 0). * @param x X (horizontal) coordinate (default 0). * @param y Y (vertical) coordinate (default 0). * @param color Optional color multiplier. Can be a palette index or color value (string, array, object, number). Defaults to white. * @param anchorX X (horizontal) rotation point (0.0-1.0). Defaults to screen's default anchor. * @param anchorY Y (vertical) rotation point (0.0-1.0). Defaults to screen's default anchor. * @param scaleX Scale factor X (default 1). * @param scaleY Scale factor Y (default 1). * @param angleRad Rotation angle in radians (default 0). * @returns This function does not return a value. */ blitSprite( params: { "name": string; "frame"?: number; "x"?: number; "y"?: number; "color"?: any; "anchorX"?: number; "anchorY"?: number; "scaleX"?: number; "scaleY"?: number; "angleRad"?: number } ): void; blitSprite( name: string, frame?: number, x?: number, y?: number, color?: any, anchorX?: number, anchorY?: number, scaleX?: number, scaleY?: number, angleRad?: number ): void; /** * Calculates the pixel width of a text message. * * Calculates how many pixels wide a text message will be when printed with the current font and print scale settings. * @param msg Text message to calculate width for. Defaults to empty string if not provided. * @returns Width of the text in pixels. */ calcWidth( params: { "msg"?: string } ): number; calcWidth( msg?: string ): number; /** * Returns the HTMLCanvasElement for the current screen. * * Gets the underlying HTMLCanvasElement DOM element for the active screen. This can be used for direct canvas manipulation or integration with other libraries. * * Note: This is for applying CSS styles to the canvas or moving the canvas in the DOM. You cannot call getContext( "2d" ) on the returned canvas element as it already has a WebGL context. If you want to use a 2d canvas context on a screen you can create a new DOM canvas and draw it as an image on the screen. * @returns The canvas DOM element for the current screen. */ canvas(): HTMLCanvasElement; /** * Draws a circle on the screen. * * This function renders a circle to the active canvas. * * The circle is drawn with a border using the current foreground color. If a fill color is provided, the circle will be filled with that color. * @param x The x coordinate of the center of the circle. * @param y The y coordinate of the center of the circle. * @param radius The radius of the circle. * @param fillColor The fill color for the circle. Can be a palette index or color value (string, array, object, number). * @returns This function does not return a value. */ circle( params: { "x": number; "y": number; "radius": number; "fillColor"?: any } ): void; circle( x: number, y: number, radius: number, fillColor?: any ): void; /** * Clears events from all plugins or a specific plugin event type. * * Clears queued/registered events. If type is provided, clears only that event type; otherwise clears events for all registered types. * * $.clearEvents() clears per-screen handlers on every screen. A screen's clearEvents(), such as screen.clearEvents(), clears them on that screen only. * * The pointer plugin registers "mouse", "touch", "press", "click", and "wheel", each clearing only the handlers of its command: onMouse, onTouch, onPress, onClick, and onWheel. These handlers are per-screen. The gamepad plugin registers "gamepad", which removes every onGamepad() callback, whichever form is called. The keyboard plugin registers "keyboard", which removes every onKey() handler, whichever form is called; $.clearEvents() also cancels every input() prompt, and a screen's clearEvents() cancels only that screen's prompt. Clearing handlers does not stop tracking or polling. * @param type Optional type to clear (e.g., "keyboard", "mouse", "click", "gamepad"). * @returns This function does not return a value. */ clearEvents( params: { "type"?: string } ): void; clearEvents( type?: string ): void; /** * Clears the screen or a rectangular region. * * This function clears the entire screen or a rectangular region of the active canvas. * * When x, y, width, and height are provided, only that region is cleared. Otherwise the full screen is cleared and the print cursor is reset to position (0, 0). * @param x The horizontal coordinate of the region to clear. * @param y The vertical coordinate of the region to clear. * @param width The width of the region to clear. * @param height The height of the region to clear. * @returns This function does not return a value. */ cls( params: { "x"?: number; "y"?: number; "width"?: number; "height"?: number } ): void; cls( x?: number, y?: number, width?: number, height?: number ): void; /** * Creates an image from a region of the current screen. * * Copies a rectangular region from the screen into a new canvas-backed image and stores it by name. * @param name Optional unique name for the image. Auto-generated if omitted. * @param x1 Left coordinate (defaults to 0). * @param y1 Top coordinate (defaults to 0). * @param x2 Right coordinate (defaults to screen width - 1). * @param y2 Bottom coordinate (defaults to screen height - 1). * @returns The created image name. */ createImageFromScreen( params: { "name"?: string; "x1"?: number; "y1"?: number; "x2"?: number; "y2"?: number } ): string; createImageFromScreen( name?: string, x1?: number, y1?: number, x2?: number, y2?: number ): string; /** * Draws lines on the screen defined by a string. * * Draws using a BASIC-style, case-insensitive draw string composed of commands. * * Supported commands: * * - **"B":** Before a line move, hides the line move (blind move). * - **"Cn"**: Set the color attribute to palette index n. * - **"C#RRGGBB"**: Set the color using a hex value (e.g., C#FF00FF). * - **"Mn, n"**: Move to absolute coordinate (x, y) without drawing. * - **"N"**: Return to the starting position after the next drawn segment. * - **"Pn[, n]"**: Paint enclosed area from the cursor using color index; optional boundary color index. * - **"Dn"**: Draw a vertical line DOWN n pixels. * - **"En"**: Draw a diagonal line UP and RIGHT n pixels each direction (slash /). * - **"Fn"**: Draw a diagonal line DOWN and RIGHT n pixels each direction. * - **"Gn"**: Draw a diagonal line DOWN and LEFT n pixels each direction (slash /). * - **"Hn"**: Draw a diagonal line UP and LEFT n pixels each direction. * - **"Ln"**: Draw a horizontal line LEFT n pixels. * - **"Rn"**: Draw a horizontal line RIGHT n pixels. * - **"Un"**: Draw a vertical line UP n pixels. * - **"Sn"**: Set scale factor; n in [1..255], actual scale is n/4 (default 1). * - **"An"**: Set angle by quadrant; n in {0,1,2,3} maps to 0°, 90°, 180°, 270°. * - **"TAn"**: Turn Angle; set any angle n from -360 to 360 degrees. * - **"ARCn, n, n"**: Draw an arc with radius, start degrees, end degrees using the cursor as center. * @param drawString Case insensitive string containing draw commands. * @returns This function does not return a value. */ draw( params: { "drawString": string } ): void; draw( drawString: string ): void; /** * Draws an image onto the screen. * * Draws an image (by name or element) using optional color, anchor, scale, and rotation parameters. * @param image Image name (string), url (string), screen object, or Image/Canvas element. * @param x X (horizontal) coordinate. * @param y Y (vertical) coordinate. * @param color Optional color multiplier. Can be a palette index or color value (string, array, object, number). * @param anchorX X (horizontal) rotation point (0.0-1.0). * @param anchorY Y (vertical) rotation point (0.0-1.0). * @param scaleX Scale factor X (default 1). * @param scaleY Scale factor Y (default 1). * @param angle Rotation angle in degrees (default 0). * @returns This function does not return a value. */ drawImage( params: { "image": any; "x": number; "y": number; "color"?: any; "anchorX"?: number; "anchorY"?: number; "scaleX"?: number; "scaleY"?: number; "angle"?: number } ): void; drawImage( image: any, x: number, y: number, color?: any, anchorX?: number, anchorY?: number, scaleX?: number, scaleY?: number, angle?: number ): void; /** * Draws a frame from a spritesheet onto the screen. * * Draws a specific frame from a previously loaded spritesheet with optional color, anchor, scale, and rotation parameters. * @param name Spritesheet name. * @param frame Frame index to draw (default 0). * @param x X (horizontal) coordinate. * @param y Y (vertical) coordinate. * @param color Optional color multiplier. Can be a palette index or color value (string, array, object, number). * @param anchorX Anchor X (0.0-1.0). Defaults to screen's default anchor. * @param anchorY Anchor Y (0.0-1.0). Defaults to screen's default anchor. * @param scaleX Scale factor X (default 1). * @param scaleY Scale factor Y (default 1). * @param angle Rotation angle in degrees (default 0). * @returns This function does not return a value. */ drawSprite( params: { "name": string; "frame"?: number; "x": number; "y": number; "color"?: any; "anchorX"?: number; "anchorY"?: number; "scaleX"?: number; "scaleY"?: number; "angle"?: number } ): void; drawSprite( name: string, frame: number | undefined, x: number, y: number, color?: any, anchorX?: number, anchorY?: number, scaleX?: number, scaleY?: number, angle?: number ): void; /** * Draws an ellipse on the screen. * * This function renders an ellipse to the active canvas. * * The ellipse is drawn with a border using the current foreground color. If a fill color is provided, the ellipse will be filled with that color. * @param x The x coordinate of the center of the ellipse. * @param y The y coordinate of the center of the ellipse. * @param radiusX The horizontal radius of the ellipse. * @param radiusY The vertical radius of the ellipse. * @param fillColor The fill color for the ellipse. Can be a palette index or color value (string, array, object, number). * @returns This function does not return a value. */ ellipse( params: { "x": number; "y": number; "radiusX": number; "radiusY": number; "fillColor"?: any } ): void; ellipse( x: number, y: number, radiusX: number, radiusY: number, fillColor?: any ): void; /** * Applies a filter function to a rectangular region of the screen. * * Queues a filter to run at end of frame. The filter callback receives a mutable pixel buffer (RGBA as Uint8ClampedArray) and x, y coordinates; return truthy to apply the modified pixel. If true is not returned in the callback the pixel will be filtered out and be set to black/transparent, even if it is not modified. * * The region and view coordinates are captured when called. Pixel data is read when the queued filter runs. Removing the screen cancels queued filtering without invoking the callback. If a callback removes its own screen, filtering stops immediately, with no further callbacks or pixel upload. This command returns no promise; callback exceptions retain their normal behavior. * * Filtering runs on the CPU rather than the GPU, so large areas may not be suitable for use in an animationFrame. * @param filter Callback (color, x, y) => truthy to accept modified pixel color, falsy to skip. * @param x1 Left coordinate (default 0). * @param y1 Top coordinate (default 0). * @param x2 Right coordinate (default screen width - 1). * @param y2 Bottom coordinate (default screen height - 1). * @returns This function does not return a value. */ filterImg( params: { "filter": ( color: PiColor, x: number, y: number ) => boolean; "x1"?: number; "y1"?: number; "x2"?: number; "y2"?: number } ): void; filterImg( filter: ( color: PiColor, x: number, y: number ) => boolean, x1?: number, y1?: number, x2?: number, y2?: number ): void; /** * Reads a region of pixels as indices (default) or color values. * * Returns a 2D array [height][width] for the region. By default returns palette indices. Set asIndex=false to return color value objects. Tolerance controls color-to-index matching. If a color that doesn't match is not found the index 0 for black/transparent will be set. * * Note: if asIndex is set to false then the 2D array cannot be used with the put command. * @param x Left coordinate. * @param y Top coordinate. * @param width Region width. * @param height Region height. * @param tolerance Color matching tolerance [0.0-1.0] for index conversion (default 1). * @param asIndex If false (default true), return color value objects instead of indices. * @returns 2D array [height][width] of palette indices (default) or color values. */ get( params: { "x": number; "y": number; "width": number; "height": number; "tolerance"?: number; "asIndex"?: boolean } ): Array>; get( x: number, y: number, width: number, height: number, tolerance?: number, asIndex?: boolean ): Array>; /** * Asynchronously reads a region of pixels as indices (default) or color values. * * Returns a Promise resolving to a 2D array [height][width]. By default resolves to palette indices. Set asIndex=false to resolve to color value objects. Tolerance controls color-to-index matching. * * The region uses the view captured when called; pixel data is read in a deferred microtask. If the screen is removed before deferred processing completes, the promise rejects with an Error whose code is "SCREEN_REMOVED". Other read failures reject with the original error. Empty or out-of-bounds results completed immediately are unaffected by later screen removal. Invalid arguments still throw synchronously. * * Note: if asIndex is set to false then the 2D array cannot be used with the put command. * @param x Left coordinate. * @param y Top coordinate. * @param width Region width. * @param height Region height. * @param tolerance Color matching tolerance [0.0-1.0] for index conversion (default 1). * @param asIndex If false, resolve to color value objects instead of indices. * @returns Resolves to a 2D array [height][width] of indices (default) or color values. Rejects with code SCREEN_REMOVED if the screen is removed before deferred processing completes, or with the original read error. */ getAsync( params: { "x": number; "y": number; "width": number; "height": number; "tolerance"?: number; "asIndex"?: boolean } ): Promise>>; getAsync( x: number, y: number, width: number, height: number, tolerance?: number, asIndex?: boolean ): Promise>>; /** * Gets the current foreground color. * * Returns the current drawing color. If asIndex is true, returns the palette index; otherwise returns the color value object. * @param asIndex If true returns the palette index, otherwise returns a color value object. * @returns Palette index if asIndex is true; otherwise a color value object. */ getColor( params: { "asIndex"?: boolean } ): number | PiColor; getColor( asIndex?: boolean ): number | PiColor; /** * Returns the number of character columns that fit on the screen. * * Gets the maximum number of character columns that can fit horizontally on the screen based on the current font size and print scale. * @returns Number of columns that fit on the screen. */ getCols(): number; /** * Returns the current color palette as an array. * * Gets the active screen's color palette. By default, index 0 (transparent black) is excluded. Note: Color indices may not match exactly because index 0 is strictly reserved for transparent black. * @param include0 If true include palette index 0 (transparent black). * @returns Array of color value objects representing the current screen palette. */ getPal( params: { "include0"?: boolean } ): Array; getPal( include0?: boolean ): Array; /** * Returns the color value object for a palette index. * * Returns the color value object at a numeric integer palette index. Index 0 is transparent black. Returns null for nonnumeric indices, non-finite numbers, fractions, and indices outside the palette. * @param index Finite integer from 0 through the last palette entry. * @returns Color value object if the index is valid; otherwise null. */ getPalColor( params: { "index": number } ): PiColor | null; getPalColor( index: number ): PiColor | null; /** * Finds the palette index for a color with optional tolerance. * * Finds the best-matching palette index for a given color. Tolerance filters how close the match must be: 0 = exact match only, 1 = any color. The closest color that fits in the tolerance range will be returned. * @param color Palette index or color value (string, array, object, number). * @param tolerance Number between 0 and 1 indicating acceptable color difference. * @returns Palette index if a match is found; otherwise null. */ getPalIndex( params: { "color": any; "tolerance"?: number } ): number | null; getPalIndex( color: any, tolerance?: number ): number | null; /** * Reads the color of a single pixel. * * Returns the color at (x, y). If asIndex is true, returns the palette index; otherwise returns a color value object. * @param x X (horizontal) coordinate. * @param y Y (vertical) coordinate. * @param asIndex If true, return palette index instead of color value. * @returns Palette index if asIndex is true; otherwise a color value object. */ getPixel( params: { "x": number; "y": number; "asIndex"?: boolean } ): number | PiColor; getPixel( x: number, y: number, asIndex?: boolean ): number | PiColor; /** * Asynchronously reads the color of a single pixel. * * Reads the color at (x, y) asynchronously. If asIndex is true, resolves to the palette index; otherwise resolves to a color value object. * * Coordinates use the view captured when called; pixel data is read in a deferred microtask. If the screen is removed before deferred processing completes, the promise rejects with an Error whose code is "SCREEN_REMOVED". Other read failures reject with the original error. An out-of-bounds result completed immediately is unaffected by later screen removal. Invalid arguments still throw synchronously. * @param x X (horizontal) coordinate. * @param y Y (vertical) coordinate. * @param asIndex If true, resolve to palette index instead of color value. * @returns Resolves to a palette index or color value object. Rejects with code SCREEN_REMOVED if the screen is removed before deferred processing completes, or with the original read error. */ getPixelAsync( params: { "x": number; "y": number; "asIndex"?: boolean } ): Promise; getPixelAsync( x: number, y: number, asIndex?: boolean ): Promise; /** * Gets the current print cursor position as column and row. * * Returns the current print cursor position as character grid coordinates (column and row). The grid size is determined by the current font size and print scale. * @returns Object with col and row properties (0-indexed). */ getPos(): Position; /** * Gets the current print cursor position in pixels. * * Returns the current print cursor position as exact pixel coordinates. * @returns Object with x and y properties in pixels. */ getPosPx(): PositionPx; /** * Returns the number of character rows that fit on the screen. * * Gets the maximum number of character rows that can fit vertically on the screen based on the current font size and print scale. * @returns Number of rows that fit on the screen. */ getRows(): number; /** * Returns lifecycle and reflection diagnostics for a custom shader. * * Returns a copied snapshot containing the shader source, default uniforms, and aggregate counts for compiled screens, queued passes, and active display screens. When a current screen is available, the result also describes that screen's compilation state, queued passes, display use, and reflected uniforms. * * This function never compiles the shader or allocates GPU resources. An unused shader reports an uncompiled screen with an empty reflected-uniform list. Unknown handles throw INVALID_SHADER_HANDLE synchronously. * @param shaderHandle Shader handle returned by createShader. * @returns Copied shader lifecycle and diagnostic information. */ getShaderInfo( params: { "shaderHandle": number } ): ShaderInfo; getShaderInfo( shaderHandle: number ): ShaderInfo; /** * Returns frame metadata for a spritesheet. * * Gets spritesheet data including frame count and per-frame bounding boxes. * @param name Spritesheet name. * @returns Object with frameCount and frames array (index, x, y, width, height, left, top, right, bottom). */ getSpritesheetData( params: { "name": string } ): SpritesheetData; getSpritesheetData( name: string ): SpritesheetData; /** * Returns the screen or active view height in pixels. * * Gets the internal height of the active screen's canvas. This is the logical height used for drawing operations, which may differ from the CSS display size. * * If there is an active view using pushView then it will return the height of the local viewport area and not the screen height. * @returns Screen or local view height in pixels. */ height(): number; /** * Draws a line on the screen. * * This function renders a line segment to the active canvas. * * The line is drawn from the first point to the second point using the current foreground color. * @param x1 The x coordinate of the starting point of the line. * @param y1 The y coordinate of the starting point of the line. * @param x2 The x coordinate of the ending point of the line. * @param y2 The y coordinate of the ending point of the line. * @returns This function does not return a value. */ line( params: { "x1": number; "y1": number; "x2": number; "y2": number } ): void; line( x1: number, y1: number, x2: number, y2: number ): void; /** * Flood fills an area with a color, with optional tolerance or boundary color. * * Performs a flood fill starting at (x, y). * * Modes: * - Tolerance fill: Fills pixels similar to the start pixel. Tolerance 0 = exact match; 1 = any color. * - Boundary fill: If boundaryColor is provided, fills until pixels similar to the boundary color. * * Notes: * - Coordinates must be within the screen; out-of-bounds start points are ignored. * - Color inputs accept palette indices or color values (name, hex, RGB[A] array, or color object). * @param x X (horizontal) coordinate to start filling. * @param y Y (vertical) coordinate to start filling. * @param fillColor Fill color. Palette index or color value (string, array, object, number). * @param tolerance Color matching tolerance [0.0-1.0]. 0 = exact match; 1 = any color. * @param boundaryColor Optional boundary color (palette index or color value). Enables boundary fill mode. * @returns This function does not return a value. */ paint( params: { "x": number; "y": number; "fillColor": any; "tolerance"?: number; "boundaryColor"?: any } ): void; paint( x: number, y: number, fillColor: any, tolerance?: number, boundaryColor?: any ): void; /** * Pops the current child view and restores the parent. * * Removes the top view from the stack and restores the parent print cursor. Popping the last view returns to implicit full screen. Calling popView() when the stack is empty throws VIEW_STACK_EMPTY. * * A view defines a local drawing area with its own origin, width, height, and clipping region. Graphics and text commands use coordinates relative to the current view and cannot draw outside its visible clipped area. * @returns This function does not return a value. */ popView(): void; /** * Prints text to the screen using the current font and advances the cursor. * * Prints text to the screen at the current cursor position using the active bitmap font. The text cursor automatically advances after printing. Supports automatic word wrapping, text centering, and vertical scrolling when the cursor reaches the bottom of the screen. * * Newlines in the message will split the text into multiple lines. Tabs are converted to spaces. * @param msg Text message to print. If omitted, prints an empty line. * @param isInline If true, cursor stays on the same line after printing instead of advancing to next line. * @param isCentered If true, centers the text horizontally on the screen. * @returns This function does not return a value. */ print( params: { "msg"?: string; "isInline"?: boolean; "isCentered"?: boolean } ): void; print( msg?: string, isInline?: boolean, isCentered?: boolean ): void; /** * Sets a pixel on the screen to the current foreground color. * * This function sets a single pixel on the active canvas to the current foreground color. * * After drawing, the cursor position is updated to the pixel coordinates. * @param x The x coordinate of the pixel to set. * @param y The y coordinate of the pixel to set. * @returns This function does not return a value. */ pset( params: { "x": number; "y": number } ): void; pset( x: number, y: number ): void; /** * Pushes a child view relative to the current view. * * Creates a new view relative to the current view. The parent print cursor is saved and the new view starts with its cursor at (0, 0). If the requested view extends outside its parent, only the overlapping area is visible. * * A view defines a local drawing area with its own origin, width, height, and clipping region. Graphics and text commands use coordinates relative to the current view and cannot draw outside its visible clipped area. * * Use popView() to restore the parent view and cursor. Child clips stay inside the parent. Resize recomputes origins and clips from the requested local rects, so previously clipped areas can become visible again when the screen grows. * @param x Left edge of the child view in current local coordinates. * @param y Top edge of the child view in current local coordinates. * @param width Requested local width in pixels. Must be 0 or greater. * @param height Requested local height in pixels. Must be 0 or greater. * @returns This function does not return a value. */ pushView( params: { "x": number; "y": number; "width": number; "height": number } ): void; pushView( x: number, y: number, width: number, height: number ): void; /** * Writes a 2D array of palette indices to the screen starting at (x, y). * * Draws pixels from a 2D array of palette indices. The array is indexed as [row][col] with row = y, col = x. Index 0 is transparent and is skipped unless include0 is true. * * You can call this using positional parameters or an object literal: * * - Positional: $.put( data, x, y, include0 ) * - Object: $.put( { "data": data, "x": x, "y": y, "include0": true } ) * * Behavior: * - Pixels are clipped to screen bounds. * - Negative x/y start positions are supported; data is clipped accordingly. * - If no pixels fall within the screen after clipping, nothing is drawn. * - Data should contain palette indices (typically from $.get with asIndex=true). * @param data 2D array [height][width] of palette indices (0..pal.length-1). * @param x X (horizontal) destination coordinate. * @param y Y (vertical) destination coordinate. * @param include0 If true, draw index 0 (transparent) pixels; otherwise skip them. * @returns This function does not return a value. */ put( params: { "data": Array>; "x": number; "y": number; "include0"?: boolean } ): void; put( data: Array>, x: number, y: number, include0?: boolean ): void; /** * Draws a rectangle on the screen. * * This function renders a rectangle to the active canvas. * * The rectangle is drawn with a border using the current foreground color. If a fill color is provided, the rectangle will be filled with that color. * @param x The x coordinate of the upper left corner of the rectangle. * @param y The y coordinate of the upper left corner of the rectangle. * @param width The width of the rectangle. * @param height The height of the rectangle. * @param fillColor The fill color for the rectangle. Can be a palette index or color value (string, array, object, number). * @returns This function does not return a value. */ rect( params: { "x": number; "y": number; "width": number; "height": number; "fillColor"?: any } ): void; rect( x: number, y: number, width: number, height: number, fillColor?: any ): void; /** * Removes this screen and cleans up all associated resources. * @returns This function does not return a value. */ removeScreen(): void; /** * Clears the view stack and resets to full screen. * * Clears the entire view stack and restores implicit full-screen origin and clip. The print cursor is set to (0, 0). Safe to call when the stack is already empty. * * resetView() does not restore saved nested cursors. Use popView() when you need to restore a parent cursor. Changing the view flushes pending batches into the framebuffer. It does not clear the screen. * @returns This function does not return a value. */ resetView(): void; /** * Converts a screen point to local view coordinates. * * Converts a point from screen / FBO coordinates to the active view's local coordinates using the logical view origin. Input stays screen-relative; call this to map mouse or other screen positions into the current view. * @param x Screen / FBO x coordinate. * @param y Screen / FBO y coordinate. * @returns Local view position { x, y }. */ screenToView( params: { "x": number; "y": number } ): PositionPx; screenToView( x: number, y: number ): PositionPx; /** * Applies multiple settings in a single call using an options object. * * Sets one or more global or screen-scoped settings. Any command registered as a "setX" command is available as an option with the lowercased name (e.g., setColor => { "color": ... }), including the settings of loaded plugins. * * Behavior: * - May be called before or after a screen exists; screen-scoped settings are applied to the active screen. A "screen" option makes its screen active for the settings after it. * - Settings routed to non-screen commands are applied globally. * - Options set to null are skipped. * - Every option name is checked before any setting is applied. A name that is not a setting, including a setting of a plugin that is not loaded, throws a RangeError with code INVALID_OPTION, and options that are not an object throw a TypeError with code INVALID_OPTIONS. A screen setting with no active screen throws NO_ACTIVE_SCREEN. * @param options Object whose keys map to available settings (e.g., { "color": 2, "font": 1 }). * @returns This function does not return a value. */ set( params: { "options": Options } ): void; set( options: Options ): void; /** * Sets the canvas background color. * * Sets the background color of the canvas element. Transparent pixels will show this background color. * @param color Palette index or color value (string, array, object, number). * @returns This function does not return a value. */ setBgColor( params: { "color": any } ): void; setBgColor( color: any ): void; /** * Sets the current blend mode used for rendering. * * Sets how new pixels are blended with existing pixels during rendering. * * Supported blend modes: * - "replace": New pixels overwrite existing pixels. * - "alpha": New pixels are alpha composited with existing pixels. * @param blend Blend mode to use. One of: "replace", "alpha". * @returns This function does not return a value. */ setBlend( params: { "blend": string } ): void; setBlend( blend: string ): void; /** * Sets a custom character bitmap in the current font. * * Modifies a character in the current screen's font atlas by replacing its bitmap data. The character must exist in the font's character set. The data can be provided as a 2D array of 0/1 values or as a hex-encoded string. * * The font is shared, so the change applies on every screen that uses it, from the next time the character is printed; text printed before the change keeps the old glyph. The edit is made to the font's own copy of its image, so the image or canvas it was loaded from is not modified, and the change survives a lost and restored WebGL context. * @param charCode Character code (number) or single-character string to modify. * @param data Character bitmap as 2D array [[row...], ...] where 1=on, 0=off, or hex-encoded string. * @returns This function does not return a value. */ setChar( params: { "charCode": number | string; "data": any[] | string } ): void; setChar( charCode: number | string, data: any[] | string ): void; /** * Sets the current foreground color used for drawing. * * Sets the active foreground color from a palette index or a supported color value. Color values are used directly, including colors outside the palette. Numeric indices must be finite integers from 0 through the last palette entry; index 0 is transparent black. * @param color Numeric integer palette index, CSS/hex string, RGB/RGBA array, or color object. * @returns This function does not return a value. */ setColor( params: { "color": any } ): void; setColor( color: any ): void; /** * Sets the background color of the screen's container element. * * Sets the CSS background color of the container element that holds the canvas. * @param color Palette index or color value (string, array, object, number). * @returns This function does not return a value. */ setContainerBgColor( params: { "color": any } ): void; setContainerBgColor( color: any ): void; /** * Sets the default anchor point for images when drawing on the current screen. * * Sets the default anchor point for all image and sprite drawing operations on this screen. The anchor point defines the relative starting position to draw the image, based a percentage of the image size using the x/y coordinates as a starting point. * * **Common anchor values:** * - `(0.0, 0.0)` - Top-left corner (default). The x/y position refers to the upper-left corner of the image. * - `(0.5, 0.5)` - Center of the image. The x/y position refers to the center point. Useful for rotating images around their center or positioning sprites by their center point. * - `(1.0, 1.0)` - Bottom-right corner. The x/y position refers to the lower-right corner of the image. * - `(0.5, 0.0)` - Top-center. Useful for UI elements that should align at their top edge. * - `(0.5, 1.0)` - Bottom-center. Useful for characters or objects that stand on a surface. * * The anchor affects all image drawing commands (`drawImage`, `drawSprite`, `blitImage`, `blitSprite`) unless they explicitly specify their own anchor point. This setting persists for the current screen until changed. * @param x Anchor X in range [0.0-1.0]. * @param y Anchor Y in range [0.0-1.0]. * @returns This function does not return a value. */ setDefaultAnchor( params: { "x": number; "y": number } ): void; setDefaultAnchor( x: number, y: number ): void; /** * Sets or clears the shader used to present the screen to the canvas. * * Sets the shader used when Pi.js presents the logical framebuffer to the canvas. Drawing commands write into the logical framebuffer at the screen's resolution. applyShader changes those pixels. setDisplayShader runs later, at presentation, and does not change logical pixels. Typical uses include custom upscaling, CRT effects, and color grading. * * Write the fragment shader with createShader. Pi.js supplies a fullscreen-quad vertex stage. u_texture is the logical framebuffer. u_sourceSize is the logical screen size. u_outputSize is the canvas backing size, which can be larger than the logical screen while a display shader is active. A good display shader: * * - Starts with "#version 300 es" and a precision qualifier such as precision mediump float * - Declares in vec2 v_texCoord, uniform sampler2D u_texture, and out vec4 fragColor * - Reads the logical framebuffer with texture(u_texture, v_texCoord) * - Writes a complete premultiplied color to fragColor * - Uses u_sourceSize and u_outputSize when scaling or sampling in pixel units * - Keeps RGB between zero and alpha, with zero RGB at zero alpha * * Passing **shaderHandle** null restores the default presentation and logical canvas backing size. While a custom display shader is active, canvas.width and canvas.height follow the CSS presentation size (clamped). CSS style size remains for layout. * * Display shaders do not run on offscreen screens, though the setting may still be stored. This call replaces the active display shader and resets persistent uniform overrides to the **uniforms** supplied here, or to none. * * Sampler images stay bound and refresh dynamic canvas or screen content on each presentation. A shader cannot sample its own destination screen. Built-in names cannot be overridden from JavaScript. Known uniform values with an invalid type or component count throw synchronously. * * Framebuffers, u_texture, custom sampler2D images, and fragment outputs use premultiplied RGBA: RGB is multiplied by alpha. For opacity, multiply all four channels. For inversion, use vec4(color.a - color.rgb, color.a). Unpremultiply with a zero-alpha guard before straight-color math, then premultiply the result before output. * * v_texCoord uses bottom-left/y-up UVs. Custom sampler2D images match the same orientation as u_texture. Drawing coordinates remain top-left/y-down. Convert UVs to screen pixels with vec2(uv.x, 1.0 - uv.y) * u_sourceSize. Video sources refresh when decoded data is available; first use without a decoded frame throws IMAGE_NOT_READY, otherwise the last valid upload is retained. No video rendering loop is created. * @param shaderHandle Shader handle from createShader, or null to restore the default display path. * @param uniforms Optional initial display uniform overrides. Replaces prior overrides. * @returns This function does not return a value. */ setDisplayShader( params: { "shaderHandle": number | null; "uniforms"?: ShaderUniforms } ): void; setDisplayShader( shaderHandle: number | null, uniforms?: ShaderUniforms ): void; /** * Updates uniforms on the active display shader. * * Updates uniforms on the active display shader without replacing the shader. createShader defaults are applied first; values set here override them and stay until you change them again or call setDisplayShader. * * If an onscreen display shader is active and the canvas can be shown, the current logical framebuffer is presented with the new uniforms. This does not change canvas or logical screen size. Hidden, detached, and offscreen screens store the new uniforms but do not present; the next valid presentation uses them. * * **uniforms** is an object of uniform names to values. Known values with an invalid type or component count throw synchronously before the stored uniforms change. Built-in names cannot be overridden from JavaScript. Sampler images stay bound and refresh dynamic canvas or screen content on each presentation. * * Display shaders sample the logical framebuffer through u_texture and do not change logical pixels. Use the same premultiplied alpha and UV rules as createShader. Video sources refresh when decoded data is available; first use without a decoded frame throws IMAGE_NOT_READY, otherwise the last valid upload is retained. No video rendering loop is created. * @param uniforms Uniform values to merge into the active display-shader overrides. * @returns This function does not return a value. */ setDisplayShaderUniforms( params: { "uniforms": ShaderUniforms } ): void; setDisplayShaderUniforms( uniforms: ShaderUniforms ): void; /** * Sets the font for the current screen. * * Sets the active font for text rendering on the current screen. The font must already be loaded using loadFont. Several default fonts are preloaded: 0=6x6, 1=6x8 (default), 2=8x8, 3=8x14, 4=8x16. * @param fontId The id of the font to set. The default fonts loaded are. * @returns This function does not return a value. */ setFont( params: { "fontId": number } ): void; setFont( fontId: number ): void; /** * Configures color noise ranges and optional seed for blending. * * Sets per-channel noise ranges that influence color variation during blending operations. * * Noise formats: * - number: A value [0..255]. Applies symmetric range [-v..+v] to RGBA channels. * - [r, g, b, a]: Up to 4 values [0..255]. Each applies a symmetric range per channel. * - [[rMin, gMin, bMin, aMin], [rMax, gMax, bMax, aMax]]: Explicit per-channel min/max ranges [0..255]. * * Seed: * - A number used to seed noise generation. If omitted or null, the current time is used. * @param noise Noise configuration (number, 1D array, or 2D min/max arrays). * @param seed Optional noise seed used for deterministic noise. * @returns This function does not return a value. */ setNoise( params: { "noise"?: number | any[]; "seed"?: number } ): void; setNoise( noise?: number | any[], seed?: number ): void; /** * Replaces the current palette with a new set of colors. * * Sets an entirely new palette for the active screen. Index 0 is reserved for transparent black and will be set automatically. Note: Color indices may not match exactly because index 0 is strictly reserved for transparent black. * @param pal Array of color values (names, hex, RGBA, or palette indices). * @returns This function does not return a value. */ setPal( params: { "pal": Array } ): void; setPal( pal: Array ): void; /** * Updates one or more palette colors at specific indices. * * Sets multiple palette entries by index. Indices must be within the palette range and cannot be 0 (reserved for transparent black). * @param indices Array of palette indices to change. * @param colors Array of color values corresponding to indices. * @returns This function does not return a value. */ setPalColors( params: { "indices": Array; "colors": Array } ): void; setPalColors( indices: Array, colors: Array ): void; /** * Sets the print cursor position using column and row coordinates. * * Sets the print cursor position based on character grid coordinates (columns and rows). The grid size is determined by the current font size and print scale. Column and row are 0-indexed. * @param col Column position (0-indexed). * @param row Row position (0-indexed). * @returns This function does not return a value. */ setPos( params: { "col"?: number; "row"?: number } ): void; setPos( col?: number, row?: number ): void; /** * Sets the print cursor position using pixel coordinates. * * Sets the print cursor position using exact pixel coordinates. This allows precise positioning independent of the font's character grid. * @param x X position in pixels. * @param y Y position in pixels. * @returns This function does not return a value. */ setPosPx( params: { "x"?: number; "y"?: number } ): void; setPosPx( x?: number, y?: number ): void; /** * Sets the scale factor for printed text. * * Sets the horizontal and vertical scale factors for bitmap font rendering. This allows you to make text larger or smaller. Scale values must be finite numbers greater than 0 (INVALID_SIZE). * * Use padX and padY to add extra padding between characters when they print to the screen. Padding must be an integer of 0 or more (INVALID_PADDING). Omitted parameters keep their current values. * @param scaleWidth Horizontal scale factor; a number greater than 0. * @param scaleHeight Vertical scale factor; a number greater than 0. * @param padX Extra horizontal padding between characters in pixels; an integer of 0 or more. Defaults to 0. * @param padY Extra vertical padding between lines in pixels; an integer of 0 or more. Defaults to 0. * @returns This function does not return a value. */ setPrintSize( params: { "scaleWidth"?: number; "scaleHeight"?: number; "padX"?: number; "padY"?: number } ): void; setPrintSize( scaleWidth?: number, scaleHeight?: number, padX?: number, padY?: number ): void; /** * Enables or disables word breaking for text wrapping. * * Controls whether text wrapping breaks at word boundaries (spaces) or at any character. When enabled, long words will wrap at the last space before the line end. When disabled, text will wrap at any character. * @param isEnabled If true, enable word breaking at spaces. If false, break at any character. * @returns This function does not return a value. */ setWordBreak( params: { "isEnabled": boolean } ): void; setWordBreak( isEnabled: boolean ): void; /** * Converts a local view point to screen coordinates. * * Converts a point from the active view's local coordinates to screen / FBO coordinates using the logical view origin. This uses the requested origin, not the clipped origin. Input events stay screen-relative; use this helper when you need to compare local drawing coordinates with input positions. * @param x Local x coordinate. * @param y Local y coordinate. * @returns Screen / FBO position { x, y }. */ viewToScreen( params: { "x": number; "y": number } ): PositionPx; viewToScreen( x: number, y: number ): PositionPx; /** * Returns the screen or active view width in pixels. * * Gets the internal width of the active screen's canvas. This is the logical width used for drawing operations, which may differ from the CSS display size. * * If there is an active view using pushView then it will return the width of the local viewport area and not the screen width. * @returns Screen or local view width in pixels. */ width(): number; } interface API extends Screen, PluginCommands { /** * Converts a supported color value into a color object. * * Creates a PiColor object from a CSS color string, array, or color-like object. Useful for normalizing color values for inspection, comparison, or reuse without setting the screen drawing color or requiring an active screen. * @param color Palette index or color value (string, array, object, number). * @returns A color value object for the converted color. */ createColor( params: { "color": any } ): PiColor; createColor( color: any ): PiColor; /** * Creates a custom fragment shader and returns a handle. * * Creates a reusable custom fragment shader and returns a numeric handle. The handle is screen-independent: create it once, then pass it to applyShader or setDisplayShader on any screen. createShader stores the source and optional default uniforms; it does not draw. * * Pi.js drawing commands write into the logical framebuffer at the screen's resolution. applyShader samples that framebuffer through u_texture, runs the shader over every pixel, and replaces those pixels with the result. setDisplayShader runs later, when the logical framebuffer is presented to the canvas, and does not change logical pixels. For applyShader, u_sourceSize and u_outputSize are both the logical screen size. For setDisplayShader, u_sourceSize is the logical screen size and u_outputSize is the canvas backing size. * * Pi.js supplies a fullscreen-quad vertex stage, so you only write GLSL ES 3.00 fragment source. A good shader: * * - Starts with "#version 300 es" and a precision qualifier such as precision mediump float * - Declares in vec2 v_texCoord, uniform sampler2D u_texture, and out vec4 fragColor * - Reads u_texture with texture(u_texture, v_texCoord) * - Writes a complete premultiplied color to fragColor * - Declares built-in uniforms only when needed: u_texture (sampler2D), u_sourceSize (vec2), u_outputSize (vec2), u_time (float seconds), and u_frame (int) * - Keeps RGB between zero and alpha, with zero RGB at zero alpha * * Framebuffers, u_texture, custom sampler2D images, and fragment outputs use premultiplied RGBA: RGB is multiplied by alpha. For opacity, multiply all four channels. For inversion, use vec4(color.a - color.rgb, color.a). Unpremultiply with a zero-alpha guard before straight-color math, then premultiply the result before output. * * v_texCoord uses bottom-left/y-up UVs. Custom sampler2D images match the same orientation as u_texture. Drawing coordinates remain top-left/y-down. Convert UVs to screen pixels with vec2(uv.x, 1.0 - uv.y) * u_sourceSize. * * The source must include "#version 300 es". Compilation and validation happen synchronously the first time the shader is used on a screen. When first used, it must declare uniform sampler2D u_texture. Invalid shaders throw synchronously without changing rendering state. * * The second argument is an optional map of default custom uniform values. Values are interpreted from the linked GLSL declaration and may include float, integer, unsigned integer, boolean, vector, matrix, uniform-array, and sampler2D image inputs. Unknown and reserved built-in names are ignored. applyShader and setDisplayShader can override these defaults for a single use. A custom sampler cannot be the same screen the shader is applied to. Video sources refresh when decoded data is available; first use without a decoded frame throws IMAGE_NOT_READY, otherwise the last valid upload is retained. No video rendering loop is created. * @param fragmentSource GLSL ES 3.00 fragment shader source. Must include "#version 300 es". * @param uniforms Optional reflected custom uniform values keyed by uniform name. * @returns Shader handle id for applyShader or setDisplayShader. */ createShader( params: { "fragmentSource": string; "uniforms"?: ShaderUniforms } ): number; createShader( fragmentSource: string, uniforms?: ShaderUniforms ): number; /** * Returns an array of all screen API objects. * * Gets all created screens as an array of screen API objects. Each object has screen=true and an id property. * @returns Array of screen API objects. */ getAllScreens(): Array; /** * Returns an array of all loaded fonts with their properties. * * Gets information about all fonts that have been loaded. Returns an array of font info objects containing id, width, and height for each font. * @returns Array of font info objects with id, width, and height properties. */ getAvailableFonts(): Array; /** * Gets the default foreground color used by new screens. * * Returns the default drawing color for newly created screens. If asIndex is true, returns the palette index; otherwise returns the color value object. * @param asIndex If true returns the palette index, otherwise returns a color value object. * @returns Palette index if asIndex is true; otherwise a color value object. */ getDefaultColor( params: { "asIndex"?: boolean } ): number | PiColor; getDefaultColor( asIndex?: boolean ): number | PiColor; /** * Gets default palette and returns an array with all the color data. * * Gets the default color palette used when screens are created. By default, index 0 (transparent black) is excluded. The default color palette defines what colors are available when a new screen is created. * @param include0 If true include palette index 0 (transparent black). * @returns An array of color data for the default color palette. */ getDefaultPal( params: { "include0"?: boolean } ): Array; getDefaultPal( include0?: boolean ): Array; /** * Gets the image element by name, or a screen's canvas. * * Returns the underlying Image or Canvas element for a previously loaded image. Given a screen, it returns the screen's canvas; for an offscreen screen, which has no canvas of its own, it returns a new canvas holding a copy of the screen's pixels. * @param name Image name, or a screen. * @returns The actual Image or Canvas element. */ getImage( params: { "name": string | Screen } ): HTMLImageElement | HTMLCanvasElement; getImage( name: string | Screen ): HTMLImageElement | HTMLCanvasElement; /** * Returns a list of registered plugins and their status. * * Returns an array of plugin info objects including name, version, description, initialized, and state. state is "pending" while a plugin waits for its dependencies, "initialized" after it installs, and "failed" after its init or installation throws. A failed plugin stays listed until its name is registered again. * @returns Array of plugin info objects: { name, version, description, initialized, state }. */ getPlugins(): Array; /** * Gets a screen API object by screen ID. * * Retrieves the screen API object for a specific screen ID. This allows you to call all the graphics operations for a specific screen. This means you do not have to call setScreen to set the active screen every time you want to draw on a different screen. There is also a tiny performance advantage for drawing commands called directly on a screen object. * @param screenId The screen ID to retrieve. * @returns Screen API object with all graphics commands and screen=true and id property. */ getScreen( params: { "screenId": number } ): Screen; getScreen( screenId: number ): Screen; /** * Loads a bitmap font from an image source. * * Loads a bitmap font from an image URL or Image/Canvas element. The font image should contain characters arranged in a grid. Each character cell is width+margin*2 by height+margin*2 pixels. * * If charset is not provided, defaults to characters 0-255. The charset can be an array of character codes or a string of characters. * * Returns a font ID that can be used with setFont. After calling loadFont, you should call $.ready() to wait for the image to load before using the font. * * width and height must be integers of at least 1 (INVALID_DIMENSIONS), and margin an integer of 0 or more (INVALID_MARGIN): a TypeError for a value that is not an integer, and a RangeError for one out of range. * @param src Font image source: URL string, Image element, or Canvas element. * @param width Character width in pixels (glyph width, excluding margin); an integer of at least 1. * @param height Character height in pixels (glyph height, excluding margin); an integer of at least 1. * @param margin Margin around each character cell in pixels; an integer of 0 or more. Defaults to 0. * @param charset Character set as array of character codes or string. Defaults to 0-255 (ASCII) if not provided. * @returns Font ID that can be used with setFont. */ loadFont( params: { "src": string | HTMLImageElement | HTMLCanvasElement; "width": number; "height": number; "margin"?: number; "charset"?: Array | string } ): number; loadFont( src: string | HTMLImageElement | HTMLCanvasElement, width: number, height: number, margin?: number, charset?: Array | string ): number; /** * Loads an image by URL or from an Image/Canvas element. * * Loads an image and stores it by name. Use $.ready() to wait for loading before calling drawImage. Images retain their source colors when the screen palette changes. Use the shader API for recoloring. * @param src Image source: URL string, HTMLImageElement, or HTMLCanvasElement. * @param name Optional unique name for the image. Auto-generated if omitted. * @param onLoad Callback invoked when the image finishes loading. * @param onError Callback invoked if the image fails to load. * @returns The image name. */ loadImage( params: { "src": string | HTMLImageElement | HTMLCanvasElement; "name"?: string; "onLoad"?: ( name: string ) => void; "onError"?: ( error: Error ) => void } ): string; loadImage( src: string | HTMLImageElement | HTMLCanvasElement, name?: string, onLoad?: ( name: string ) => void, onError?: ( error: Error ) => void ): string; /** * Loads a spritesheet by URL or from an Image/Canvas element. * * Loads a spritesheet and slices it either automatically (connected components) or by a fixed grid. Sprites retain their source colors when the screen palette changes. Use the shader API for recoloring. * * In fixed grid mode, width and height must be integers of at least 1 (INVALID_DIMENSIONS), and margin an integer of 0 or more (INVALID_MARGIN), after rounding: a TypeError for a value that is not an integer, and a RangeError for one out of range. * @param src Spritesheet source: URL string, HTMLImageElement, or HTMLCanvasElement. * @param name Optional unique name for the spritesheet. Auto-generated if omitted. * @param width Sprite width for fixed grid mode. * @param height Sprite height for fixed grid mode. * @param margin Margin between sprites in fixed grid mode; an integer of 0 or more. Defaults to 0. * @param onLoad Callback invoked when the spritesheet finishes loading. * @param onError Callback invoked if the spritesheet fails to load. * @returns The spritesheet name. */ loadSpritesheet( params: { "src": string | HTMLImageElement | HTMLCanvasElement; "name"?: string; "width"?: number; "height"?: number; "margin"?: number; "onLoad"?: ( name: string ) => void; "onError"?: ( error: Error ) => void } ): string; loadSpritesheet( src: string | HTMLImageElement | HTMLCanvasElement, name?: string, width?: number, height?: number, margin?: number, onLoad?: ( name: string ) => void, onError?: ( error: Error ) => void ): string; /** * Waits for document readiness and all pending resources. * * Defers execution until the document is ready and all registered asynchronous resources have completed loading (e.g., images queued via internal loading). Supports both callback and promise styles. * * Callbacks always run asynchronously. If a callback throws synchronously, only that ready call's promise rejects with the thrown value; other queued waiters continue. Handle this failure through the returned promise. Successful calls resolve to undefined. Callback return values are ignored, including promises: ready does not wait for async callbacks to finish or adopt their rejections. * * Usage styles: * - Callback: $.ready( function() {} ); * - Promise: $.ready().then( function() {} ); * - Async/Await: await $.ready(); * @param callback Optional callback to run when ready completes. * @returns Resolves to undefined when ready, after invoking the optional callback. Rejects with the original thrown value if the callback throws synchronously. Callback return values are ignored. */ ready( params: { "callback"?: () => void } ): Promise; ready( callback?: () => void ): Promise; /** * Registers a plugin to extend Pi.js with custom commands and features. * * Registers a plugin that adds commands and per-screen behavior to Pi.js. Provide a unique name and an init function. init receives a pluginApi object; this is a callback argument, not a return value. Commands registered with addCommand appear on the Pi.js API and accept the same positional or options-object calling style as built-in commands. * * pluginApi methods and properties (the add and register methods work only while init runs, and throw REGISTRATION_CLOSED afterward): * * - **addCommand**(name, fn, isScreen, parameterNames, isScreenOptional): Add a command. Screen commands receive (screenData, options); global commands receive (options). Use screenData.api to draw. isScreenOptional allows a screen command when no screen is active. * - **addScreenDataItem**(name, defaultValue): Attach cloned data to every screen. * - **addScreenDataItemGetter**(name, getterFn): Attach per-screen data from a function called for each screen. * - **addScreenInitFunction**(initFn): Run when a screen is created, and once for screens that already exist. * - **addScreenPreCleanupFunction**(cleanupFn): Run first when a screen is removed. Cancel owned work and do not draw. * - **addScreenCleanupFunction**(cleanupFn): Run later when a screen is removed. Release remaining resources. * - **getActiveScreen**(fnName, isScreenOptional): Return the active screen data, or throw if none unless optional. * - **getScreenData**(fnName, screenId): Return screen data for a screen id. * - **getAllScreensData**(): Return all current screen data objects. * - **resizeOffscreenScreen**(screenData, width, height): Resize an offscreen screen. * - **getApi**(): Return the main Pi.js API object. * - **utils**: Shared helper functions for colors, parsing, and math. * - **wait**(): Hold $.ready() while an async resource loads. * - **done**(): Release one wait() so $.ready() can continue. * - **registerClearEvents**(name, handler): Handle $.clearEvents for an event type. * - **provideService**(service): During init, publish one service object for plugins that depend on this plugin. A second call throws DUPLICATE_SERVICE, a non-object throws INVALID_SERVICE, and a call after init throws SERVICE_PROVIDE_CLOSED. * - **getService**(pluginName): Return the service of a plugin listed in dependencies. Throws SERVICE_NOT_AVAILABLE when the plugin is not a declared dependency, is not initialized, or provided no service. * * Optional version and description are stored for getPlugins. Optional dependencies are other plugin names that must initialize first. Omit dependencies, or pass an empty array, if there are none. Missing or cyclic dependencies stay pending. * * Installation is all or nothing. The plugin's commands, settings, screen data, screen hooks, and clearEvents handlers take effect only after init and installation on existing screens both succeed. If either throws, none of them remain and the plugin's state in getPlugins is "failed"; side effects of the plugin's own code are not undone. A failure throws PLUGIN_INIT_FAILED from the registerPlugin call that registered the plugin. A plugin that fails while another call is resolving it, such as one waiting on the dependency that call registers, is reported with console.error instead. Plugins that depend on a failed plugin stay pending. Registering a failed plugin's name again retries it; any other duplicate name throws DUPLICATE_PLUGIN. * * If screens already exist when the plugin initializes, its commands and screen data are added to those screens and its screen init functions run once. Screens created later receive the same registrations automatically. Plugin scripts register themselves when loaded after Pi.js. The standalone scripts of plugins that the Full bundle includes are for Lite; loading one after the Full bundle throws DUPLICATE_PLUGIN. * @param name Unique plugin name. * @param init Initialization function that receives pluginApi. * @param version Optional plugin version. * @param description Optional plugin description. * @param dependencies Optional list of dependency plugin names. * @returns This function does not return a value. */ registerPlugin( params: { "name": string; "init": ( pluginApi: PluginAPI ) => void; "version"?: string; "description"?: string; "dependencies"?: Array } ): void; registerPlugin( name: string, init: ( pluginApi: PluginAPI ) => void, version?: string, description?: string, dependencies?: Array ): void; /** * Removes all screens from memory and the DOM. * @returns This function does not return a value. */ removeAllScreens(): void; /** * Removes a previously loaded image by name. * * Deletes the stored image and frees associated GPU resources (textures) for all screens. Draws already queued with the image complete before their textures are freed. Subsequent draws using the removed name throw IMAGE_NOT_FOUND. * @param name Image name to remove. * @returns This function does not return a value. */ removeImage( params: { "name": string } ): void; removeImage( name: string ): void; /** * Removes a screen and cleans up all associated resources. * * Removes a screen from the page and cleans up all WebGL2 resources, event handlers, and DOM elements. After removal, the screen object becomes invalid and calling methods on it will throw errors. * * Can be called either as a global function with a screen ID/object, or as a method on a screen API object. The global form also takes { "screen": screen }. A missing, unknown, or already removed screen throws INVALID_SCREEN_ID. * @param screen Screen ID (number) or screen API object to remove. Required in the global form; the declaration marks it optional because each screen's own removeScreen() takes none. * @returns This function does not return a value. */ removeScreen( params: { "screen"?: number | Screen } ): void; removeScreen( screen?: number | Screen ): void; /** * Removes a custom shader and releases its cached GPU programs. * * Completes every queued pass using the shader, clears it from active display screens, deletes its cached WebGL program from every screen, and invalidates the handle for future use. Removing an unknown or previously removed numeric handle is a no-op. Malformed handles throw INVALID_SHADER_HANDLE synchronously. * @param shaderHandle Shader handle returned by createShader. * @returns This function does not return a value. */ removeShader( params: { "shaderHandle": number } ): void; removeShader( shaderHandle: number ): void; /** * Creates a new screen (canvas) with specified dimensions and aspect ratio. * * Creates a WebGL 2 screen, makes it the active drawing target, and returns its Screen API object. Call screen before any graphics commands. Drawing writes into a logical framebuffer at the screen's resolution; Pi.js then presents that framebuffer to the canvas. * * **aspect** uses `(width)(x|e|m)(height)`: * * - **x**: Exact pixel dimensions (e.g., "320x200") * - **e**: Extend the logical area to fill the container while keeping the aspect ratio (e.g., "320e200") * - **m**: Scale by integer multiples of the target resolution (e.g., "320m200") * * For offscreen screens, only exact pixel dimensions (x) are allowed. An offscreen screen can use an existing screen as its parent to share that screen's WebGL context. This allows drawImage to use the offscreen framebuffer directly for faster drawing. The parent controls rendering-context affinity only and does not establish lifecycle ownership. * * Creating a screen makes it active. Pointer input requires an onscreen target, so after creating an offscreen buffer call setScreen on the visible screen or use visible.inMouse(). * @param aspect Aspect ratio string in format (width)(x|e|m)(height), e.g., '300x200', '100e00', '300m200'. * @param container DOM element or element ID string to use as container. Defaults to document.body. * @param isOffscreen If true, creates an offscreen canvas that is not displayed. Requires exact pixel dimensions. * @param resizeCallback Callback function called when screen is resized. Receives (screenApi, fromSize, toSize). * @param parent Existing screen ID or screen API object whose WebGL context the offscreen screen uses. Only valid when isOffscreen is true. Enables fast drawImage calls directly from the offscreen framebuffer and does not establish lifecycle ownership. * @param noCss If true, Pi.js does not write automatic canvas, container, html, or body styles. Supply canvas layout in your own CSS. The canvas is still appended and its size and WebGL resources are managed. Explicit background commands still apply requested styles. Logical x/e/m dimensions follow the container; display shader backing size follows the canvas CSS content size. Hidden hosts keep their last valid size and recover when visible. * @returns Screen API object with all graphics command and screen=true and id property. */ screen( params: { "aspect": string; "container"?: string | HTMLElement; "isOffscreen"?: boolean; "resizeCallback"?: ( screenApi: Screen, fromSize: Size, toSize: Size ) => void; "parent"?: number | Screen; "noCss"?: boolean } ): Screen; screen( aspect: string, container?: string | HTMLElement, isOffscreen?: boolean, resizeCallback?: ( screenApi: Screen, fromSize: Size, toSize: Size ) => void, parent?: number | Screen, noCss?: boolean ): Screen; /** * Sets the default foreground color used by new screens. * * Sets the drawing color for subsequently created screens from a default-palette index or a supported color value. Numeric indices must be finite integers from 0 through the last default-palette entry; index 0 is transparent black. * @param color Numeric integer palette index, CSS/hex string, RGB/RGBA array, or color object. * @returns This function does not return a value. */ setDefaultColor( params: { "color": any } ): void; setDefaultColor( color: any ): void; /** * Sets the default font for new screens. * * Sets the default font ID that will be used when new screens are created. The font must already be loaded using loadFont. * @param fontId Font ID from loadFont to use as default for new screens. * @returns This function does not return a value. */ setDefaultFont( params: { "fontId": number } ): void; setDefaultFont( fontId: number ): void; /** * Sets the default color palette for newly created screens. * * Defines the default palette used when a new screen is created. * * The first color (index 0) is reserved for transparent black and will be set automatically. This means that the color you set at (index 0) will be (index 1) in the internal palette. * @param pal Array of color values (names, hex, RGBA, or palette indices). * @returns This function does not return a value. */ setDefaultPal( params: { "pal": Array } ): void; setDefaultPal( pal: Array ): void; /** * Sets the active screen for graphics commands. * * Changes the active screen to the specified screen. All subsequent graphics commands will operate on this screen until another screen is set as active. * @param screen Screen ID (number) or screen API object to set as active. * @returns This function does not return a value. */ setScreen( params: { "screen": number | Screen } ): void; setScreen( screen: number | Screen ): void; /** * Current Pi.js version string. */ readonly version: "2.3.0"; } } // Module and global bindings for Pi.js // Runtime exposes window.pi and optional window.$; ESM exports pi and $. declare const pi: Pi.API; declare const $: Pi.API; export { pi, $ }; export default pi; export type PluginAPI = Pi.PluginAPI; export type API = Pi.API; export type Screen = Pi.Screen; // The global pi and $ are declared only by the Full declarations, so the Full and // Lite declarations can load together without conflicting globals.