WebGL backend
The WebGL backend maps luma.gl's shared GPU model to a browser WebGL2 context. It is packaged with core and gives applications a common device, resource, pipeline, pass, and submission flow while preserving the limits and rules of WebGL. See Rendering runtime platforms, Core API, Engine render loop, and WebGPU backend for the wider platform model.
Backend role
The backend is the WebGL implementation of luma.gl's Device API. It creates or adopts a WebGL2 context, exposes device limits and features, translates shared resource descriptions to WebGL objects, and turns render work into WebGL calls. The main entry point is webgl2Adapter in modules/…/webgl-adapter.ts.
The public WebGL surface is exported from modules/…/index.ts. It provides the adapter, device, canvas context, resource wrappers, render pipeline and pass types, command encoder, transform feedback, state helpers, and WebGL constants. This keeps WebGL-specific access available from core without changing the shared GPU API.
The backend aims to make common rendering work portable. It does not make WebGL behave like WebGPU in areas that WebGL cannot support, such as compute pipelines, render bundles, indirect draws, and external textures.
Context integration
Device creation and attachment
WebGLDevice owns one WebGL2 context and links that context back to its luma.gl device. The adapter can create a context for a canvas or attach to an existing context. Attachment is useful when another part of an application already controls context creation. In that case the adapter leaves canvas resizing to the context owner. A device supports one canvas context and can reuse the device already attached to that context when the caller enables device reuse.
Context creation first requests a high-performance WebGL2 context. It can fall back to a software renderer when allowed, but it rejects WebGL1 because the backend requires WebGL2 behavior. Context attributes and loss callbacks become part of the device lifecycle. The device links its resource and debug metadata to the context, initializes the state tracker from the context's current state, starts the default command encoder, and starts the canvas observers that keep frame work aligned with the drawing surface. Destruction stops those observers and marks the device lost when the device owns the teardown; reused wrappers leave the shared device lifetime to its owner. A lost context blocks creation of buffers, textures, samplers, and shaders.
flowchart LR
A[Canvas or external WebGL2 context] --> B[webgl2Adapter]
B --> C[WebGLDevice]
C --> D[Limits and features]
C --> E[Canvas context]
C --> F[WebGL resources and command encoder]
References: modules/…/webgl-adapter.ts• L15-73 modules/…/webgl-device.ts• L150-281 modules/…/webgl-device.ts• L284-354 modules/…/create-browser-context.ts• L19-97
Canvas and presentation
WebGLCanvasContext represents the device's single drawing canvas and treats the browser's default framebuffer as the current render target. It creates the default framebuffer wrapper when first needed and keeps that view's size aligned with the drawing buffer. A default render pass applies a pending size change before it sets its viewport, so rendering sees the current drawing buffer.
WebGLPresentationContext supports presentation through an OffscreenCanvas. It submits the WebGL work, checks that source and destination sizes agree, then copies the rendered image to a 2D presentation canvas. This path keeps rendering and display surfaces separate when the application needs it.
References: modules/…/webgl-canvas-context.ts• L11-59 modules/…/webgl-presentation-context.ts• L13-93 modules/…/webgl-render-pass.ts• L56-79
GPU concept translation
Resource model
The backend represents luma.gl resources with WebGL handles and records the WebGL rules needed to use those handles correctly. Shared formats, dimensions, usages, and layouts are converted at resource creation time so later rendering can use the device model. Framebuffers attach texture views to color and depth-stencil attachment points. The browser-owned default framebuffer has no WebGL framebuffer handle and follows the drawing-buffer size, while owned framebuffers manage their attachments.
Vertex arrays use native WebGL vertex array objects. They translate shared shader and buffer layout metadata into per-location attribute pointers, index-buffer bindings, and instance divisors. WebGL constant attributes use the context's constant values at draw time. When the browser cannot safely disable attribute location zero, the backend can use a buffer-backed constant value instead.
| luma.gl concept | WebGL representation | Main platform rule |
|---|---|---|
| Buffer | WebGL buffer object | Its first useful binding selects a buffer target such as vertex, index, or uniform data. |
| Texture | WebGL texture object | The texture target fixes the texture kind when it is first bound. |
| Sampler | Texture sampling parameters | Sampling state is applied to the texture rather than kept as a separate WebGL sampler binding. |
| Shader | Compiled vertex or fragment shader | Source is compiled as GLSL ES 3.00 unless it already declares a version. |
| Render pipeline | Linked WebGL program | Shader reflection supplies attributes, uniforms, samplers, uniform blocks, and varyings. |
| Vertex array | WebGL vertex array object | It stores index and vertex attribute setup for a draw. |
| Framebuffer | WebGL framebuffer or the default framebuffer | Color and depth targets become WebGL attachments. |
| Transform feedback | WebGL transform feedback object | It provides the WebGL path for selected buffer-output work. |
| Fence | WebGL sync object | Completion is observed by polling the sync state. |
The backend also supports borrowed texture handles for resources owned outside luma.gl. These handles are binding-only, so luma.gl does not allocate storage or change their data and sampling state. Owned textures use WebGL pixel transfer paths for updates and readback. Readback can target CPU memory or a buffer and uses a framebuffer for color subresources. Borrowed textures reject luma.gl texture mutations, including uploads, sampler changes, mipmap generation, and resize operations.
WebGL buffer mapping follows the shared buffer API through copies rather than persistent GPU mapping. Map-and-write creates temporary CPU data before a buffer update, while map-and-read obtains a CPU copy from the WebGL buffer.
References: modules/…/webgl-device.ts• L322-376 modules/…/webgl-buffer.ts• L10-180 modules/…/webgl-texture.ts• L89-188 modules/…/webgl-texture.ts• L311-385 modules/…/webgl-texture.ts• L626-759 modules/…/webgl-vertex-array.ts• L17-56 modules/…/webgl-vertex-array.ts• L73-182 modules/…/webgl-framebuffer.ts• L15-95 modules/…/webgl-framebuffer.ts• L117-157 modules/…/webgl-fence.ts• L8-58
Shader layouts and bindings
WebGL does not receive the same explicit binding model as WebGPU. After a program links, the backend inspects the program and builds a luma.gl shader layout. That layout connects shader attributes to vertex data and connects uniform blocks and sampler uniforms to application bindings.
Shared linked programs can serve more than one WebGL render pipeline. Each pipeline resolves its own reflected layout after it selects the shared program, so pipeline-specific uniform-block metadata does not become shared cache state. The layout can also apply supported application overrides to attributes and bindings that exist in the linked program.
During a draw, uniform buffers are bound to WebGL uniform-buffer points and textures are assigned to texture units. The backend initializes sampler uniforms when the program links, then reapplies uniform-block points and ordinary uniforms for each draw. Sampler bindings are represented by the texture's sampling parameters. A supplied layout can refine reflected attribute or block information when the application needs it.
flowchart LR
A[GLSL shaders] --> B[Linked WebGL program]
B --> C[Reflected shader layout]
C --> D[Uniform blocks]
C --> E[Texture units]
C --> F[Vertex attributes]
D --> G[Draw bindings]
E --> G
F --> G
References: modules/…/webgl-shared-render-pipeline.ts• L14-92 modules/…/webgl-shared-render-pipeline.ts• L134-193 modules/…/webgl-render-pipeline.ts• L34-88 modules/…/webgl-render-pipeline.ts• L217-318
Shader compilation
WEBGLShader turns shared vertex and fragment shader resources into GLSL ES 3.00 WebGL shader objects. When source has no version declaration, the backend supplies the WebGL2 version. The shader exposes compilation status and compiler messages through the shared shader API, so applications can inspect errors without using WebGL calls directly.
Compilation can be reported synchronously in debug mode or remain pending when production settings avoid an immediate status check. When the browser exposes parallel shader compilation, the backend waits for its completion status before it reports the final result. The optional WEBGL_debug_shaders extension can provide the browser-translated source for diagnosis.
References: modules/…/webgl-shader.ts• L13-77 modules/…/webgl-shader.ts• L81-135 modules/…/webgl-shader.ts• L143-185
Format and feature mapping
The backend maps luma.gl texture formats to WebGL internal formats, data formats, and pixel types. It reports support through the device's feature and capability model instead of assuming that every WebGL implementation supports every format. The format table also supplies the WebGL attachment and data rules used by texture creation and read or write operations.
Many optional capabilities depend on WebGL extensions. These include compressed textures, floating-point render targets, floating-point filtering, anisotropic filtering, and some normalized formats. A format can be creatable but not renderable or filterable, so callers must use the reported capability for the intended operation. Renderability checks can probe a one-pixel texture and framebuffer when extension data alone is not enough. Standalone stencil8 textures are reported as unsupported, and WebGL texture capabilities never expose storage-texture writes.
References: modules/…/webgl-texture-table.ts• L18-115 modules/…/webgl-texture-table.ts• L117-163 modules/…/webgl-texture-table.ts• L313-417 modules/…/webgl-device.ts• L514-517
WebGL execution behavior
Render pass execution
A WebGL render pass sets the framebuffer, viewport, scissor, blend, depth, stencil, and clear state before drawing. It saves the relevant context state when it starts and restores it when it ends. A missing framebuffer and an explicit wrapper with a null handle both use the browser's default framebuffer path. An application framebuffer maps its color attachments to draw buffers, while the default path selects GL.BACK and refreshes the drawing buffer before it derives default viewport state.
A draw selects the linked program, applies bindings and uniforms, binds the vertex array, and issues the matching WebGL draw call. The pass supports indexed, non-indexed, attribute-less, and instanced draws. Indexed draws require an index buffer and use indexCount for the element count. It can use transform feedback and WebGL query objects where the device exposes the matching feature. It skips a draw while shader linking or required texture loading is incomplete. Bindings must be set after the pipeline because the pipeline defines the binding layout used by the draw.
sequenceDiagram
participant App as Application
participant Enc as Command encoder
participant Pass as WebGL render pass
participant GL as WebGL2 context
App->>Enc: beginRenderPass()
Enc->>Pass: configure target and state
App->>Pass: set pipeline, bindings, and vertex array
App->>Pass: draw()
Pass->>GL: bind program and resources
Pass->>GL: issue draw call
App->>Pass: end()
Pass->>GL: restore saved state
References: modules/…/webgl-render-pass.ts• L39-115 modules/…/webgl-render-pass.ts• L132-181 modules/…/webgl-render-pass.ts• L201-305
Command encoding and submission
WebGL executes render passes and direct buffer writes immediately because the WebGL API is stateful and does not provide a native command buffer. The command encoder records supported copy operations. When a render pass or direct write starts, it flushes earlier copies first so the visible result keeps command order. Compute passes and query-set resolve operations are outside this execution path.
finish() returns a luma.gl command buffer. WebGLDevice.submit() flushes that buffer, resolves any submitted timing work, destroys the submitted buffer, and creates a fresh default encoder for the next frame. Buffer and texture copies use WebGL copy calls or pixel pack and unpack paths. Texture readback can attach a texture to a temporary or cached framebuffer and use readPixels. These operations are constrained by WebGL attachment, format, aspect, and row-layout rules.
References: modules/…/webgl-command-encoder.ts• L25-97 modules/…/webgl-command-buffer.ts• L64-126 modules/…/webgl-command-buffer.ts• L167-255 modules/…/webgl-command-buffer.ts• L280-372 modules/…/webgl-device.ts• L400-455
GPU completion fences
WEBGLFence represents completion of WebGL GPU work with a WebGLSync object. Its shared signaled promise polls the sync until WebGL reports completion, while isSignaled() provides a synchronous status check. The fence deletes the sync object when it owns the handle, so callers can use the common fence lifecycle without treating WebGL synchronization as a blocking CPU wait.
References: modules/…/webgl-fence.ts• L8-58 modules/…/webgl-device.ts• L368-374
Context state isolation
WebGL stores much of its state on the context rather than on individual resources. The state tracker caches selected state changes and provides nested push and pop behavior so luma.gl passes can change state without leaking it to later work. It intercepts tracked setters, getters, and program changes to avoid repeated context calls. It also invalidates tracked framebuffer, renderbuffer, and vertex-array bindings when those resources are deleted. It does not track buffer bindings.
When a device adopts or reuses an existing context, the tracker can first snapshot the context's current state. This lets luma.gl start from the state that the context owner established instead of from assumed defaults. The tracker restores state that luma.gl manages, but it does not cache every binding. Texture bindings depend on the active texture, while uniform-buffer and some other dynamic bindings remain outside the cache. The tracker is exposed through gl.lumaState, which gives the backend one state record for the context. Code that uses the raw context must still follow WebGL binding rules and must not assume that every state change is isolated by a resource wrapper.
References: modules/…/webgl-parameter-tables.ts• L14-93 modules/…/webgl-parameter-tables.ts• L97-180 modules/…/webgl-parameter-tables.ts• L401-472 modules/…/webgl-parameter-tables.ts• L643-682 modules/…/webgl-device.ts• L257-265 modules/…/webgl-device.ts• L546-554 modules/…/webgl-state-tracker.ts• L47-179 modules/…/webgl-state-tracker.ts• L181-331
Backend boundaries
WebGL provides a compatibility path for the shared rendering model, not the full WebGPU feature set. The following boundaries are part of the backend contract:
- WebGL1 contexts are not supported.
- Compute pipelines and compute passes are not supported.
- Render bundles and indirect draws are not supported.
- External textures are not supported.
- Storage and read-only storage bindings are not supported.
- Some texture dimensions and formats have no WebGL mapping.
- Device loss follows browser WebGL context-loss behavior and may require application recovery.
References: modules/…/webgl-adapter.ts• L24-39 modules/…/webgl-device.ts• L335-398 modules/…/webgl-command-encoder.ts• L49-57 modules/…/webgl-render-pass.ts• L124-127 modules/…/webgl-render-pass.ts• L287-295 modules/…/webgl-render-pipeline.ts• L291-298
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the public exports in modules/…/index.ts aligned with the backend classes and types that applications are expected to use. An internal move can otherwise remove a supported WebGL entry point without a clear runtime error.
- Keep shared-program caching separate from per-pipeline shader reflection and uniform-block metadata. A cache key that ignores layout behavior can reuse a program with the wrong binding contract.
- Keep shader source versioning, compilation status, compiler-log parsing, and draw readiness aligned. A shader can appear usable before its WebGL compilation result is safe to consume.
- Keep shader reflection, sampler-unit initialization, uniform-block lookup, and per-draw binding application aligned. Changes to names or binding order can silently break draws.
- Keep shader attribute locations, buffer layouts, WebGL pointer setup, and constant-attribute handling aligned. A location or type mismatch can silently corrupt vertex input.
- Keep default-framebuffer detection aligned with draw-buffer selection and deferred canvas resizing. An explicit wrapper or an externally resized canvas must follow the same default path.
- Preserve command flush points before immediate render passes, direct writes, and submit. Removing one can reorder copies and visible rendering.
- Keep fence creation, sync polling, signaled state, and owned-handle destruction aligned with the shared fence contract.
- Keep texture format tables, extension dependencies, renderability probes, and reported capabilities aligned. A format must not be advertised for an operation that WebGL cannot perform.
- Keep parameter defaults, setter tables, hooked setters, and non-cache rules aligned. A new state parameter can otherwise be set but not restored or tracked.
- Keep command-buffer copy options aligned with buffer and texture read and write limits. Unsupported aspects, mip levels, or row layouts must fail before issuing an invalid WebGL call.
- Keep context-loss classification, synchronous
isLoststate, and creation guards aligned. A lost context must not register new buffers, textures, samplers, or shaders. - Keep context ownership, device reuse, event-abort handling, and canvas observer teardown aligned. A wrapper must not destroy a context or shared device that another owner still uses.
- Keep borrowed-resource ownership checks aligned with texture allocation, upload, sampler, mipmap, readback, and resize paths. A borrowed handle must remain binding-only.
- Keep buffer target selection aligned with buffer usage and index type normalization. WebGL fixes a buffer's target class after its first bind.
- Keep
gl.lumaStatemetadata, deletion invalidation, context-state snapshots, and the state tracker's cache boundaries aligned. A new cached parameter or tracked binding can change what push and pop restore.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| No WebGL2 context is available | Device creation fails | Check adapter support and allow a software renderer only when suitable. |
| A format lacks its required extension or fails the renderability probe | Texture creation, framebuffer setup, or a draw can fail | Query device format capabilities before use. |
A standalone stencil8 texture is requested | The texture is rejected even though WebGL can use stencil renderbuffers | Use a supported depth or depth-stencil texture format. |
| A draw uses bindings that do not match the reflected shader layout | The draw is rejected or receives the wrong resources | Set the pipeline before bindings and use the pipeline's layout names. |
| A shared program is reused with incompatible pipeline metadata | Uniform blocks or attributes can use the wrong layout | Keep shared program reuse separate from pipeline-specific reflection and overrides. |
| A vertex attribute location or buffer layout does not match the shader | Vertex data is read with the wrong type, stride, or offset | Use the pipeline's shared layout when configuring the vertex array. |
| A constant attribute cannot disable location zero on the current browser | The constant value is not used or the draw incurs a browser fallback | Use the backend's constant-attribute path and its buffer fallback. |
| Shader compilation fails or remains pending when a draw starts | The draw is skipped or the pipeline reports an error | Wait for compilation completion and inspect the shared compiler messages. |
| A copy is followed by an immediate pass or write without preserving command order | The pass can read stale data | Use the command encoder and keep its flush-before-immediate-work behavior. |
| A render pass treats a default-framebuffer wrapper as an application framebuffer | The pass can select invalid draw buffers or use a stale viewport | Preserve null-handle detection and refresh the drawing buffer before default-pass setup. |
| A presentation canvas size differs from the WebGL drawing buffer | Presentation throws instead of copying an invalid image | Resize both surfaces through their context owners before presenting. |
| The browser loses the WebGL context | GPU work stops, the device becomes lost, and later guarded resource creation is rejected | Observe the device loss promise and rebuild application resources after recovery. |
| Application code changes untracked WebGL state | Later luma.gl work can render with wrong state | Use luma.gl parameter APIs or save and restore state around raw calls. |
| Code mutates a borrowed texture handle through a luma.gl upload or sampler API | An error is raised and the external texture remains unchanged | Treat borrowed textures as binding-only resources. |
| A buffer is used with an incompatible WebGL target class | WebGL rejects the bind or later operation | Create the buffer with the correct shared usage and keep its target class stable. |
| A reused device wrapper tears down shared context state | Other users lose their WebGL context or device | Keep teardown with the owner and use the reuse path for shared wrappers. |
Key files
| File | Why to read it |
|---|---|
| modules/…/index.ts | Shows the WebGL-specific API surface that core makes public. |
| modules/…/webgl-adapter.ts | Shows how applications create or attach a WebGL backend device. |
| modules/…/webgl-device.ts | Defines the backend lifecycle, resource factories, submission, loss, device reuse, and WebGL-only behavior. |
| modules/…/webgl-canvas-context.ts | Explains the default canvas and drawing-buffer relationship. |
| modules/…/webgl-presentation-context.ts | Explains offscreen rendering presentation to a 2D canvas. |
| modules/…/webgl-render-pass.ts | Shows how shared render-pass work becomes WebGL state changes, draw-buffer selection, and draw calls. |
| modules/…/webgl-framebuffer.ts | Shows how texture views become WebGL framebuffer attachments and how the default framebuffer follows the drawing buffer. |
| modules/…/webgl-render-pipeline.ts | Shows the link between reflected shader layout, bindings, uniforms, and a draw. |
| modules/…/webgl-shared-render-pipeline.ts | Shows shared program linking, sampler setup, and uniform-block lookup. |
| modules/…/webgl-vertex-array.ts | Shows how shared vertex layouts become WebGL VAO state, indexed input, instancing, and constant attributes. |
| modules/…/webgl-shader.ts | Shows WebGL shader versioning, compilation status, diagnostics, and translated-source access. |
| modules/…/webgl-fence.ts | Shows how GPU completion becomes a shared fence promise and status check. |
| modules/…/webgl-buffer.ts | Shows how shared buffer usage becomes WebGL target selection, copy-based mapping, and synchronous readback. |
| modules/…/webgl-texture.ts | Shows texture ownership rules, pixel uploads, buffer readback, subresource attachment, and WebGL sampler behavior. |
| modules/…/webgl-command-encoder.ts | Shows which work is recorded, when it is flushed, and which WebGL features are unavailable. |
| modules/…/webgl-command-buffer.ts | Shows how copy and readback commands execute at flush or submit time. |
| modules/…/get-shader-layout-from-glsl.ts | Explains how WebGL program metadata becomes the shared binding layout. |
| modules/…/webgl-texture-table.ts | Explains format translation, extension checks, and renderability capability probes. |
| modules/…/webgl-parameter-tables.ts | Defines WebGL state defaults, setters, hooks, and cache boundaries. |
| modules/…/webgl-state-tracker.ts | Explains state caching, context-state snapshots, deletion invalidation, and pass-level state restoration. |
| modules/…/create-browser-context.ts | Explains WebGL2 context selection, software fallback, creation errors, and loss events. |
| modules/…/fill-array.ts | Shows the shared array-fill behavior used when the backend expands constant vertex values for buffer fallback. |