Class WebGLResourceRepository

A comprehensive repository for managing WebGL resources including buffers, textures, shaders, and framebuffers. This class provides a centralized interface for creating, managing, and disposing of WebGL resources while maintaining resource handles for efficient memory management.

const repository = WebGLResourceRepository.getInstance();
const textureHandle = repository.createTextureFromImageBitmapData(imageData, options);

Hierarchy (view full)

Implements

Properties

Accessors

Methods

__createDummyTextureInner addWebGLContext allocateTexture attachColorBufferCubeToFrameBufferObject attachColorBufferLayerToFrameBufferObject attachColorBufferToFrameBufferObject attachDepthBufferToFrameBufferObject attachDepthStencilBufferToFrameBufferObject attachStencilBufferToFrameBufferObject bindFramebuffer bindTexture bindTexture2D bindTexture2DArray bindTextureCube bindTextureSampler bindUniformBlock bindUniformBufferBase blitToTexture2dFromTexture2dArray blitToTexture2dFromTexture2dArray2 blitToTexture2dFromTexture2dArrayFake clearFrameBuffer createCompressedTexture createCompressedTextureFromBasis createCubeTexture createCubeTextureFromBasis createCubeTextureFromFiles createDummyBlackCubeTexture createDummyBlackTexture createDummyCubeTexture createDummyNormalTexture createDummyTexture createDummyWhiteTexture createFrameBufferObject createIndexBuffer createMultiviewFramebuffer createOrGetTextureSamplerClampToEdgeLinear createOrGetTextureSamplerClampToEdgeNearest createOrGetTextureSamplerRepeatAnisotropyLinear createOrGetTextureSamplerRepeatLinear createOrGetTextureSamplerRepeatNearest createOrGetTextureSamplerRepeatTriLinear createOrGetTextureSamplerShadow createRenderBuffer createRenderTargetTexture createRenderTargetTextureArray createRenderTargetTextureCube createShaderProgram createTexStorage2D createTextureArray createTextureFromDataUri createTextureFromHTMLImageElement createTextureFromImageBitmapData createTextureFromTypedArray createTextureSampler createTransformFeedback createUniformBuffer createVertexArray createVertexBuffer createVertexBufferAndIndexBuffer createVertexBufferFromTypedArray deleteFrameBufferObject deleteRenderBuffer deleteTexture deleteTransformFeedback deleteUniformBuffer deleteVertexArray deleteVertexBuffer deleteVertexDataResources generateMipmaps2d generateMipmapsCube generateWebGLContext getCanvasSize getGlslDataUBODefinitionString getGlslDataUBOVec4SizeString getGlslRenderTargetBeginString getPixelDataFromTexture getTexturePixelData getWebGLResource isSupportMultiViewVRRendering loadImageToMipLevelOfTexture2D rebuildProgramBySpector resizeCanvas setDrawTargets setUniform1iForTexture setUniformValue setUniformValueInner setVertexDataToPipeline setViewport setWebGLStateToDefault setWebGLTextureDirectly setupBasicUniformLocations setupUniformBufferDataArea setupUniformLocations switchDepthTest unbindFramebuffer unbindTextureSamplers updateIndexBuffer updateLevel0TextureAndGenerateMipmap updateTexture updateUniformBuffer updateVertexBuffer updateVertexBufferAndIndexBuffer getCgApiResourceRepository getInstance getWebGLResourceRepository getWebGpuResourceRepository

Properties

InvalidCGAPIResourceUid: -1 = -1

Invalid resource handle constant used to indicate failed resource creation or invalid resources

Accessors

Methods

  • Adds an existing WebGL2 context to the repository.

    Parameters

    • gl: WebGL2RenderingContext

      The WebGL2 rendering context to add

    • canvas: HTMLCanvasElement

      The HTML canvas element associated with the context

    • asCurrent: boolean

      Whether to set this context as the current active context

    Returns void

  • Allocates texture storage without uploading any image data. This method creates an empty texture with the specified format and dimensions.

    Parameters

    • params: {
          format: TextureFormatEnum;
          height: number;
          mipLevelCount: number;
          width: number;
      }

      Configuration object for texture allocation

      • format: TextureFormatEnum

        Internal format of the texture

      • height: number

        Height of the texture

      • mipLevelCount: number

        Number of mipmap levels to allocate

      • width: number

        Width of the texture

    Returns number

    The handle of the allocated texture

  • Attaches a specific face of a cube texture to a framebuffer object. This method is used for rendering to individual faces of cube maps.

    Parameters

    • framebuffer: FrameBuffer

      The framebuffer to attach to

    • attachmentIndex: number

      The color attachment index (0-based)

    • faceIndex: number

      The cube face index (0-5: +X, -X, +Y, -Y, +Z, -Z)

    • mipLevel: number

      The mip level to attach

    • renderable: IRenderable

      The cube texture to attach

    Returns void

  • Attaches a specific layer of a texture array to a framebuffer object. This method is useful for rendering to individual layers of a texture array.

    Parameters

    • framebuffer: FrameBuffer

      The framebuffer to attach to

    • attachmentIndex: number

      The color attachment index (0-based)

    • renderable: IRenderable

      The texture array to attach

    • layerIndex: number

      The layer index within the texture array

    • mipLevel: number

      The mip level to attach

    Returns void

  • Binds textures and samplers based on the composition type information. This method handles different texture types including 2D, cube, and texture arrays.

    Parameters

    Returns void

  • Binds a 2D texture to the specified texture slot.

    Parameters

    • textureSlotIndex: number

      The texture slot index to bind to

    • textureUid: number

      The handle of the texture to bind

    Returns void

  • Binds a 2D texture array to the specified texture slot.

    Parameters

    • textureSlotIndex: number

      The texture slot index to bind to

    • textureUid: number

      The handle of the 2D texture array to bind

    Returns void

  • Binds a cube texture to the specified texture slot.

    Parameters

    • textureSlotIndex: number

      The texture slot index to bind to

    • textureUid: number

      The handle of the cube texture to bind

    Returns void

  • Binds a texture sampler to the specified texture slot.

    Parameters

    • textureSlotIndex: number

      The texture slot index to bind to

    • samplerUid: number

      The handle of the sampler to bind, or -1 to unbind

    Returns void

  • Parameters

    • shaderProgramUid: number
    • blockName: string
    • blockIndex: number

    Returns void

  • Parameters

    • srcTextureUid: number
    • dstFboUid: number
    • dstWidth: number
    • dstHeight: number

    Returns void

  • Parameters

    • srcTextureUid: number
    • dstTextureUid: number
    • dstWidth: number
    • dstHeight: number

    Returns void

  • Parameters

    • srcTextureUid: number
    • dstFboUid: number
    • dstWidth: number
    • dstHeight: number

    Returns void

  • Creates a compressed texture from pre-transcoded texture data for multiple mip levels. This method handles various compressed texture formats and uploads the data to GPU.

    Parameters

    Returns Promise<number>

    Promise that resolves to the handle of the created compressed texture

  • Creates a compressed texture from a Basis Universal file. This method automatically detects the best compression format supported by the hardware and transcodes the Basis file accordingly.

    Parameters

    • basisFile: _BasisFile

      The Basis Universal file containing the compressed texture data

    • params: {
          border: number;
          format: EnumIO;
          type: ComponentTypeEnum;
      }

      Configuration object for texture creation

      • border: number

        Border width (must be 0 in WebGL)

      • format: EnumIO

        Pixel format (not used for compressed textures)

      • type: ComponentTypeEnum

        Data type (not used for compressed textures)

    Returns number

    The handle of the created compressed texture

  • Create Cube Texture from image files.

    Parameters

    • baseUri: string

      the base uri to load images;

    • mipLevelCount: number

      the number of mip levels (include root level). if no mipmap, the value should be 1;

    • isNamePosNeg: boolean
    • hdriFormat: EnumIO

    Returns Promise<[number, Sampler]>

    the WebGLResourceHandle for the generated Cube Texture

  • Parameters

    • width: number
    • height: number
    • samples: number

    Returns [number, number]

  • Creates or returns an existing texture sampler with clamp-to-edge wrapping and linear filtering. This method implements a singleton pattern for commonly used sampler configurations.

    Returns number

    The handle of the clamp-to-edge linear sampler

  • Creates or returns an existing texture sampler with clamp-to-edge wrapping and nearest filtering. This method implements a singleton pattern for commonly used sampler configurations.

    Returns number

    The handle of the clamp-to-edge nearest sampler

  • Creates or returns an existing texture sampler with repeat wrapping, anisotropic filtering, and linear filtering. This method implements a singleton pattern for commonly used sampler configurations.

    Returns number

    The handle of the repeat anisotropy linear sampler

  • Creates or returns an existing texture sampler with repeat wrapping and linear filtering. This method implements a singleton pattern for commonly used sampler configurations.

    Returns number

    The handle of the repeat linear sampler

  • Creates or returns an existing texture sampler with repeat wrapping and nearest filtering. This method implements a singleton pattern for commonly used sampler configurations.

    Returns number

    The handle of the repeat nearest sampler

  • Creates or returns an existing texture sampler with repeat wrapping and trilinear filtering. This method implements a singleton pattern for commonly used sampler configurations.

    Returns number

    The handle of the repeat trilinear sampler

  • Creates or returns an existing texture sampler configured for shadow mapping. This sampler uses nearest filtering and enables shadow comparison functionality.

    Returns number

    The handle of the shadow sampler

  • Creates and compiles a shader program from vertex and fragment shader source code. This method handles shader compilation, linking, and error reporting.

    Parameters

    • params: {
          attributeNames: AttributeNames;
          attributeSemantics: VertexAttributeEnum[];
          fragmentShaderStr: string;
          material: Material;
          onError?: ((message: string) => void);
          primitive: Primitive;
          vertexShaderStr: string;
      }

      Configuration object for shader program creation

      • attributeNames: AttributeNames

        Array of vertex attribute names

      • attributeSemantics: VertexAttributeEnum[]

        Array of vertex attribute semantics

      • fragmentShaderStr: string

        The fragment shader source code

      • material: Material

        The material associated with this shader program

      • OptionalonError?: ((message: string) => void)

        Optional error callback function

          • (message): void
          • Parameters

            • message: string

            Returns void

      • primitive: Primitive

        The primitive that will use this shader program

      • vertexShaderStr: string

        The vertex shader source code

    Returns number

    The handle of the created shader program, or InvalidCGAPIResourceUid on failure

    Error if no WebGL context is available

  • Creates a 2D texture with immutable storage using texStorage2D. This method allocates texture storage with the specified parameters.

    Parameters

    • params: {
          height: number;
          internalFormat: EnumIO | TextureParameterEnum;
          levels: number;
          width: number;
      }

      Configuration object for texture creation

      • height: number

        Height of the texture

      • internalFormat: EnumIO | TextureParameterEnum

        Internal format of the texture

      • levels: number

        Number of mipmap levels to allocate

      • width: number

        Width of the texture

    Returns number

    The handle of the created texture

  • Creates a 2D texture array with specified dimensions and format. Texture arrays allow storing multiple texture layers in a single texture object.

    Parameters

    • width: number

      Width of each texture layer

    • height: number

      Height of each texture layer

    • arrayLength: number

      Number of texture layers in the array

    • mipLevelCount: number

      Number of mipmap levels

    • internalFormat: TextureFormatEnum

      Internal format of the texture

    • format: EnumIO

      Pixel format of the source data

    • type: ComponentTypeEnum

      Data type of the source data

    • imageData: TypedArray

      Typed array containing the texture data

    Returns number

    The handle of the created texture array

  • Creates a texture from a data URI string. This method decodes base64-encoded image data and creates a GPU texture.

    Parameters

    • dataUri: string

      The data URI string containing encoded image data

    • options: {
          border: number;
          format: EnumIO;
          generateMipmap: boolean;
          internalFormat: TextureParameterEnum;
          level: number;
          type: ComponentTypeEnum;
      }

      Texture creation parameters

      • border: number

        Border width (typically 0)

      • format: EnumIO

        Pixel data format

      • generateMipmap: boolean

        Whether to automatically generate mipmaps

      • internalFormat: TextureParameterEnum

        Internal texture format for GPU storage

      • level: number

        Mipmap level (typically 0 for base level)

      • type: ComponentTypeEnum

        Component data type

    Returns Promise<number>

    Promise resolving to the texture resource handle

  • Creates a 2D texture from an HTML image element with specified parameters. This method allocates texture storage and uploads the image data to the GPU.

    Parameters

    • imageData: HTMLImageElement

      The HTML image element containing the image data

    • params: {
          border: number;
          format: EnumIO;
          generateMipmap: boolean;
          height: number;
          internalFormat: TextureParameterEnum;
          level: number;
          type: ComponentTypeEnum;
          width: number;
      }

      Configuration object for texture creation

      • border: number

        Border width (must be 0 in WebGL)

      • format: EnumIO

        Pixel format of the source data

      • generateMipmap: boolean

        Whether to generate mipmaps automatically

      • height: number

        Height of the texture

      • internalFormat: TextureParameterEnum

        Internal format of the texture

      • level: number

        Mipmap level (usually 0 for base level)

      • type: ComponentTypeEnum

        Data type of the source data

      • width: number

        Width of the texture

    Returns Promise<number>

    Promise that resolves to the handle of the created texture

  • Creates a 2D texture from ImageBitmap data with specified parameters. This method allocates texture storage and uploads the image data to the GPU.

    Parameters

    • imageData: ImageBitmapData

      The ImageBitmap or ImageBitmapSource data to upload

    • params: {
          border: number;
          format: EnumIO;
          generateMipmap: boolean;
          height: number;
          internalFormat: TextureFormatEnum;
          level: number;
          type: ComponentTypeEnum;
          width: number;
      }

      Configuration object for texture creation

      • border: number

        Border width (must be 0 in WebGL)

      • format: EnumIO

        Pixel format of the source data

      • generateMipmap: boolean

        Whether to generate mipmaps automatically

      • height: number

        Height of the texture

      • internalFormat: TextureFormatEnum

        Internal format of the texture

      • level: number

        Mipmap level (usually 0 for base level)

      • type: ComponentTypeEnum

        Data type of the source data

      • width: number

        Width of the texture

    Returns Promise<number>

    Promise that resolves to the handle of the created texture

  • Creates a 2D texture from a typed array with specified parameters. This method is useful for creating textures from raw pixel data.

    Parameters

    • imageData: TypedArray

      The typed array containing the pixel data

    • params: {
          border: number;
          format: EnumIO;
          generateMipmap: boolean;
          height: number;
          internalFormat: TextureFormatEnum;
          level: number;
          type: ComponentTypeEnum;
          width: number;
      }

      Configuration object for texture creation

      • border: number

        Border width (must be 0 in WebGL)

      • format: EnumIO

        Pixel format of the source data

      • generateMipmap: boolean

        Whether to generate mipmaps automatically

      • height: number

        Height of the texture

      • internalFormat: TextureFormatEnum

        Internal format of the texture

      • level: number

        Mipmap level (usually 0 for base level)

      • type: ComponentTypeEnum

        Data type of the source data

      • width: number

        Width of the texture

    Returns number

    The handle of the created texture

  • Creates a new vertex array object (VAO).

    Returns undefined | number

    The handle of the created VAO or undefined if creation failed

    Error if no WebGL context is available

  • Generates mipmaps for a 2D texture. Mipmaps improve rendering quality and performance by providing pre-filtered texture versions.

    Parameters

    • textureHandle: number

      Handle to the texture

    • width: number

      Base texture width in pixels

    • height: number

      Base texture height in pixels

    Returns void

  • Generates mipmaps for a cube texture. This creates mipmaps for all six faces of the cube texture.

    Parameters

    • textureHandle: number

      Handle to the cube texture

    • width: number

      Base texture width in pixels

    • height: number

      Base texture height in pixels

    Returns void

  • Generates a new WebGL2 context for the given canvas element.

    Parameters

    • canvas: HTMLCanvasElement

      The HTML canvas element to create the context for

    • asCurrent: boolean

      Whether to set this context as the current active context

    • OptionalwebglOption: WebGLContextAttributes

      Optional WebGL context attributes for context creation

    Returns WebGL2RenderingContext

    The created WebGL2 rendering context

  • Parameters

    • texUid: number
    • x: number
    • y: number
    • width: number
    • height: number

    Returns Uint8Array

  • Reads pixel data from a texture attached to a framebuffer. This allows CPU access to rendered texture data for analysis or processing.

    Parameters

    • textureHandle: number

      Handle to the texture to read from

    • width: number

      Width of the region to read

    • height: number

      Height of the region to read

    • frameBufferUid: number

      Handle to the framebuffer containing the texture

    • colorAttachmentIndex: number

      Index of the color attachment to read from

    Returns Promise<Uint8Array>

    Promise resolving to the pixel data as a Uint8Array

  • Loads image data to a specific mip level of an existing 2D texture. This method supports uploading data with row padding, extracting only the relevant pixels.

    Parameters

    • params: {
          data: TypedArray;
          format: TextureFormatEnum;
          height: number;
          mipLevel: number;
          rowSizeByPixel: number;
          textureUid: number;
          type: ComponentTypeEnum;
          width: number;
          xOffset: number;
          yOffset: number;
      }

      Configuration object for image loading

      • data: TypedArray

        The typed array containing the image data

      • format: TextureFormatEnum

        The format of the image

      • height: number

        Height of the image to copy

      • mipLevel: number

        The mip level to load the image to

      • rowSizeByPixel: number

        Size of each row in pixels (including padding)

      • textureUid: number

        The handle of the target texture

      • type: ComponentTypeEnum

        The data type of the image

      • width: number

        Width of the image to copy

      • xOffset: number

        X offset of the copy region

      • yOffset: number

        Y offset of the copy region

    Returns void

  • Parameters

    • this: RnWebGLProgram
    • updatedVertexSourceCode: string
    • updatedFragmentSourceCode: string
    • onCompiled: ((program: WebGLProgram) => void)
        • (program): void
        • Parameters

          • program: WebGLProgram

          Returns void

    • onError: ((message: string) => void)
        • (message): void
        • Parameters

          • message: string

          Returns void

    Returns boolean

  • Resizes the canvas to the specified dimensions. This operation may trigger viewport adjustments and resource reallocation.

    Parameters

    • width: number

      The new canvas width in pixels

    • height: number

      The new canvas height in pixels

    Returns void

  • Sets a uniform value for texture binding and binds the texture to the appropriate slot.

    Parameters

    • shaderProgram_: WebGLProgram

      The shader program to set the uniform for

    • semanticStr: string

      The semantic string identifying the uniform

    • value: any

      The value array containing texture slot index and texture data

    Returns void

  • Sets a uniform value in the shader program with automatic type detection and conversion. This method handles various composition types including matrices, vectors, and textures.

    Parameters

    • shaderProgram_: WebGLProgram

      The shader program to set the uniform for

    • semanticStr: string

      The semantic string identifying the uniform

    • firstTime: boolean

      Whether this is the first time setting this uniform

    • value: any

      The value to set (can be scalar, vector, matrix, or texture data)

    Returns boolean

    True if the uniform was successfully set, false otherwise

  • Internal method for setting uniform values with proper WebGL calls based on data type. This method handles the actual WebGL uniform* calls with appropriate type conversion.

    Parameters

    • shaderProgram: WebGLProgram

      The shader program to set the uniform for

    • semanticStr: string

      The semantic string identifying the uniform

    • info: ShaderSemanticsInfo

      The shader semantics information

    • isMatrix: boolean

      Whether the value is a matrix

    • componentNumber: number

      Number of components in the value

    • isVector: boolean

      Whether the value is a vector/array

    • param6: {
          w?: number | boolean;
          x: number | boolean | ArrayType;
          y?: number | boolean;
          z?: number | boolean;
      }

      Object containing the value components

      • Optionalw?: number | boolean

        Fourth value component (optional)

      • x: number | boolean | ArrayType

        Primary value component

      • Optionaly?: number | boolean

        Second value component (optional)

      • Optionalz?: number | boolean

        Third value component (optional)

    Returns boolean

    True if the uniform was successfully set, false if location not found

  • Configures vertex data for rendering by setting up VAO with VBOs and IBO. This method binds vertex arrays, index buffers, and configures vertex attribute pointers.

    Parameters

    • handles: {
          iboHandle?: number;
          vaoHandle: number;
          vboHandles: number[];
      }

      Object containing VAO, IBO, and VBO handles

      • OptionaliboHandle?: number

        Handle to the index buffer object (optional)

      • vaoHandle: number

        Handle to the vertex array object

      • vboHandles: number[]

        Array of vertex buffer object handles

    • primitive: Primitive

      The primitive object containing vertex attribute information

    • instanceIDBufferUid: number = CGAPIResourceRepository.InvalidCGAPIResourceUid

      Handle to instance ID buffer for instanced rendering (optional)

    Returns void

    Error if required buffers are not found

  • Sets up basic uniform locations required for data texture operations.

    Parameters

    • shaderProgramUid: number

      The handle of the shader program to configure

    Returns void

  • Sets up uniform locations for a shader program based on shader semantics information. This method extracts uniform locations from the compiled shader program and stores them for efficient access during rendering.

    Parameters

    • shaderProgramUid: number

      The handle of the shader program

    • infoArray: ShaderSemanticsInfo[]

      Array of shader semantics information

    • isUniformOnlyMode: boolean

      Whether to set up only uniform locations

    Returns WebGLProgram

    The WebGL program object with configured uniform locations

  • Updates an existing index buffer with new data from the accessor.

    Parameters

    • accessor: Accessor

      The accessor containing new index data

    • resourceHandle: number

      The handle of the index buffer to update

    Returns void

    Error if no WebGL context is available or IBO not found

  • Updates an existing vertex buffer with new data from the accessor.

    Parameters

    • accessor: Accessor

      The accessor containing new vertex data

    • resourceHandle: number

      The handle of the vertex buffer to update

    Returns void

    Error if no WebGL context is available or VBO not found