GLGraphicsBatcher

clay.opengl.GLGraphicsBatcher (Class)

OpenGL implementation of the graphics batcher for batched rendering.

This class handles all OpenGL rendering operations for batched geometry, including vertex buffer management, texture binding, shader operations, render targets, and batch rendering optimization.

Key features:

  • Efficient batch rendering with automatic buffer management
  • Support for multi-texture batching
  • Render-to-texture capabilities
  • Stencil buffer operations for masking
  • Custom shader attribute support
  • Scissor testing for clipping
  • Blend mode management

The class uses a buffer cycling system to avoid GPU stalls and provides platform-specific optimizations for different targets (web, desktop, mobile).

This class implements clay.spec.GraphicsBatcher for compile-time API checking. All methods are inlined for performance.

Static Members

MAX_VERTS_SIZE: Int

Maximum number of vertices that can be stored in a single buffer.


MAX_INDICES: Int

Maximum number of indices that can be stored in a single buffer.


MAX_BUFFERS: Int

Maximum number of buffer sets to cycle through. Buffer cycling prevents GPU stalls by using multiple buffer sets.


ATTRIBUTE_POS: Int

Vertex attribute location for position data (x, y, z).


ATTRIBUTE_UV: Int

Vertex attribute location for texture coordinate data (u, v).


ATTRIBUTE_COLOR: Int

Vertex attribute location for color data (r, g, b, a).


defaultTextureId: clay.TextureId

Default texture ID to use when no texture is bound. On web targets, WebGL requires a texture to be bound, so this should be set to a 1x1 white texture. On native targets, this can be left as null/0.

Instance Members

initBuffers(): Void

Initializes the vertex and index buffers for rendering.

This method sets up the buffer management system and prepares the first set of buffers for use. Should be called before any rendering operations begin.


beginRender(): Void

Begins a rendering pass by enabling vertex attributes.

Enables the core vertex attributes used by all shaders:

  • Position (x, y, z)
  • Texture coordinates (u, v)
  • Color (r, g, b, a)

Additional attributes are enabled dynamically based on the active shader.


endRender(): Void

Ends the current rendering frame.

Performs any cleanup or finalization needed after all draw operations. Currently a no-op for OpenGL, but provided for API completeness.


setVertexLayout(hasTextureSlot: Bool, customFloatAttributesSize: Int): Void

Configures the vertex layout for the current shader.

This determines how vertex data is structured in the buffer, including support for multi-texture batching and custom attributes.

The vertex size calculation includes:

  • 3 floats for position (x, y, z)
  • Custom float attributes defined by the shader
  • 1 float for texture slot (if multi-texturing is enabled)
Name Type Description
hasTextureSlot Bool Whether vertices include a texture slot for multi-texture batching
customFloatAttributesSize Int Number of custom float attributes per vertex

setCustomAttributes(attributes: Array<Dynamic>): Void

Sets the custom shader attributes for vertex layout.

These attributes define how custom per-vertex data is structured in the position buffer. Used by shaders that require additional vertex data beyond position, UV, and color.

Name Type Description
attributes Array<Dynamic> Array of shader attributes, or null for none

putVertex(x: Float, y: Float, z: Float): Void

Adds a vertex position to the current batch.

On C++ targets, uses direct memory access for performance. On other targets, uses array access.

Name Type Description
x Float X coordinate in screen space
y Float Y coordinate in screen space
z Float Z coordinate for depth ordering

putVertexWithTextureSlot(x: Float, y: Float, z: Float, textureSlot: Float): Void

Adds a vertex position with texture slot for multi-texture batching.

Name Type Description
x Float X coordinate in screen space
y Float Y coordinate in screen space
z Float Z coordinate for depth ordering
textureSlot Float Texture slot index for multi-texture batching

putUVs(u: Float, v: Float): Void

Adds texture coordinates for the current vertex.

Name Type Description
u Float Horizontal texture coordinate (0.0 to 1.0)
v Float Vertical texture coordinate (0.0 to 1.0)

putColor(r: Float, g: Float, b: Float, a: Float): Void

Adds color data for the current vertex.

Colors are stored as floating-point values from 0.0 to 1.0. The color will be interpolated across the triangle/line.

Name Type Description
r Float Red component (0.0 to 1.0)
g Float Green component (0.0 to 1.0)
b Float Blue component (0.0 to 1.0)
a Float Alpha component (0.0 to 1.0)

putIndex(i: Int): Void

Adds an index to the index buffer. Indices reference vertices in the vertex buffer to form primitives.

Name Type Description
i Int Vertex index

putFloatAttribute(index: Int, value: Float): Void

Adds a custom float attribute value for the current vertex. Used with custom shaders that require additional per-vertex data.

Name Type Description
index Int Attribute index (as defined by the shader)
value Float Attribute value

endFloatAttributes(): Void

Signals the end of custom float attributes for the current vertex. Must be called after all putFloatAttribute() calls for a vertex.


getNumVertices(): Int

Gets the number of vertices currently in the buffer.

Returns Description
Int Current vertex count

shouldFlush(numVerticesAfter: Int, numIndicesAfter: Int): Bool

Checks if the buffer should be flushed before adding more geometry.

Returns true if adding the specified number of vertices or indices would exceed buffer capacity, indicating that the current batch should be sent to the GPU before continuing.

Name Type Description
numVerticesAfter Int Number of vertices to be added
numIndicesAfter Int Number of indices to be added
Returns Description
Bool True if flush is needed, false otherwise

remainingVertices(): Int

Gets the remaining vertex capacity in the buffer.

Returns Description
Int Number of vertices that can still be added

remainingIndices(): Int

Gets the remaining index capacity in the buffer.

Returns Description
Int Number of indices that can still be added

hasAnythingToFlush(): Bool

Checks if there is any geometry in the buffer to flush.

Returns Description
Bool True if there are vertices/indices waiting to be submitted

flush(): Void

Flushes the current batch of vertices to the GPU.

This is the core rendering method that:

  1. Creates GPU buffers from the accumulated vertex data
  2. Configures vertex attributes for the shader
  3. Handles multi-texture batching if supported
  4. Sets up custom shader attributes
  5. Issues the draw call to render all triangles/lines
  6. Cleans up temporary buffers
  7. Prepares for the next batch

The method uses temporary GPU buffers that are deleted after rendering to avoid memory leaks. Buffer data is uploaded as STREAM_DRAW for optimal performance with dynamic geometry.


clear(r: Float, g: Float, b: Float, a: Float, clearDepth: Bool): Void

Clears the current render target.

Name Type Description
r Float Red component of clear color (0.0 to 1.0)
g Float Green component of clear color (0.0 to 1.0)
b Float Blue component of clear color (0.0 to 1.0)
a Float Alpha component of clear color (0.0 to 1.0)
clearDepth Bool Whether to also clear the depth buffer

setViewport(x: Int, y: Int, width: Int, height: Int): Void

Sets the viewport dimensions.

Name Type Description
x Int Left edge of viewport
y Int Bottom edge of viewport
width Int Viewport width in pixels
height Int Viewport height in pixels

setPrimitiveType(primitiveType: Int): Void

Sets the primitive type for rendering.

Name Type Description
primitiveType Int 0 for triangles, 1 for lines

enableBlending(): Void

Enables alpha blending for subsequent draw operations.


disableBlending(): Void

Disables alpha blending for subsequent draw operations.


setBlendFuncSeparate(srcRgb: Int, dstRgb: Int, srcAlpha: Int, dstAlpha: Int): Void

Sets separate blend functions for RGB and alpha channels.

Name Type Description
srcRgb Int Source blend factor for RGB channels
dstRgb Int Destination blend factor for RGB channels
srcAlpha Int Source blend factor for alpha channel
dstAlpha Int Destination blend factor for alpha channel

setActiveTexture(slot: Int): Void

Sets the active texture slot for multi-texturing.

Name Type Description
slot Int Texture slot index (0-based)

bindTexture(textureId: clay.TextureId): Void

Binds a texture to the current texture slot.

Name Type Description
textureId clay.TextureId Texture identifier to bind

bindNoTexture(): Void

Unbinds any texture from the current texture slot. Uses the defaultTextureId which should be set to a white texture on web targets.


shouldFlipRenderTargetY(): Bool

Returns true if render target MVP matrix should be flipped vertically.

Returns
Bool

setRenderTarget(renderTarget: clay.RenderTarget): Void

Sets the render target for subsequent draw operations.

Name Type Description
renderTarget clay.RenderTarget Render target to draw into, or null for main framebuffer

blitRenderTargetBuffers(renderTarget: clay.RenderTarget, width: Int, height: Int): Void

Resolves MSAA render target buffers. Called when switching away from an antialiased render target.

Name Type Description
renderTarget clay.RenderTarget The render target to resolve
width Int Width of the render target
height Int Height of the render target

useShader(shader: clay.GpuShader): Void

Activates a shader program for subsequent draw operations.

Name Type Description
shader clay.GpuShader Shader program to use

setProjectionMatrix(matrix: clay.buffers.Float32Array): Void

Sets the projection matrix uniform.

Name Type Description
matrix clay.buffers.Float32Array 4x4 projection matrix as Float32Array (16 elements)

setModelViewMatrix(matrix: clay.buffers.Float32Array): Void

Sets the model-view matrix uniform.

Name Type Description
matrix clay.buffers.Float32Array 4x4 model-view matrix as Float32Array (16 elements)

beginStencilWrite(): Void

Begins writing to the stencil buffer. Subsequent draw calls will write to stencil instead of color buffer.


endStencilWrite(): Void

Ends writing to the stencil buffer. Returns to normal color buffer rendering.


enableStencilTest(): Void

Enables stencil testing for subsequent draw operations. Only pixels passing the stencil test will be rendered.


disableStencilTest(): Void

Disables stencil testing for subsequent draw operations.


enableScissor(x: Float, y: Float, width: Float, height: Float): Void

Enables scissor testing with the specified rectangle. Only pixels within this rectangle will be rendered.

Name Type Description
x Float Left edge of scissor rectangle
y Float Top edge of scissor rectangle
width Float Width of scissor rectangle
height Float Height of scissor rectangle

disableScissor(): Void

Disables scissor testing.


new(): Void

Creates a new GLGraphicsBatcher instance.

Private Members

prepareNextBuffers(): Void

Prepares the next set of vertex buffers for use.

This implements a buffer cycling system to avoid GPU stalls. Instead of reusing the same buffer immediately (which could cause the GPU to wait), it cycles through multiple buffer sets.

Buffer allocation:

  • Position buffer: Full vertex capacity (MAX_VERTS_SIZE)
  • UV buffer: 2/3 of vertex capacity (optimized for quads)
  • Color buffer: Full vertex capacity (4 floats per vertex)
  • Index buffer: MAX_INDICES * 2 capacity

On C++ targets, additional ArrayBufferView objects are created for efficient memory access without copying.


resetIndexes(): Void

Resets all vertex buffer indexes to zero.

This prepares the buffers for a new batch of vertices. Called when starting a new draw batch or after flushing.