Introducing a new way to review your PRs.

Read the announcement

visgl / luma.gl

High-performance Toolkit for WebGL-based Data Visualization

View on GitHub

30 documents · Updated Nov 20, 2026

docs / core-api

Core API and GPU abstractions

The core API gives applications and platform backends one shared way to create devices, manage GPU resources, encode work, and move data between the CPU and GPU. It keeps application code independent of WebGL and WebGPU while exposing the device limits, features, formats, and life cycle rules that affect rendering. Shared shader and data types, uniform layouts, diagnostics, and test devices support the same contract across runtime environments. See Rendering runtime platforms for the place of this API in the wider runtime.

API boundary

The API separates platform choice from GPU work. The application asks luma for a device, the selected adapter creates or attaches the device, and the device exposes common resource and submission operations to both backend families.

flowchart LR
  App[Application] --> Luma[luma entry point]
  Luma --> Adapter[Backend adapter]
  Adapter --> Device[Core Device]
  Device --> Resources[Shared GPU resources]
  Device --> Encoder[Command encoder]
  Encoder --> Submit[Backend submission]

Device selection

modules/…/luma.ts is the public entry point. createDevice selects a registered adapter by request or by the best-available order, which prefers WebGPU, then WebGL, and then a registered null adapter. attachDevice wraps an existing WebGL or WebGPU handle so an application can keep control of context or device creation. Adapter registration controls which platform packages can be selected, and waitForPageLoad lets browser adapters delay canvas access until the page is ready. The Adapter contract in modules/…/adapter.ts also gives each backend a support check, handle check, create path, attach path, and shared page-load wait.

WebGPU device selection also chooses a feature profile. core requests the portable profile, max forwards supported features and limits, compatibility stays in compatibility mode, and best-available upgrades to core when the adapter supports it. The created device reports the effective profile rather than only the request, so applications can make decisions from the capabilities they actually received.

References: modules/…/luma.ts• L22-45 modules/…/luma.ts• L92-125 modules/…/luma.ts• L129-167 modules/…/adapter.ts• L8-32 modules/…/webgpu-adapter.ts• L82-185 modules/…/webgpu-adapter.ts• L209-359 modules/…/luma.spec.ts• L9-34 modules/…/luma.spec.ts• L61-82

Device defaults

Device creation starts from shared defaults so applications and adapters use the same policy. The defaults request high performance, leave optional features and limits open unless the application sets them, enable resource and pipeline reuse, and provide callbacks for errors and canvas changes. Debug mode is on when the URL contains the debug parameter or when logging explicitly enables it; otherwise a non-production environment enables it and production defaults to off. The same defaults apply when a backend creates a device and when it wraps an existing handle.

References: modules/…/device-defaults.ts• L8-62 modules/…/device-defaults.ts• L64-90 modules/…/device.spec.ts• L145-174

Device contract

The Device is the main boundary used by applications and backends. It reports device identity, the effective WebGPU feature level when relevant, features, limits, preferred formats, and loss state. It also creates resources, owns the default command encoder, creates canvas contexts, and submits finished command work. An application can use these reports to choose a valid path before it creates a resource or starts a pass.

The same contract includes device-facing helpers for format capability checks, external image handling, asynchronous pipeline creation, and device-managed GPU timing. Backend-specific implementations decide which optional operations are available while preserving the shared type and life cycle contract. Device errors are reported through one callback and loss reports use stable unknown and destroyed reasons; the diagnostic message remains for people, not for application control flow.

References: modules/…/device.ts• L46-106 modules/…/device.ts• L383-482 modules/…/device.ts• L510-588 modules/…/device.ts• L600-685 modules/…/device.ts• L687-745 modules/…/device.ts• L757-933

Public API surface

The package entry points expose the device contract, resource classes, pipeline factories, pass and command types, shader layouts, uniform helpers, data types, vertex formats, texture formats, and small utility functions. modules/…/index.ts is the API export map, while modules/…/index.ts makes that contract available from the package root and also exposes the shader-type decoders and format helpers used by applications and backends.

References: modules/…/index.ts• L5-23 modules/…/index.ts• L33-71 modules/…/index.ts• L95-137 modules/…/index.ts• L5-23 modules/…/index.ts• L119-142 modules/…/index.ts• L215-281

Canvas and presentation contexts

The canvas API keeps drawing targets separate from the device. A CanvasContext supplies a current framebuffer from an HTML or offscreen canvas. A PresentationContext tracks a destination canvas and presents completed output. Shared canvas tracking covers CSS size, physical pixel size, device-pixel ratio, visibility, and optional position changes. The surface starts resize, visibility, and pixel-ratio observers only after the derived context and device are ready. It defers drawing-buffer and device reconfiguration until the current framebuffer is requested, and it stops all observers when the surface is destroyed. This lets a frame use the latest surface size without callbacks running against a partial device or surviving its owner.

On WebGL, WebGLCanvasContext represents the browser's default framebuffer as a luma framebuffer. It creates that wrapper only when the frame asks for the current target and resizes it to the current drawing-buffer size. Destroying the context also releases that wrapper, so canvas presentation follows the device lifetime.

References: modules/…/canvas-context.ts• L8-16 modules/…/presentation-context.ts• L9-16 modules/…/canvas-surface.ts• L16-53 modules/…/canvas-surface.ts• L65-145 modules/…/canvas-surface.ts• L205-228 modules/…/canvas-surface.ts• L317-355 modules/…/canvas-surface.ts• L372-505 modules/…/webgl-canvas-context.ts• L11-57

Platform device mappings

The shared Device contract is backed by one device wrapper per active native context or device. The wrappers translate resource creation, submission, loss, and capability reporting into the rules of the selected platform while keeping application-facing types stable.

WebGL device

WebGLDevice maps the shared API onto one WebGL2 context. It discovers extensions, limits, formats, and GPU identity, creates the WebGL resource family, and turns the default command encoder into ordered native work. WebGL has one canvas context per device, does not provide compute pipelines or render bundles, and uses explicit submission to flush the recorded command buffer.

WebGL context creation first asks for WebGL2 with the requested performance and canvas attributes. If the application allows software rendering, the backend retries without the hardware-only performance guard. WebGL1 is not accepted as a fallback. Context loss and restoration events feed the shared loss contract, while resource creation rejects work after loss.

References: modules/…/webgl-device.ts• L81-113 modules/…/webgl-device.ts• L152-282 modules/…/webgl-device.ts• L284-428 modules/…/create-browser-context.ts• L21-94

WebGL state tracking

The WebGL state tracker keeps the mutable context state used by luma.gl visible to resource and pass code. It avoids repeated native queries, supports temporary state scopes through push and pop, and invalidates cached bindings when tracked native objects are deleted. Reattachment takes a fresh state snapshot so the wrapper does not restore assumptions from an earlier owner.

References: modules/…/webgl-state-tracker.ts• L18-136 modules/…/webgl-state-tracker.ts• L138-187 modules/…/webgl-state-tracker.ts• L190-331 modules/…/webgl-device.ts• L257-265

WebGPU device

WebGPUAdapter selects the native adapter and requests the feature and limit profile. WebGPUDevice then wraps the native GPUDevice, exposes its features and limits through the shared types, and records the effective feature level in device information. It supports asynchronous render and compute pipeline creation, external textures, render bundles, compute work, and native queue submission.

An attached GPU device keeps its application-selected feature and limit view, and repeated attachment returns the live wrapper for that native handle. A device that is already lost is rejected or retried during creation. Loss removes the wrapper from the handle map, while destruction releases the native device only when luma.gl owns it.

WebGPU CPU-to-buffer writes are placed into the same command stream as draw and dispatch work through transient staging buffers. Those buffers remain alive until submitted work completes. This preserves ordering without exposing the queue details to code that uses the shared device API.

References: modules/…/webgpu-adapter.ts• L187-369 modules/…/webgpu-adapter.ts• L386-389 modules/…/webgpu-device.ts• L77-170 modules/…/webgpu-device.ts• L189-314 modules/…/webgpu-device.ts• L318-475

GPU resource model

Core models GPU objects as device-bound resources with common identity, ownership, debug, and destruction behavior. The main resource groups are:

Resource groupPurpose
DataBuffers and textures hold GPU data. Texture views, samplers, and external textures describe how data is used.
ProgramsShaders provide stage code. Render and compute pipelines define how that code runs.
TargetsFramebuffers and canvas contexts provide render attachments.
WorkCommand encoders record copies and passes. Render and compute passes record draw or dispatch work.
Queries and reuseQuery sets and fences support timing or completion. Factories reuse equivalent shaders and pipelines when enabled.

Resource lifecycle

DeviceResource in modules/…/device-resource.ts is the common device-bound layer above the general Resource life cycle. Each resource belongs to one device, has a debug id, can hold application data, and may wrap a native handle supplied by the backend or by the application. Explicit destroy releases the resource and its attached resources. The device-resource layer also records created and active resources and tracks owned and referenced GPU memory for diagnostics. Borrowed handles are reference-only: their memory can appear as external GPU memory in reports, but luma does not claim ownership of their native lifetime.

References: modules/…/resource.ts• L80-168 modules/…/device-resource.ts• L81-168 modules/…/device-resource.ts• L178-299 modules/…/device-resource.ts• L364-420 modules/…/buffer.spec.ts• L167-245 modules/…/texture.spec.ts• L170-299

Data resources

Buffers represent byte data for vertex, index, uniform, storage, copy, and indirect use. Textures represent images, depth data, storage data, and render targets across common dimensions and formats. Both expose writes and reads through the shared API, while each device decides which operations its native API can support. Texture transfers can address mip levels, cube faces, array layers, or 3D slices with explicit row layout. The shared read paths return the same logical texel data across WebGL and WebGPU.

Texture transfer options describe a region and its CPU or GPU memory layout. The texture normalizes the mip extent and subresource range, computes format-dependent alignment, and rejects rows that cannot contain the requested region. Color readback has a defined first-pass scope: it accepts uncompressed color formats and the full color aspect for the supported texture dimensions.

References: modules/…/buffer.ts• L11-29 modules/…/buffer.ts• L51-117 modules/…/texture.ts• L136-178 modules/…/texture.ts• L359-440 modules/…/texture.ts• L587-685 modules/…/texture-formats.ts• L88-112 modules/…/buffer.spec.ts• L379-623 modules/…/texture.spec.ts• L670-934 modules/…/texture.spec.ts• L996-1298

Dynamic resource wrappers

The optional dynamic resource layer gives application and engine code a stable object while its current GPU resource changes. It is exported from modules/…/index.ts rather than the core root entry point, so callers opt into conveniences for resources that load asynchronously, resize, or need a changing backing object.

WrapperRole
DynamicBufferKeeps a stable buffer-like handle while replacing its backing Buffer on resize. It supports range bindings, read and write helpers, optional CPU debug data, and a generation value for binding-cache invalidation.
DynamicTextureLoads texture data that may contain nested promises, creates the texture and its view and sampler, and exposes a ready state. It supports common texture dimensions, explicit or generated mip chains, resize, subresource updates, and readback.

The wrappers preserve the core resource model underneath. A buffer resize creates a new immutable buffer and can copy a chosen prefix of the old contents. A texture resize clones the immutable texture without copying its contents, so the caller must re-upload data when needed. Generation and update timestamps let higher layers detect identity or content changes without replacing their application-level reference.

References: modules/…/index.ts• L5-8 modules/…/dynamic-buffer.ts• L52-87 modules/…/dynamic-buffer.ts• L253-337 modules/…/dynamic-texture.ts• L61-79 modules/…/dynamic-texture.ts• L134-265 modules/…/dynamic-texture.ts• L267-370

Texture views and samplers

Textures are immutable descriptions of storage. A clone creates a separate texture with the same settings and can change its size, while a texture view selects how existing storage is used. A texture may have a default sampler; omitted sampler properties can use a device-shared default, while explicit sampler properties or a sampler object preserve an application-specific choice and ownership. Samplers describe address, filter, level-of-detail, comparison, and anisotropy behavior as a separate immutable resource.

References: modules/…/texture.ts• L309-340 modules/…/texture.ts• L730-743 modules/…/sampler.ts• L9-32 modules/…/texture.spec.ts• L37-72 modules/…/texture.spec.ts• L301-361

Shader and pipeline resources

Shaders hold stage source and report compilation state and compiler messages. A render pipeline combines shader stages with shader bindings, vertex layout, attachment formats, and fixed render state. A compute pipeline provides the parallel-work counterpart. Applications use the pipeline as the stable description of how resources and shader stages work together.

References: modules/…/shader.ts• L12-28 modules/…/shader.ts• L31-67 modules/…/render-pipeline.ts• L25-77 modules/…/render-pipeline.ts• L79-124

Command and pass model

Core records GPU work before submission. A command encoder groups copies and render or compute passes, finish produces a command buffer, and the device submits that buffer. This model gives backends one place to preserve ordering and lets applications use the same frame structure on WebGL and WebGPU. WebGL maps the shared pass contract to context state and immediate native draws, while WebGPU records native pass commands. Cross-backend conformance checks protect the order of encoded writes, copies, and passes.

sequenceDiagram
  participant App as Application
  participant D as Device
  participant E as CommandEncoder
  participant P as Render or Compute Pass
  participant G as GPU backend
  App->>D: create or use default encoder
  App->>E: begin pass and record work
  E->>P: set targets, pipeline, bindings, and inputs
  App->>P: draw or dispatch
  App->>E: finish()
  E-->>App: CommandBuffer
  App->>D: submit(CommandBuffer)
  D->>G: execute ordered work

Render passes

RenderPass describes one rendering scope. It selects the framebuffer, clear and depth rules, pipeline, bindings, and vertex array before draw calls. It also exposes indirect draws, reusable render bundles where supported, occlusion queries, and debug markers. A render pass can resolve multisampled color targets and can change viewport, scissor, blend, stencil, and color-mask state while it runs. RenderBundleEncoder records immutable reusable draw commands for compatible WebGPU passes; its attachment formats and sample count are fixed when recording, and it inherits dynamic state from the pass that executes it. The shared draw contract covers indexed offsets and zero draw counts across WebGL and WebGPU.

References: modules/…/render-pass.ts• L20-92 modules/…/render-pass.ts• L123-170 modules/…/render-bundle.ts• L14-43 modules/…/render-bundle.ts• L45-117 modules/…/parameters.ts• L166-191 modules/…/webgl-render-pass.ts• L56-115 modules/…/webgl-render-pass.ts• L132-285 modules/…/webgpu-render-pass.ts• L49-125 modules/…/webgpu-render-pass.ts• L139-285 modules/…/device-draw-conformance.spec.ts• L85-141 modules/…/device-draw-conformance.spec.ts• L143-222

Command encoding

CommandEncoder records copies, pass work, query results, and debug markers without requiring immediate submission. A finished encoder becomes a single-use command buffer. Device-level writes that use an encoder remain in the same ordered command stream as copies and passes.

When timestamp queries are available, the encoder can assign begin and end slots to passes, resolve their results, and report the summed GPU duration. A timestamp snapshot can retain the results and the CPU-to-GPU clock correlation for later interpretation, so a query set can be reused only after the current encoding's results are captured.

References: modules/…/command-encoder.ts• L15-28 modules/…/command-encoder.ts• L155-217 modules/…/command-encoder.ts• L219-294 modules/…/device-command-order-conformance.spec.ts• L11-95 modules/…/device.spec.ts• L177-208

Portable data model

Core also defines the data contracts that make shader inputs and texture data portable. These contracts describe types and layouts in backend-neutral terms, then let a device answer which formats and operations are valid on the current GPU.

Features, limits, and formats

Features and limits describe optional GPU behavior and maximum resource sizes. Texture format metadata describes channels, data type, packing, compression, and memory layout. Device capability queries combine that generic metadata with device features to report whether a format can be created, sampled, filtered, rendered to, blended, or used for storage.

References: modules/…/device.ts• L108-180 modules/…/device.ts• L297-381 modules/…/device.ts• L600-660 modules/…/texture-formats.ts• L31-112 modules/…/device.spec.ts• L51-86

Shader layouts

Shader layout types describe attributes, bindings, uniform blocks, samplers, textures, and storage resources. Buffer layout types describe how vertex data reaches shader attributes. Pipelines use these descriptions to connect application resources to shader inputs without exposing a backend-specific binding model. WGSL scanners discover binding declarations and shader interfaces while ignoring comments and preserving source positions for layout consumers.

References: modules/…/shader-layout.ts• L11-26 modules/…/shader-layout.ts• L64-80 modules/…/wgsl-binding-scan.ts• L5-16 modules/…/wgsl-interface-scan.ts• L5 modules/…/shader-types.ts• L5-15 modules/…/shader-type-decoder.ts• L5-15 modules/…/shader-block-layout.ts• L5-10

Shared array types

The core type layer gives resource and data APIs one vocabulary for numeric arrays. It keeps ordinary typed arrays separate from 64-bit integer arrays and provides a float16 constructor that uses the native type when the runtime supports it, with a Uint16Array fallback for representation-level compatibility. Small type guards distinguish typed arrays from ordinary numeric arrays at API boundaries.

References: modules/…/types.ts• L5-44 modules/…/is-array.ts• L5-28

Shader and vertex data types

Data types describe the physical values stored in vertex and pixel data, including integer, floating-point, and normalized forms. Decoder utilities map those forms to shader-visible types, byte sizes, and compatible typed-array constructors. Vertex formats add component count and attribute interpretation, including formats that are only valid on WebGL. Shader type aliases and composite types then describe scalar, vector, matrix, struct, and array values used by shader layouts.

References: modules/…/data-types.ts• L5-45 modules/…/decode-data-types.ts• L18-99 modules/…/vertex-formats.ts• L11-102 modules/…/shader-types.ts• L5-15 modules/…/shader-type-decoder.ts• L5-15

Uniform data

The portable uniform helpers turn structured application values into packed block data. UniformStore owns block definitions and optional GPU buffers, UniformBlock tracks changed values, and ShaderBlockWriter flattens nested values according to a declared layout. The uniform value types support scalar values, numeric arrays, nested structures, and arrays. This gives render code one update path for uniform data while respecting the packing rules expected by the shader.

References: modules/…/uniforms.ts• L5-22 modules/…/uniform-block.ts• L14-28 modules/…/uniform-block.ts• L53-84 modules/…/shader-block-writer.ts• L19-23 modules/…/shader-block-writer.ts• L48-92 modules/…/uniform-store.ts• L18-50 modules/…/uniform-store.ts• L72-125 modules/…/shader-block-layout.ts• L5-10

Resource reuse and diagnostics

Core provides optional shared factories and global diagnostics for repeated resource work. The shader factory reuses equivalent shader resources. The pipeline factory reuses equivalent render and compute pipelines, shares pending asynchronous creation, and keeps the cache device-scoped. Resource counters, memory estimates, logging, and device error reports help an application find leaks or backend errors without changing its rendering model.

Shader and pipeline factories

Factories are device-scoped caches with reference counts. They are enabled through device properties, so applications can choose reuse when creation cost matters and can choose cache eviction when many distinct resources are created. Equivalent asynchronous requests share one pending compilation, while synchronous and asynchronous results join the same cache when they complete. A compilation scope can collect independent asynchronous pipeline work during one construction phase. WebGL can also share the linked program beneath multiple pipeline wrappers. A release balances a factory request rather than replacing normal resource ownership rules.

References: modules/…/shader-factory.ts• L10-20 modules/…/shader-factory.ts• L40-95 modules/…/pipeline-factory.ts• L22-65 modules/…/pipeline-factory.ts• L103-171 modules/…/pipeline-factory.ts• L173-253 modules/…/pipeline-factory.ts• L287-343 modules/…/pipeline-factory.ts• L368-465

Debug and loss handling

The device exposes shared logging, error reporting, debug breaks, resource statistics, and a loss promise. The global luma.log instance provides the logging control used by device creation and factory diagnostics. StatsManager creates named stats on demand and keeps the main GPU time and memory measures in a stable order. Applications should treat a lost device as a system state change and use the reported reason and message for diagnosis rather than parsing the message as a protocol. Resource and memory counters cover both owned allocations and resources that wrap external native handles. Debug GPU timing is managed by the device and is reflected in the command encoder's profiling query set.

References: modules/…/log.ts• L5-8 modules/…/stats-manager.ts• L7-54 modules/…/device.ts• L94-106 modules/…/device.ts• L665-745 modules/…/device-resource.ts• L191-299 modules/…/luma.ts• L54-64 modules/…/device.spec.ts• L22-39 modules/…/device.spec.ts• L177-208

Test device utilities

The test device utilities provide the same device-facing contract without requiring every test to create a live GPU context. getTestDevice and its related helpers create cached WebGL, WebGPU, or null devices, refresh cached devices after loss, and expose feature-level WebGPU choices. The null device accepts resource and render-pass lifecycles for non-rendering tests but reports unsupported GPU work instead of pretending to execute it. The old synchronous WebGL helper remains only as a deprecated compatibility export.

References: modules/…/index.ts• L5-21 modules/…/create-test-device.ts• L41-129 modules/…/create-test-device.ts• L153-177 modules/…/create-test-device.ts• L256-280 modules/…/register-devices.ts• L5-9 modules/…/null-adapter.ts• L8-35 modules/…/null-device.ts• L48-75 modules/…/null-device.ts• L91-170 modules/…/null-render-pass.ts• L18-65 modules/…/null-command-encoder.ts• L21-78 modules/…/test-utils-legacy.ts• L5-6

The core API is the contract used by the platform and engine layers. Continue with Rendering runtime platforms, Engine render loop, WebGL backend, or WebGPU backend to follow the device lifecycle into a runtime or a specific platform.

Change checklist

When these files or sections are changed, remember to consider these:

  • Changes to Device creation or adapter selection must preserve explicit backend requests, best-available fallback order, adapter registration, handle attachment, feature-level selection, and the page-load gate.
  • Changes to shared device defaults must preserve debug precedence and the policy used by both direct device creation and adapter attachment.
  • Changes to WebGPU feature-level negotiation must keep adapter request options, required features, required limits, and the reported effective feature level aligned.
  • Changes to device loss types or handling must preserve the unknown and destroyed meanings and the rule that application code does not parse the diagnostic message.
  • Changes to resource props or ownership must stay aligned with borrowed native handles, external memory statistics, attached-resource destruction, and explicit destruction in both backend resource families.
  • Changes to WebGL context creation must preserve WebGL2-only support, the hardware-first and software fallback policy, context event cleanup, and the device ownership decision.
  • Changes to WebGL state tracking must preserve fresh snapshots on reattachment, cached getter and setter behavior, state-stack restoration, and invalidation after tracked object deletion.
  • Changes to the public export maps must keep the package root and API entry point aligned for device resources, shader types, vertex formats, texture formats, and their decoders.
  • Changes to texture read or write options must preserve byte offsets, row padding, mip extents, layer or slice selection, and parity between WebGL and WebGPU paths.
  • Changes to shader layouts, buffer layouts, vertex formats, or texture formats must remain consistent with pipeline binding and device capability checks.
  • Changes to data type decoders or float16 helpers must keep physical buffer formats, shader-visible types, byte sizes, and runtime array constructors in agreement.
  • Changes to command encoding must preserve pass ordering and the rule that helper operations record on the supplied encoder when one is active.
  • Changes to WebGPU staging uploads must preserve command ordering and defer transient buffer destruction until submitted work is complete.
  • Changes to timestamp profiling must preserve pass slot assignment, query-set capacity checks, result capture before query reuse, and CPU-to-GPU clock correlation.
  • Changes to draw argument handling must preserve indexed offsets, zero-count behavior, and dynamic state across both backend families.
  • Changes to render-pass targets or dynamic parameters must preserve resolve-target compatibility, viewport and scissor behavior, blend and stencil values, and the split between pass state and pipeline state.
  • Changes to render bundle recording must preserve attachment format, depth/stencil read-only state, sample-count compatibility, immutable finish behavior, and the restriction against pass-only state or queries.
  • Changes to uniform block packing must keep layout generation and binary writing in agreement for std140, WGSL uniform, and WGSL storage data.
  • Changes to canvas sizing or presentation must preserve the link between observed CSS size, physical pixel size, drawing-buffer size, and the current framebuffer. Observer startup must follow device setup, and observer teardown must follow surface destruction.
  • Changes to canvas pixel-size policy must preserve the distinction between exact physical-pixel observation and CSS-size times device-pixel-ratio calculation, including updates when only the device-pixel ratio changes.
  • Changes to pending canvas resize handling must preserve the rule that a newer owner resize takes precedence over a stale deferred request before device reconfiguration.
  • Changes to pipeline cache keys or async compilation scopes must keep WebGPU attachment formats in the key, keep WebGL shared-program keys separate from wrapper-only state, and balance every cache request with one release.
  • Changes to logging or stats initialization must preserve the global instance, device resource counts, canonical resource categories, external memory buckets, and stable stat ordering used by diagnostics.
  • Changes to buffer or texture readback must preserve exact requested ranges and the distinction between owned and external GPU memory in diagnostics.
  • Changes to dynamic resource exports must keep the wrappers opt-in and preserve the distinction between the stable wrapper and its current core resource.
  • Changes to dynamic buffer or texture identity must preserve generation updates so binding caches can resolve the current resource.
  • Changes to dynamic texture data normalization must preserve base-level presence, matching dimensions and formats across slices, and valid mip limits for compressed formats.
  • Changes to dynamic resource resizing must preserve buffer ownership rules and the fact that dynamic texture resize does not copy texture contents.
  • Changes to test utility exports or their moved paths must preserve adapter registration, backend-specific device availability, null-device behavior, loss-aware cache refresh, and the deprecated synchronous compatibility export.

Important failure modes

TriggerConsequenceGuard
No supported adapter is registeredDevice creation fails before application rendering starts.Import the required backend package or pass a supported adapter to createDevice.
A requested WebGPU feature level or required limit is not availableWebGPU device creation fails instead of producing the requested capability profile.Request only the feature level, optional features, and limits that the target adapter can provide.
A WebGPU device is returned already lostCreation fails or retries once with a fresh adapter instead of returning an unusable wrapper.Treat creation failure as a capability or platform error and create resources only after the returned device is live.
WebGL2 is unavailable and software rendering is disallowedBrowser context creation fails even when WebGL1 is present.Use a WebGL2-capable browser and set failIfMajorPerformanceCaveat: false only when software rendering is acceptable.
Debug mode is expected from NODE_ENV while a URL or log setting overrides itBrowser debug behavior differs from the assumed environment policy.Apply the URL, explicit log, and environment precedence defined by the shared defaults.
An existing context or device has an unsupported handle typeattachDevice cannot select an adapter and device creation fails.Attach a WebGL2 context or WebGPU device supported by a registered adapter.
A WebGL context is lost while resources are being createdAllocation is rejected instead of registering resources against an unusable context.Check the shared loss state and recreate the device and its resources after loss.
A WebGL state cache is stale after reattachment or native deletionA setter can be skipped or a saved state can restore a deleted handle.Snapshot state on reattachment and keep deletion invalidation enabled.
A texture format is used without checking device capabilitiesCreation, filtering, rendering, or storage can fail on one backend or GPU.Use the device format capability queries before selecting the format or operation.
A texture readback requests a compressed, depth, stencil, or non-color aspect through the color-read pathThe read request is rejected instead of returning the requested data.Use an uncompressed color format with the full color aspect, or use a backend path that supports the requested data.
A resource is used after its device or resource is destroyedNative work can fail or produce invalid output.Keep resource lifetime inside the device lifetime and release attached resources with their owner.
A borrowed or externally created handle is treated as luma-ownedApplication-owned native state can be changed or destroyed unexpectedly.Mark ownership correctly and manage the external handle's lifetime outside the resource wrapper.
A pipeline is used while shader or link work has failedDraw or dispatch setup cannot produce valid GPU work.Check compilation and link state and use compiler messages for diagnosis.
A cached pipeline key omits an attachment format or includes the wrong WebGL stateA cache hit can reuse an invalid WebGPU pipeline or reduce safe WebGL program reuse.Keep backend-specific immutable inputs in the right cache key and keep shared-program keys limited to link inputs.
A cached shader or pipeline is released more times than it was requestedThe cache count becomes invalid and later reuse can be unsafe.Balance factory create and release calls.
An asynchronous pipeline compilation scope is nested or closed with the wrong scopePipeline construction fails before the collected work can be awaited.Open one device-scoped scope at a time and close that exact scope before awaiting it.
A texture upload has an invalid row layout or targets the wrong subresourceData is rejected or reaches the wrong mip level, layer, face, or slice.Compute the layout for the requested region and pass matching offsets, row sizes, and extents.
A frame uses a stale canvas size or observers start before the device is readyOutput can be stretched, clipped, or rendered into the wrong target size.Start observers after device setup, stop them during surface destruction, and read the current framebuffer after resize tracking has updated it.
A command helper submits work outside the active encoderCopies or writes can run out of order relative to later passes.Record helper operations on the supplied encoder and submit the finished command buffer once.
A timestamp query set is reused before the encoder captures its resultsProfiling data can be overwritten or associated with the wrong encoding.Capture the timestamp snapshot before reuse and retain its clock correlation with the results.
A render bundle is executed with incompatible attachment formats or sample countReusable draw work cannot execute in the current render pass.Use bundles whose attachment formats and sample count match the pass.
A render bundle records pass-only state or is ended like a render passRecording fails or the bundle does not represent the intended reusable draw work.Set compatibility props at encoder creation, use pipeline, binding, vertex, draw, and debug commands only, and call finish.
A render pass uses resolve targets that do not match its multisampled attachmentsPresentation or resolve work fails or produces invalid output.Match resolve targets to the pass color attachments and use them only for supported multisample paths.
A draw uses an unintended zero count or index offsetA pass can draw nothing or select the wrong indexed data on one backend.Treat draw counts and offsets as part of the portable render contract.
A buffer read requests an invalid or misaligned rangeReadback can fail or return data for the wrong byte range.Validate the range and let the device choose aligned staging or mapping for the requested slice.
A dynamic buffer adopts a resource from another device or combines it with new data propsConstruction fails because the wrapper cannot safely define one backing resource.Adopt only a buffer from the supplied device and choose either adoption or new buffer data.
A dynamic resource is replaced without observing its generationCached bindings can continue to point at an old buffer, texture, view, or sampler.Compare generation values and refresh bindings when identity changes.
A dynamic texture is used before its asynchronous data is readyResource access can fail or a binding can resolve to no texture.Await ready or check the ready state before using the texture.
Dynamic texture slices omit mip level 0 or disagree on base size or formatTexture creation fails or the supplied mip chain is not valid for the texture.Provide a complete compatible base level for each slice and use one format and valid mip sizes.
A dynamic texture is resized and the caller expects old contents to remainThe new texture contains no copied image data.Re-upload the required subresources and regenerate mips after resize.
Automatic mipmaps are requested for a compressed dynamic textureMipmap generation is skipped and a warning is logged.Provide an explicit compatible mip chain or use an uncompressed format when automatic generation is required.
A test requests a backend that is unavailable or reuses a lost cached deviceThe test is skipped, fails during setup, or uses an unusable device.Use the asynchronous test-device helpers, filter unavailable devices, and refresh the cache after device loss.
A null-device test assumes unsupported GPU work executesThe test passes without checking the behavior it intends to cover, or it fails on an unsupported operation.Use the null device for lifecycle and contract checks, and expect compute, texture-copy, and render-bundle operations to be unsupported.

Key files

FileWhy to read it
modules/…/index.tsPublic export map for the core API, device-facing resources, portable types, and utilities.
modules/…/index.tsPackage-level exports that connect the core API and shader-type utilities to the rest of the module.
modules/…/index.tsOpt-in exports for dynamic buffer and texture conveniences.
modules/…/dynamic-buffer.tsStable buffer wrapper, resize and ownership behavior, range binding resolution, and debug mirroring.
modules/…/dynamic-texture.tsAsynchronous texture loading, mip and subresource handling, resize, sampler identity, and readback.
modules/…/luma.tsDevice creation, adapter selection, handle attachment, and backend registration entry points.
modules/…/adapter.tsBackend adapter contract and shared browser page-load boundary.
modules/…/device-defaults.tsShared device policy for performance, debug behavior, callbacks, and resource reuse.
modules/…/device.tsShared device capabilities, feature profiles, context creation, resource creation, submission, and loss contract.
modules/…/canvas-surface.tsShared canvas creation, size tracking, pixel-size policy, deferred drawing-buffer updates, observer lifetime, and framebuffer boundary.
modules/…/wgsl-binding-scan.tsWGSL binding declaration discovery used by portable shader layout work.
modules/…/wgsl-interface-scan.tsWGSL interface discovery used to relate shader inputs and outputs.
modules/…/resource.tsGeneral resource life cycle and attachment behavior.
modules/…/device-resource.tsDevice ownership, native handle borrowing, resource counters, and GPU memory tracking.
modules/…/texture.tsPortable texture storage, views, samplers, upload, layout, and readback contract.
modules/…/render-pass.tsShared render-pass targets, dynamic state, bindings, queries, bundles, and draw interface.
modules/…/render-bundle.tsReusable render command compatibility rules and encoder restrictions.
modules/…/parameters.tsShared raster, depth, blend, multisample, and dynamic pass state.
modules/…/command-encoder.tsCommand recording, pass creation, copies, profiling, and submission boundary.
modules/…/shader-layout.tsPortable resource binding and shader layout types.
modules/…/uniforms.tsScalar and nested uniform value contracts.
modules/…/types.tsShared array types and float16 runtime compatibility helpers.
modules/…/data-types.tsPhysical data types, normalization, shader-visible types, and typed-array relationships.
modules/…/vertex-formats.tsVertex attribute formats and their component and data-type rules.
modules/…/decode-data-types.tsMapping between physical data types, shader types, byte sizes, and array constructors.
modules/…/shader-block-layout.tsBackend-neutral shader block packing contract.
modules/…/texture-formats.tsTexture format metadata, capabilities, and memory layout types.
modules/…/pipeline-factory.tsDevice-scoped pipeline reuse, backend-specific cache keys, and asynchronous compilation sharing.
modules/…/log.tsGlobal luma logging instance used by core diagnostics.
modules/…/stats-manager.tsShared named stats and stable GPU time and memory metrics.
modules/…/index.tsPublic asynchronous test-device, null-device, type, copy, and resource tracking utilities.
modules/…/create-test-device.tsCached WebGL, WebGPU, and null test-device creation with loss refresh.
modules/…/null-device.tsNo-op device contract and supported versus unsupported test operations.
modules/…/null-render-pass.tsNull render-pass state and draw-order contract for non-rendering tests.
modules/…/test-utils-legacy.tsDeprecated synchronous WebGL compatibility export.
modules/…/webgl-device.tsWebGL device mapping, context lifetime, state setup, submission, loss, and shared resource creation.
modules/…/webgl-canvas-context.tsWebGL default framebuffer wrapper and drawing-buffer resize boundary.
modules/…/create-browser-context.tsWebGL2 context request, software fallback, and context event wiring.
modules/…/webgl-state-tracker.tsWebGL state cache, temporary state scopes, reattachment snapshots, and deletion invalidation.
modules/…/webgl-render-pass.tsWebGL mapping of the shared pass and draw contract.
modules/…/webgl-vertex-array.tsWebGL vertex layout, constant attributes, and buffer binding behavior.
modules/…/webgpu-adapter.tsWebGPU adapter selection, feature profiles, requested limits, attachment, and immediate-loss handling.
modules/…/webgpu-device.tsWebGPU device mapping, capability reporting, ownership, ordered uploads, submission, and loss.
modules/…/webgpu-render-pass.tsWebGPU mapping of framebuffers, bindings, draws, queries, and render bundles.
modules/…/luma.spec.tsGuarantees for adapter selection, handle attachment, debug failure reporting, and WebGL2 enforcement.
modules/…/device-command-order-conformance.spec.tsCross-backend guarantee for command write, copy, and pass order.
modules/…/device-draw-conformance.spec.tsCross-backend guarantee for portable draw arguments and dynamic render state.
modules/…/texture.spec.tsTexture view and sampler behavior, subresource transfer semantics, external image paths, and memory accounting.
modules/…/buffer.spec.tsBuffer data movement, range readback, ownership, and diagnostic counter behavior.