Skip to content

Modern WebGL state wrapper for PEX: allocate GPU resources (textures, buffers), setup state pipelines and passes, and combine them into commands.

License

Notifications You must be signed in to change notification settings

pex-gl/pex-context

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

pex-context

npm version stability-stable npm minzipped size dependencies types Conventional Commits styled with prettier linted with eslint license

Modern WebGL state wrapper for PEX: allocate GPU resources (textures, buffers), setup state pipelines and passes, and combine them into commands.

Installation

npm install pex-context

Usage

import createContext from "pex-context";

import { mat4 } from "pex-math";
import { cube } from "primitive-geometry";

const W = 640;
const H = 480;
const ctx = createContext({ width: W, height: H });

const geom = cube();

const clearCmd = {
  pass: ctx.pass({
    clearColor: [0.2, 0.2, 0.2, 1],
    clearDepth: 1,
  }),
};

const drawCmd = {
  pipeline: ctx.pipeline({
    depthTest: true,
    vert: /* glsl */ `
attribute vec3 aPosition;
attribute vec3 aNormal;

uniform mat4 uProjectionMatrix;
uniform mat4 uViewMatrix;

varying vec4 vColor;

void main () {
  vColor = vec4(aNormal * 0.5 + 0.5, 1.0);

  gl_Position = uProjectionMatrix * uViewMatrix * vec4(aPosition, 1.0);
}
`,
    frag: /* glsl */ `
precision highp float;

varying vec4 vColor;

void main() {
  gl_FragColor = vColor;
}
`,
  }),
  attributes: {
    aPosition: ctx.vertexBuffer(geom.positions),
    aNormal: ctx.vertexBuffer(geom.normals),
  },
  indices: ctx.indexBuffer(geom.cells),
  uniforms: {
    uProjectionMatrix: mat4.perspective(
      mat4.create(),
      Math.PI / 4,
      W / H,
      0.1,
      100,
    ),
    uViewMatrix: mat4.lookAt(mat4.create(), [2, 2, 5], [0, 0, 0], [0, 1, 0]),
  },
};

ctx.frame(() => {
  ctx.submit(clearCmd);
  ctx.submit(drawCmd);
});

API

Objects

ctx : object

Functions

createContext([options]) ⇒ ctx

Create a context object

Typedefs

BufferOptions : PexResource
Attachment : object
PassOptions : PexResource
PipelineOptions : PexResource
QueryOptions : PexResource
PexQuery : QueryOptions
RenderbufferOptions : PexResource
TextureOptionsData : HTMLImageElement | HTMLVideoElement | HTMLCanvasElement
TextureTarget : WebGLRenderingContext.TEXTURE_2D | WebGLRenderingContext.TEXTURE_CUBE_MAP
TextureOptions : PexResource
TextureCubeOptions : PexResource
VertexArrayOptions : PexResource
PexContextOptions : object
PexResource : object

All resources are plain js object and once constructed their properties can be accessed directly. Please note those props are read only. To set new values or upload new data to GPU see updating resources.

PexTexture2D : object
PexAttribute : object
PexCommand : object
MultiDrawOptions : object
PexContextSetOptions : object
Viewport : Array.<number>

[x, y, w, h]

Color : Array.<number>

[r, g, b, a]

TypedArray : Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array

ctx : object

Kind: global namespace

ctx.gl

The RenderingContext returned by pex-gl

Kind: static property of ctx

ctx.capabilities

Max capabilities and extensions availability. See Capabilities Table.

Kind: static property of ctx

ctx.width ⇒ number

Getter for gl.drawingBufferWidth

Kind: static property of ctx

ctx.height ⇒ number

Getter for gl.drawingBufferHeight

Kind: static property of ctx

ctx.BlendFactor

Kind: static enum of ctx Properties

Name Default
One gl.ONE
Zero gl.ZERO
SrcAlpha gl.SRC_ALPHA
OneMinusSrcAlpha gl.ONE_MINUS_SRC_ALPHA
DstAlpha gl.DST_ALPHA
OneMinusDstAlpha gl.ONE_MINUS_DST_ALPHA
SrcColor gl.SRC_COLOR
OneMinusSrcColor gl.ONE_MINUS_SRC_COLOR
DstColor gl.DST_COLOR
OneMinusDstColor gl.ONE_MINUS_DST_COLOR

ctx.CubemapFace

Kind: static enum of ctx Properties

Name Default
PositiveX gl.TEXTURE_CUBE_MAP_POSITIVE_X
NegativeX gl.TEXTURE_CUBE_MAP_NEGATIVE_X
PositiveY gl.TEXTURE_CUBE_MAP_POSITIVE_Y
NegativeY gl.TEXTURE_CUBE_MAP_NEGATIVE_Y
PositiveZ gl.TEXTURE_CUBE_MAP_POSITIVE_Z
NegativeZ gl.TEXTURE_CUBE_MAP_NEGATIVE_Z

ctx.DepthFunc

Kind: static enum of ctx Properties

Name Default
Never gl.NEVER
Less gl.LESS
Equal gl.EQUAL
LessEqual gl.LEQUAL
Greater gl.GREATER
NotEqual gl.NOTEQUAL
GreaterEqual gl.GEQUAL
Always gl.ALWAYS

ctx.Face

Kind: static enum of ctx Properties

Name Default
Front gl.FRONT
Back gl.BACK
FrontAndBack gl.FRONT_AND_BACK

ctx.Filter

Kind: static enum of ctx Properties

Name Default
Nearest gl.NEAREST
Linear gl.LINEAR
NearestMipmapNearest gl.NEAREST_MIPMAP_NEAREST
NearestMipmapLinear gl.NEAREST_MIPMAP_LINEAR
LinearMipmapNearest gl.LINEAR_MIPMAP_NEAREST
LinearMipmapLinear gl.LINEAR_MIPMAP_LINEAR

ctx.PixelFormat

Mapping of ctx.TextureFormat keys to their string values and legacy depth formats

One of:

  • Unsized: RGB, RGBA, LUMINANCE_ALPHA, LUMINANCE, ALPHA
  • Sized 1 component: R8, R8_SNORM, R16F, R32F, R8UI, R8I, R16UI, R16I, R32UI, R32I
  • Sized 2 components: RG8, RG8_SNORM, RG16F, RG32F, RG8UI, RG8I, RG16UI, RG16I, RG32UI, RG32I
  • Sized 3 components: RGB8, RGB8_SNORM, RGB16F, RGB32F, RGB8UI, RGB8I, RGB16UI, RGB16I, RGB32UI, RGB32I
  • Sized 4 components: RGBA8, RGBA8_SNORM, RGBA16F, RGBA32F, RGBA8UI, RGBA8I, RGBA16UI, RGBA16I, RGBA32UI, RGBA32I
  • Sized special: SRGB8, RGB565, R11F_G11F_B10F, RGB9_E5, SRGB8_ALPHA8, RGB5_A1, RGBA4, RGB10_A2, RGB10_A2UI
  • Sized depth/stencil: DEPTH_COMPONENT16, DEPTH_COMPONENT24, DEPTH_COMPONENT32F, DEPTH24_STENCIL8, DEPTH32F_STENCIL8

Kind: static enum of ctx

ctx.RenderbufferFloatFormat

Kind: static enum of ctx Properties

Name Default
RGBA32F
RGBA16F
R16F
RG16F
R32F
RG32F
R11F_G11F_B10F

ctx.Encoding

Kind: static enum of ctx Properties

Name Default
Linear 1
Gamma 2
SRGB 3
RGBM 4

ctx.Primitive

Kind: static enum of ctx Properties

Name Default
Points gl.POINTS
Lines gl.LINES
LineStrip gl.LINE_STRIP
Triangles gl.TRIANGLES
TriangleStrip gl.TRIANGLE_STRIP

ctx.Usage

Kind: static enum of ctx Properties

Name Default
StaticDraw gl.STATIC_DRAW
DynamicDraw gl.DYNAMIC_DRAW
StreamDraw gl.STREAM_DRAW

ctx.Wrap

Kind: static enum of ctx Properties

Name Default
ClampToEdge gl.CLAMP_TO_EDGE
Repeat gl.REPEAT
MirroredRepeat gl.MIRRORED_REPEAT

ctx.QueryTarget

Kind: static enum of ctx Properties

Name Default
TimeElapsed gl.TIME_ELAPSED
AnySamplesPassed gl.ANY_SAMPLES_PASSED
AnySamplesPassedConservative gl.ANY_SAMPLES_PASSED_CONSERVATIVE
TransformFeedbackPrimitivesWritten gl.TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN

ctx.QueryState

Kind: static enum of ctx Properties

Name Default
Ready ready
Active active
Pending pending

ctx.set(options)

Set the context size and pixelRatio The new size and resolution will not be applied immediately but before drawing the next frame to avoid flickering. Context's canvas doesn't resize automatically, even if you don't pass width/height on init and the canvas is assigned the dimensions of the window. To handle resizing use the following code:

window.addEventListener("resize", () => {
  ctx.set({ width: window.innerWidth, height: window.innerHeight });
});

Kind: static method of ctx

Param Type
options PexContextSetOptions

ctx.debug([enabled])

Enable debug mode

Kind: static method of ctx

Param Type
[enabled] boolean

ctx.frame(cb)

Render Loop

Kind: static method of ctx

Param Type Description
cb function Request Animation Frame callback

ctx.submit(cmd, [batches], [subCommand])

Submit a command to the GPU. Commands are plain js objects with GPU resources needed to complete a draw call.

const cmd = {
  pass: Pass
  pipeline: Pipeline,
  attributes: { name:  VertexBuffer | { buffer: VertexBuffer, offset: number, stride: number } },
  indices: IndexBuffer | { buffer: IndexBuffer, offset: number, count: number },
  // or
  count: number,
  instances: number,
  uniforms: { name: number, name: Array, name: Texture2D },
  viewport: [0, 0, 1920, 1080],
  scissor: [0, 0, 1920, 1080]
}

Note: Either indices or count need to be specified when drawing geometry. Note: Scissor region is by default set to null and scissor test disabled.

Kind: static method of ctx

Param Type
cmd PexCommand
[batches] PexCommand | Array.<PexCommand>
[subCommand] PexCommand

Example

  • ctx.submit(cmd, opts): submit partially updated command without modifying the original one.
// Draw mesh with custom color
ctx.submit(cmd, {
  uniforms: {
    uColor: [1, 0, 0, 0],
  },
});
  • ctx.submit(cmd, [opts1, opts2, opts3...]): submit a batch of commands differences in opts.
// Draw same mesh twice with different material and position
ctx.submit(cmd, [
  { pipeline: material1, uniforms: { uModelMatrix: position1 },
  { pipeline: material2, uniforms: { uModelMatrix: position2 }
])
  • ctx.submit(cmd, cb): submit command while preserving state from another command. This approach allows to simulate state stack with automatic cleanup at the end of callback.
// Render to texture
ctx.submit(renderToFboCmd, () => {
  ctx.submit(drawMeshCmd);
});

ctx.pass(opts) ⇒ PexResource

Passes are responsible for setting render targets (textures) and their clearing values. FBOs are created internally and automatically.

Kind: static method of ctx

Param Type
opts PassOptions

Example

const pass = ctx.pass({
  color: [Texture2D, ...]
  color: [{ texture: Texture2D | TextureCube, target: CubemapFace }, ...]
  depth: Texture2D
  clearColor: Array,
  clearDepth: number,
})

ctx.pipeline(opts) ⇒ PexResource

Pipelines represent the state of the GPU rendering pipeline (shaders, blending, depth test etc).

Kind: static method of ctx

Param Type
opts PipelineOptions

Example

const pipeline = ctx.pipeline({
  vert: string,
  frag: string,
  depthWrite: boolean,
  depthTest: boolean,
  depthFunc: DepthFunc,
  blend: boolean,
  blendSrcRGBFactor: BlendFactor,
  blendSrcAlphaFactor: BlendFactor,
  blendDstRGBFactor: BlendFactor,
  blendDstAlphaFactor: BlendFactor,
  cullFace: boolean,
  cullFaceMode: Face,
  colorMask: Array,
  primitive: Primitive,
});

ctx.vertexArray(opts) ⇒ PexResource

Create a VAO resource.

Kind: static method of ctx

Param Type
opts VertexArrayOptions

Example

const vertexLayout = {
  aPosition: { location: 0, type: "vec3" },
  aNormal: { location: 1, type: "vec3" },
};

const drawCmd = {
  pipeline: ctx.pipeline({
    vertexLayout,
    // ...
  }),
  vertexArray: ctx.vertexArray({
    vertexLayout,
    attributes: {
      aPosition: ctx.vertexBuffer(geom.positions),
      aNormal: { buffer: ctx.vertexBuffer(geom.normals) },
    },
    indices: ctx.indexBuffer(geom.cells),
  }),
  // ...
};

ctx.texture2D(opts) ⇒ PexResource

Create a 2D Texture resource.

Kind: static method of ctx

Param Type
opts HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | TextureOptions

Example

const tex = ctx.texture2D({
  data: [255, 255, 255, 255, 0, 0, 0, 255],
  width: 2,
  height: 1,
  pixelFormat: ctx.PixelFormat.RGB8,
  encoding: ctx.Encoding.Linear,
  wrap: ctx.Wrap.Repeat,
});

ctx.textureCube(opts) ⇒ PexResource

Create a 2D Texture cube resource.

Kind: static method of ctx

Param Type
opts TextureCubeOptions

Example

const tex = ctx.textureCube({
  data: [posx, negx, posy, negy, posz, negz],
  width: 64,
  height: 64
])

ctx.renderbuffer(opts) ⇒ PexResource

Renderbuffers represent pixel data store for rendering operations.

Kind: static method of ctx

Param Type
opts RenderbufferOptions

Example

const tex = ctx.renderbuffer({
  width: 1280,
  height: 720,
  pixelFormat: ctx.PixelFormat.DEPTH_COMPONENT16,
});

ctx.vertexBuffer(opts) ⇒ PexResource

Create an attribute buffer (ARRAY_BUFFER) resource. Stores vertex data in the GPU memory.

Kind: static method of ctx

Param Type
opts BufferOptions

Example

const vertexBuffer = ctx.vertexBuffer({
  data: Array | TypedArray | ArrayBuffer,
});

ctx.indexBuffer(opts) ⇒ PexResource

Create an index buffer (ELEMENT_ARRAY_BUFFER) resource. Stores index data in the GPU memory.

Kind: static method of ctx

Param Type
opts BufferOptions

Example

const indexBuffer = ctx.vertexBuffer({
  data: Array | TypedArray | ArrayBuffer,
});

ctx.query(opts) ⇒ PexResource

Queries can be used for GPU timers.

Kind: static method of ctx

Param Type
opts QueryOptions

Example

const query = ctx.query({
  target: QueryTarget,
});

ctx.beginQuery(query)

Begin the query measurement.

Kind: static method of ctx

Param Type Description
query PexQuery Note: There can be only one query running at the time.

ctx.endQuery(query)

End the query measurement.

Kind: static method of ctx

Param Type Description
query PexQuery Note: The result is not available immediately and will be null until the state changes from ctx.QueryState.Pending to ctx.QueryState.Ready.

ctx.readPixels(viewport) ⇒ Uint8Array

Helper to read a block of pixels from a specified rectangle of the current color framebuffer.

Kind: static method of ctx

Param Type
viewport Object

ctx.update(resource, opts)

Update a resource.

Kind: static method of ctx

Param Type
resource PexResource
opts object

Example

ctx.update(buffer, { data: [] });

ctx.update(texture, {
  width: 1,
  height: 1,
  data: new Uint8Array([255, 0, 0, 255]),
});

ctx.dispose([resource])

Delete one or all resource(s). Disposed resources are no longer valid for use.

Kind: static method of ctx

Param Type
[resource] PexResource

Example Delete all allocated resources:

ctx.dispose();

Delete a single resource:

ctx.dispose(texture);

Note: Framebuffers are ref counted and released by Pass. Programs are also ref counted and released by Pipeline.

createContext([options]) ⇒ ctx

Create a context object

Kind: global function

Param Type
[options] PexContextOptions | module:pex-gl~Options

BufferOptions : PexResource

Kind: global typedef Properties

Name Type Default
data Array | TypedArray | ArrayBuffer
[type] ctx.DataType
[usage] Usage ctx.Usage.StaticDraw
offset number

Attachment : object

Kind: global typedef Properties

Name Type
texture PexResource
target WebGLRenderingContext.FRAMEBUFFER

PassOptions : PexResource

Kind: global typedef Properties

Name Type Description
[color] Array.<PexTexture2D> | Array.<Attachment> render target
[depth] PexTexture2D render target
[clearColor] Color
[clearDepth] number

PipelineOptions : PexResource

Kind: global typedef Properties

Name Type Default Description
[vert] string null Vertex shader code
[frag] string null Fragment shader code
[depthWrite] boolean true Depth write mask
[depthTest] boolean false Depth test on/off
[depthFunc] DepthFunc ctx.DepthFunc.LessEqual Depth test function
[blend] boolean false Blending on/off
[blendSrcRGBFactor] BlendFactor ctx.BlendFactor.One Blending source color factor
[blendSrcAlphaFactor] BlendFactor ctx.BlendFactor.One Blending source alpha factor
[blendDstRGBFactor] BlendFactor ctx.BlendFactor.One Blending destination color factor
[blendDstAlphaFactor] BlendFactor ctx.BlendFactor.One Blending destination alpha factor
[cullFace] boolean false Face culling on/off
[cullFaceMode] Face ctx.Face.Back Face culling mode
[colorMask] Array.<boolean> [true, true, true, true] Color write mask for [r, g, b, a]
[primitive] Primitive ctx.Primitive.Triangles Geometry primitive

QueryOptions : PexResource

Kind: global typedef Properties

Name Type Default Description
[target] QueryTarget ctx.QueryTarget.TimeElapsed query type

PexQuery : QueryOptions

Kind: global typedef Properties

Name Type Default Description
[state] QueryState ctx.QueryState.Ready
[result] number result of the measurement

RenderbufferOptions : PexResource

Kind: global typedef Properties

Name Type Default Description
width number
height number
[pixelFormat] PixelFormat ctx.PixelFormat.DEPTH_COMPONENT16 only PixelFormat.DEPTH_COMPONENT16 is currently supported for use as render pass depth storage (e.g. ctx.pass({ depth: renderbuffer })) for platforms with no WEBGL_depth_texture support.

TextureOptionsData : HTMLImageElement | HTMLVideoElement | HTMLCanvasElement

Kind: global typedef Properties

Name Type
data Array | TypedArray
width number
height number

TextureTarget : WebGLRenderingContext.TEXTURE_2D | WebGLRenderingContext.TEXTURE_CUBE_MAP

Kind: global typedef

TextureOptions : PexResource

Kind: global typedef Properties

Name Type Default Description
[data] HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | Array | TypedArray | TextureOptionsData | Array.<HTMLImageElement> | Array.<TextureOptionsData>
[width] number
[height] number
[pixelFormat] PixelFormat ctx.PixelFormat.RGB8
[internalFormat] ctx.TextureFormat ctx.TextureFormat.RGBA
[type] ctx.DataType ctx.TextureFormat[opts.pixelFormat]
[encoding] Encoding ctx.Encoding.Linear
[wrapS] Wrap ctx.Wrap.ClampToEdge
[wrapT] Wrap ctx.Wrap.ClampToEdge
[wrap] Wrap ctx.Wrap.ClampToEdge
[min] Filter ctx.Filter.Nearest
[mag] Filter ctx.Filter.Nearest
[aniso] number 0 requires EXT_texture_filter_anisotropic
[mipmap] boolean true requires min to be set to ctx.Filter.LinearMipmapLinear or similar
[premultiplyAlpha] boolean false
[flipY] boolean false
[compressed] boolean false
[target] TextureTarget

TextureCubeOptions : PexResource

Kind: global typedef Extends: TextureOptions Properties

Name Type Description
[data] Array.<HTMLImageElement> | Array.<TypedArray> 6 images, one for each face +X, -X, +Y, -Y, +Z, -Z

VertexArrayOptions : PexResource

Kind: global typedef Properties

Name Type
vertexLayout object
[attributes] object
[indices] object

PexContextOptions : object

Kind: global typedef Properties

Name Type Default
[gl] WebGLRenderingContext | WebGL2RenderingContext WebGL2RenderingContext
[width] number window.innerWidth
[height] number window.innerHeight
[pixelRatio] number 1
[type] "webgl" | "webgl2" "webgl2"
[debug] boolean false

PexResource : object

All resources are plain js object and once constructed their properties can be accessed directly. Please note those props are read only. To set new values or upload new data to GPU see updating resources.

Kind: global typedef Properties

Name Type
name string

PexTexture2D : object

Kind: global typedef

PexAttribute : object

Kind: global typedef Properties

Name Type Description
buffer object ctx.vertexBuffer() or ctx.indexBuffer()
[offset] number
[stride] number
[divisor] number
[normalized] boolean

PexCommand : object

Kind: global typedef Properties

Name Type Description
pass PassOptions
pipeline PipelineOptions
[attributes] object vertex attributes, map of attributeName: ctx.vertexBuffer() or attributeName: PexAttribute
[indices] object indices, ctx.indexBuffer() or PexAttribute
[count] number number of vertices to draw
[instances] number number instances to draw
[uniforms] object shader uniforms, map of name: value
[viewport] Viewport drawing viewport bounds
[scissor] Viewport scissor test bounds
[multiDraw] MultiDrawOptions
[baseVertex] number
[baseInstance] number

MultiDrawOptions : object

Kind: global typedef See

Properties

Name Type
counts Int32Array | Array
[countsOffset] number
offsets Int32Array | Array
[offsetsOffset] number
firsts Int32Array | Array
[firstsOffset] number
instanceCounts Int32Array | Array
[instanceCountsOffset] number
baseVertices Int32Array | Array
[baseVerticesOffset] number
baseInstances UInt32Array | Array
[baseInstancesOffset] number
[drawCount] number

PexContextSetOptions : object

Kind: global typedef Properties

Name Type
[width] number
[height] number
[pixelRatio] number

Viewport : Array.<number>

[x, y, w, h]

Kind: global typedef

Color : Array.<number>

[r, g, b, a]

Kind: global typedef

TypedArray : Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array

Kind: global typedef

Capabilities

Example

const maxTextureSize = ctx.capabilities.maxTextureSize;
Name Type
isWebGL2 number
maxColorAttachments number
maxTextureImageUnits number
maxVertexTextureImageUnits number
maxVertexAttribs number
maxTextureSize number
maxCubeMapTextureSize number
depthTexture boolean
shaderTextureLod boolean
textureFloat boolean
textureFloatLinear boolean
textureHalfFloat boolean
textureHalfFloatLinear boolean
textureFilterAnisotropic boolean
disjointTimerQuery boolean
colorBufferFloat boolean
colorBufferHalfFloat boolean
floatBlend boolean
multiDraw boolean
drawInstancedBase boolean
multiDrawInstancedBase boolean

License

MIT. See license file.

About

Modern WebGL state wrapper for PEX: allocate GPU resources (textures, buffers), setup state pipelines and passes, and combine them into commands.

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks