Lua logo

Preface

This is the reference manual of MoonGL, which is a Lua binding library for OpenGL. [1]

It is assumed that the reader is familiar with both OpenGL and the Lua programming language.

For convenience of reference, this document contains external (deep) links to the Lua Reference Manual and the OpenGL Documentation.

Getting and installing

For installation intructions, refer to the README file in the MoonGL official repository on GitHub.

Module organization

The MoonGL module is loaded using Lua’s require() and returns a table containing the functions it provides (as usual with Lua modules). This manual assumes that such table is named gl, i.e. that it is loaded with:

 gl = require("moongl")

but nothing forbids the use of a different name.

Examples

This manual contains a code snippets section where short incomplete examples show how to use MoonGL functions.

Complete examples can be found in the examples/ directory of the release package.

License

MoonGL is released under the MIT/X11 license (same as Lua, and with the same only requirement to give proper credits to the original author). The copyright notice is in the LICENSE file in the base directory of the official repository on GitHub.

See also

MoonGL is part of MoonLibs, a collection of Lua libraries for graphics and audio programming.

Introduction

MoonGL is an almost-one-to-one binding library to OpenGL, and it is intended to be used in the same way one would use OpenGL, except, of course, for coding in Lua instead of C or C++. In particular, this means that tasks like creating a GL context and handling input are not addressed by MoonGL, and one needs to resort to external modules (some of them are needed to run the examples).

This document purposedly reflects the structure of the OpenGL 4.5 Reference card, so that one can easily find the correspondence between MoonGL and OpenGL API by comparing the two documents. Links to corresponding sections of the OpenGL Wiki are also provided for this purpose.

As a general rule, each OpenGL function is bound to by a MoonGL function whose name is a snake_case version of the original. For example, glClear( ) is bound to by gl.clear( ), glClearBuffer( ) by gl.clear_buffer( ), and so on.

The mapping between OpenGL and MoonGL functions is not exactly one-to-one, however. This is mainly because MoonGL leverages Lua’s function overloading capabilities, whereas OpenGL, being a C API, has a lot of functions with slightly different names that are logically the same overloaded function.

MoonGL also adds a few functions (tagged with NONGL in this manual) that are not present in the OpenGL API. Among these:

  • new_xxx( ) functions that combine generation and binding of a single object;

  • unbind_xxx( ) functions to unbind objects (these are just wrappers of the corresponding bind_xxx( ) which have the same effect if they receive a nil or 0 as object name);

  • data handling functions, to convert data from Lua arrays to binary strings and viceversa;

  • utilities for compiling shader programs.

Parameter values that in OpenGL are #defined as integer codes become strings in MoonGL (as is customary in Lua). There is usually an easily recognizable pattern to derive the correct MoonGL string from the OpenGL #define name. For example, the buffer target codes GL_ARRAY_BUFFER and GL_ELEMENT_ARRAY_BUFFER become 'array' and 'element array', respectively (the string is typically obtained by removing the GL_ prefix and possibly some redundant part from the #define name, replacing underscores with spaces, and going from upper-case to lower-case letters).

Initialization

  • init( )
    Binding to glewInit(). This function must be called as soon as a GL context is obtained and made current, and before calling any other MoonGL function (since it initializes OpenGL’s function pointers, failing to do so would likely cause a segmentation fault).
    See example.

  • boolean = is_supported(string)
    Binding to glewIsSupported() (accepts the same strings). See example.

  • string = version( )
    Returns a string describing the latest OpenGL version supported by the combination of MoonGL, GLEW, and the OpenGL implementation being used (e.g. 'OpenGL 4.5'). This function can be used only after initialization.
    (Note that the get() function returns the version supported by the OpenGL implementation being used, which may differ from the version returned by this function).

  • The gl table contains the following fields for version information:
    - gl._VERSION: a string describing the MoonGL version (e.g. 'MoonGL 0.4'), and
    - gl._GLEW_VERSION: a string describing the GLEW version (e.g. 'GLEW 1.13.0').

Command Execution

  • status = get_graphics_reset_status( )
    status: 'no error', 'guilty context reset', 'innocent context reset', 'unknown context reset'.
    Rfr: glGetGraphicsResetStatus.

  • get

Note
The glGetError( ) function is not exposed. It is used internally by MoonGL, that checks for errors each time it executes an OpenGL command and raises an error if the command did not succeed.

Synchronization

  • sync = fence_sync(condition)
    delete_sync(sync)
    condition: 'gpu commands complete'.
    Rfr: glFenceSync - glDeleteSync.

  • status = client_wait_sync(sync, timeout, [flag, …​ ])
    status: 'already signaled', 'timeout expired', 'condition satisfied', 'wait failed'.
    glClientWaitSync.

  • value, …​ = get_sync(sync, pname)
    pname: 'type', 'condition', 'status', 'flags'.
    Rfr: glGetSync.

  • lightuserdata = raw_sync(sync) NONGL
    Returns the raw sync object as a lightuserdata (GLsync*).

Asynchronous Queries and Timers

  • value = get_query(target, pname, [index])
    pname: 'current query', 'query counter bits'.
    Rfr: glGetQuery.

Buffer Objects


Create/Modify Buffer Object Data:

  • size = buffer_storage(target|buffer, [data|dataptr], [flag, flag, …​])
    flag: 'dynamic storage', 'map read', 'map write', 'map persistent', 'map coherent', 'client storage'.
    Rfr: glBufferStorage.


Map/Unmap Buffer Data:

  • ptr = map_buffer(target|buffer, access)
    ptr = map_buffer_range(target|buffer, offset, length, [accessbit1, …​])
    unmap_buffer(target|buffer)
    access: 'read only', 'write only', 'read write',
    accessbit: 'read', 'write', 'persistent', 'coherent', 'invalidate buffer', 'invalidate range', 'flush explicit', 'unsynchronized'.
    The returned ptr value is a lightuserdata containing the raw pointer to the mapped memory (use at your peril).
    Rfr: glMapBuffer - glMapBufferRange.

  • mapped_buffer_write(target|buffer, offset, data|dataptr) NONGL
    data = mapped_buffer_read(target|buffer, offset, length) NONGL
    Write/read data to/from a mapped buffer (non-OpenGL functions).

  • mapped_buffer_copy_from(target|buffer, offset, length, srcptr, [srcoffset=0]) NONGL
    mapped_buffer_copy_to(target|buffer, offset, length, dstptr, [dstoffset=0]) NONGL
    Copy data from/to raw memory to/from a mapped buffer (non-OpenGL functions).
    srcptr, dstptr: lightuserdata containing a pointer to raw memory.
    (Note that MoonGL has no means to perform boundary checks on the passed raw memory, so use with caution.)


Invalidate Buffer Data:


Buffer Object Queries:

  • value, …​ = get_buffer_parameter(target|buffer, pname)
    pname: 'size', 'usage', 'access', 'access flags', 'immutable storage', 'mapped', 'map pointer', 'map offset', 'map length', 'storage flags'.
    Rfr: glGetBufferParameter.


Copy Between Buffers:

  • copy_buffer_sub_data(readtarget|readbuffer, writetarget|writebuffer, readoffset, writeoffset, size)
    Source and destination must be specified both as targets or both as buffer names.
    Rfr: glCopyBufferSubData.

Shaders and Programs

The following functions are MoonGL additions to ease the creation of shading programs:

  • program, shader1, shader2, …​ = make_program(shadertype1, filename1, [shadertype2, filename2, …​]) NONGL
    program, shader1, shader2, …​ = make_program({shadertype = filename}) NONGL
    Creates, compiles and links a program with the given shaders, checking for errors at each compilation step.
    Returns the OpenGL names assigned to the program and to the shaders.

  • program, shader1, shader2, …​ = make_program_s(shadertype1, sourcestring1, [shadertype2, sourcestring2, …​]) NONGL
    program, shader1, shader2, …​ = make_program_s({shadertype, sourcestring}) NONGL
    Same as gl.make_program( ), but loads the shaders' code from strings instead of from files.

  • clean_program(program, shader1, shader2, …​) NONGL
    Given the names of a program and of the shaders attached to it, detaches the shaders, and deletes them and the program.


Shader Objects

  • compile_shader(shader, [checkstatus=false])
    If checkstatus=true, also checks the compile status and possibly raises an error with the info log.
    Rfr: glCompileShader.


Program Objects

  • program_parameter(program, pname, boolean)
    pname: 'separable', 'binary retriavable hint'.
    Rfr: glProgramParameter.

  • format, binary = get_program_binary(program)
    program_binary(program, format, binary)
    format: integer,
    binary: binary string
    Rfr: glGetProgramBinary - glProgramBinary.


Program Pipeline Objects

  • pipeline = new_program_pipeline( ) NONGL
    pipeline1, pipeline2, …​ = gen_program_pipelines([n = 1])
    pipeline1, pipeline2, …​ = create_program_pipelines([n = 1])
    bind_program_pipeline(pipeline)
    unbind_program_pipeline( ) NONGL
    delete_program_pipelines(pipeline1, [pipeline2, …​])
    Rfr: glGenProgramPipelines - glBindProgramPipeline - glDeleteProgramPipelines.

  • use_program_stages(pipeline, program, [stage1, …​])
    stage: 'vertex', 'fragment', 'geometry', 'tess control', 'tess evaluation', 'compute', 'all'.
    Rfr: glUseProgramStages.


Uniform Variables Queries:

  • value1, …​ = get_active_uniforms(program, pname, index1, [index2, …​])
    pname: 'type', 'size', 'name length', 'block index', 'offset', 'array stride', 'matrix stride', 'is row major', 'atomic counter buffer index'.
    Rfr: glGetActiveUniforms.

  • value = get_active_uniform_block(program, index, pname)
    pname: 'binding', 'data size', 'name length', 'active uniforms', 'active uniform indices', 'referenced by vertex shader', 'referenced by tess control shader', 'referenced by tess evaluation shader', 'referenced by geometry shader', 'referenced by fragment shader', 'referenced by compute shader'.
    Rfr: glGetActiveUniformBlock.

  • value = get_active_atomic_counter_buffer(program, index, pname)
    pname: 'binding', 'data size', 'active atomic counters', 'active atomic counter indices', 'referenced by vertex shader', 'referenced by tess control shader', 'referenced by tess evaluation shader', 'referenced by geometry shader', 'referenced by fragment shader', 'referenced by compute shader'.
    Rfr: glGetActiveAtomicCounterBuffer.


Load Uniform Variables:

  • uniform(location, type, val1, [val2, val3, val4])
    uniformv(location, count, type, val1, [val2, …​ ])
    program_uniform(program, location, type, val1, [val2, val3, val4])
    program_uniformv(program, location, count, type, val1, [val2, …​ ])
    type: 'bool', 'int', 'uint', 'float' or 'double'.
    count: number of vectors (or variables) in the array.
    Rfr: glUniform - glProgramUniform. See example.

  • uniform_matrix(location, type, size, transpose, val1, val2, …​, valN)
    uniform_matrixv(location, count, type, size, transpose, val1, val2, …​, valN)
    program_uniform_matrix(program, location, type, size, transpose, val1, val2, …​, valN)
    program_uniform_matrixv(program, location, count, type, size, transpose, val1, val2, …​, valN)
    type: 'bool', 'int', 'uint', 'float' or 'double'.
    size: '2x2', '3x3', '4x4', '2x3', '3x2', '2x4', '4x2'', '3x4', '4x3'.
    transpose: boolean (= true if the value are passed in row-major order).
    count: number of matrices in the array (N = count x no. of elements in a matrix).
    Rfr: glUniformMatrix - glProgramUniformMatrix. See example.


Uniform Buffer Objects Bindings:


Shader Buffer Variables:


Subroutine Uniform Variables:

  • value, …​ = get_active_subroutine_uniform(program, shadertype, index, pname)
    pname: 'num compatible subroutines', 'compatible subroutines', 'uniform size', 'uniform name length'.
    Rfr: glGetActiveSubroutineUniform.


Shared Memory Access

  • memory_barrier(bit1, bit2, …​)
    memory_barrier_by_region(bit1, bit2, …​)
    bitk: 'all', 'vertex attrib array', 'element array', 'uniform', 'texture fetch', 'shader image access', 'command', 'pixel buffer', 'texture update', 'buffer update', 'client mapped buffer', 'query buffer', 'framebuffer', 'transform feedback', 'atomic counter', 'shader storage'.
    Rfr: glMemoryBarrier.


Program Interfaces:

  • value = get_program_interface(program, interface, pname)
    index = get_program_resource_index(program, interface, name)
    name = get_program_resource_name(program, interface, index)
    location = get_program_resource_location(program, interface, name)
    index = get_program_resource_location_index(program, interface, name)
    value, …​ = get_program_resource(program, interface, index, property)
    interface: 'uniform' for GL_UNIFORM, 'uniform block' for GL_UNIFORM_BLOCK, etc.
    pname: 'active resources', 'max name length', 'max num active variables', 'max num compatible subroutines'.
    property: 'array size' for GL_ARRAY_SIZE, 'array stride' for GL_ARRAY_STRIDE, etc.
    Rfr: Shader Program Query.


Shader and Program Queries

  • value = get_shader(shader, pname)
    pname: 'type', 'delete status', 'compile status', 'info log length', 'source length'.
    Rfr: glGetShader.

  • value, …​ = get_program(program, pname)
    pname: 'active atomic counter buffers' for GL_ACTIVE_ATOMIC_COUNTER_BUFFERS, etc.
    Rfr: glGetProgram.

  • value, …​ = get_program_pipeline(pipeline, pname)
    pname: 'active program' for GL_ACTIVE_PROGRAM, 'validate status' for GL_VALIDATE_STATUS, etc.
    Rfr: glGetProgramPipeline.

  • shader1, …​ = get_attached_shaders(program)
    Returns nil if no shaders are attached to program.
    Rfr: glGetAttachedShaders.

  • range0, range1, precision = get_shader_precision_format(shadertype, precisiontype)
    precisiontype: 'low int' for GL_LOW_INT, 'medium int' for GL_MEDIUM_INT, etc.
    Rfr: glGetShaderPrecisionFormat.

  • val1, …​ = get_uniform(program, location, type, size)
    type: 'bool', 'int', 'uint', 'float' or 'double'.
    size: number of elements in the uniform variable, vector or matrix (1 …​ 16).
    Rfr: glGetUniform.

  • value, …​ = get_program_stage(program, shadertype, pname)
    pname: 'active subroutines' for GL_ACTIVE_SUBROUTINES, etc.
    Rfr: glGetProgramStage.

Textures and Samplers

Texture units:


Texture Objects:


Sampler Objects

  • sampler = new_sampler(unit) NONGL
    sampler1, sampler2, …​ = gen_samplers([n = 1])
    sampler1, sampler2, …​ = create_samplers([n = 1])
    bind_sampler(unit, [sampler])
    bind_samplers(first, sampler1, [sampler2, …​])
    unbind_sampler(unit) NONGL
    delete_samplers(sampler1, [sampler2, …​])
    Rfr: glGenSamplers - glBindSampler - glBindSamplers - glDeleteSamplers.

  • sampler_parameter(sampler, pname, val1, [val2, …​])
    value, …​ = get_sampler_parameter(sampler, pname)
    pname: 'wrap s', 'wrap t', 'wrap r', 'max anisotropy', 'min filter', 'mag filter', 'border color', 'min lod', 'max lod', 'lod bias', 'compare mode', 'compare func'.
    Rfr: glSamplerParameter - glGetSamplerParameter.


Texture Image Spec.:


Alternate Texture Image Spec.:


Compressed Texture Images:


Multisample Textures:


Buffer Textures:


Invalidate/Clear Texture Image Data:


Texture Parameters

  • texture_parameter(target|texture, pname, val1, …​)
    pname: 'base level', 'wrap s', 'wrap t', 'wrap r', 'border color', 'depth stencil mode', 'compare func', 'compare mode', 'lod bias', 'min filter', 'mag filter', 'min lod', 'max lod', 'max level', 'swizzle r', 'swizzle g', 'swizzle b', 'swizzle a', 'swizzle rgba', 'max anisotropy'.
    Rfr: glTexParameter.
    See example.


Texture Queries

  • value, …​ = get_texture_parameter(target|texture, pname)
    pname: 'depth stencil texture mode', 'base level' for GL_TEXTURE_BASE_LEVEL, 'compare func' for GL_TEXTURE_COMPARE_FUNC, etc.
    Rfr: glGetTexParameter.

  • value = get_texture_level_parameter(target|texture, level, pname)
    pname: 'width' for GL_TEXTURE_WIDTH, 'fixed sample locations' for GL_TEXTURE_FIXED_SAMPLE_LOCATIONS, etc.
    'width', 'height', 'depth', 'fixed sample locations', 'internal format', 'shared size', 'compressed', 'compressed image size', 'samples', 'buffer offset', 'buffer size', 'red size', 'green size', 'blue size', 'alpha size', 'depth size', 'red type', 'green type', 'blue type', 'alpha type', 'depth type'.
    Rfr: glGetTexLevelParameter.

  • data = get_texture_image(target|texture, level, format, type, n)
    n: data size or offset in buffer.
    If a buffer is bound to the 'pixel pack' target, then n is interpreted as an offset and this function returns nil (in this case OpenGL copies the data to that buffer at the given offset). Otherwise n must be the size in bytes of the expected data, which this function returns as a binary string.
    Rfr: glGetTexImage.


Pixel Storage Modes:

  • pixel_store(pname, val)
    pname: 'unpack swap bytes' for GL_UNPACK_SWAP_BYTES, 'unpack lsb first' for GL_UNPACK_LSB_FIRST, etc.
    Rfr: glPixelStore.


Cube Map Texture Select:


Manual Mipmap Generation:


Texture Views:


Immutable-Format Tex. Images:


Texture Image Loads/Stores:

  • bind_image_texture(unit, texture, level, layered, layer, access, intformat)
    access: 'read only', 'write only', 'read write'.
    Rfr: glBindImageTexture.

Framebuffer Objects

  • framebuffer = new_framebuffer(target) NONGL
    framebuffer1, framebuffer2, …​ = gen_framebuffers([n = 1])
    framebuffer1, framebuffer2, …​ = create_framebuffers([n = 1])
    bind_framebuffer(target, [framebuffer])
    unbind_framebuffer(target) NONGL
    delete_framebuffers(framebuffer1, [framebuffer2, …​])
    Rfr: glGenFramebuffers - glBindFramebuffer - glDeleteFramebuffers.

  • framebuffer_parameter(target|framebuffer, pname, value)
    pname: 'default width', 'default height', 'default layers', 'default samples', 'default fixed sample locations'.
    Rfr: glFramebufferParameter.

  • value, …​ = get_framebuffer_parameter(target|framebuffer, pname)
    pname: 'default width', 'default height', 'default layers', 'default samples', 'default fixed sample locations', 'doublebuffer', 'implementation color read format', 'implementation color read type', 'samples', 'sample buffers', 'stereo'.
    Rfr: glGetFramebufferParameter.

  • value, …​ = get_framebuffer_attachment_parameter(target|framebuffer, attachment, pname)
    pname: 'object type', 'object name', 'component type', 'red size', 'green size', 'blue size', 'alpha size', 'depth size', 'stencil size', 'color encoding', 'texture layer', 'texture level', 'layered', 'texture cube map face'.
    Rfr: glGetFramebufferAttachmentParameter.


Renderbuffer Objects:

  • renderbuffer = new_renderbuffer(target) NONGL
    renderbuffer1, renderbuffer2, …​ = gen_renderbuffers([n = 1])
    renderbuffer1, renderbuffer2, …​ = create_renderbuffers([n = 1])
    bind_renderbuffer(target, [renderbuffer])
    unbind_renderbuffer(target) NONGL
    delete_renderbuffers(renderbuffer1, [renderbuffer2, …​])
    Rfr: glGenRenderbuffers - glBindRenderbuffer - glDeleteRenderbuffers.

  • value, …​ = get_renderbuffer_parameter(target|renderbuffer, pname)
    pname: 'width', 'height', 'internal format', 'samples', 'red size', 'green size', 'blue size', 'alpha size', 'depth size', 'stencil size'.
    Rfr: glGetRenderbufferParameter.


Attaching Renderbuffer Images:


Attaching Texture Images:


Feedback Loops:


Framebuffer Completeness:

  • status = check_framebuffer_status(target, [framebuffer])
    status: 'complete', 'undefined', 'incomplete attachment', 'incomplete missing attachment', 'incomplete draw buffer', 'incomplete read buffer', 'unsupported', 'incomplete multisample', 'incomplete layer targets'.
    Rfr: glCheckFramebufferStatus.

Vertices

Separate Patches :

  • patch_parameter(pname, val, [val, …​])
    pname: 'vertices', 'default outer level', 'default inner level'.
    Rfr: glPatchParameter.


Current Vertex Attribute Values:

  • vertex_attrib(index, type, val1, [val2, val3, val4])
    type: 'byte', 'ubyte', 'short', 'ushort', 'int', 'uint', 'float', 'double'.
    Rfr: glVertexAttrib.

  • vertex_attrib_n(index, type, val1, val2, val3, val4)
    type: 'byte', 'ubyte', 'short', 'ushort', 'int', 'uint'.
    Rfr: glVertexAttrib.

  • vertex_attrib_p(index, type, normalized, val1, val2, val3, val4)
    type: 'int 2 10 10 10 rev', 'uint 2 10 10 10 rev', 'uint 10f 11f 11f rev'.
    Rfr: glVertexAttrib.

Vertex Arrays

Vertex Array Objects:

  • array = new_vertex_array( ) NONGL
    array1, array2, …​ = gen_vertex_arrays([n = 1])
    array1, array2, …​ = create_vertex_arrays([n = 1])
    bind_vertex_array([array])
    unbind_vertex_array( ) NONGL
    delete_vertex_arrays(array1, [array2, …​])
    Rfr: glGenVertexArrays - glBindVertexArray - glDeleteVertexArrays - See example.

  • vertex_array_element_buffer(array, buffer)


Generic Vertex Attribute Arrays:

  • vertex_attrib_format(index, size, type, normalized, offset)
    vertex_attrib_format(array, index, size, type, normalized, offset)
    type: 'byte', 'ubyte', 'short', 'ushort', 'int', 'uint', 'float', 'double', 'half float', 'fixed', 'int 2 10 10 10 rev', 'uint 2 10 10 10 rev', 'uint 10f 11f 11f rev'.
    Rfr: glVertexAttribFormat.

  • bind_vertex_buffer(index, buffer, offset, stride)
    bind_vertex_buffer(array, index, buffer, offset, stride)
    bind_vertex_buffers(index, buffer1, offset1, stride1, [buffer2, offset2, stride2, …​])
    bind_vertex_buffers(array, index, buffer1, offset1, stride1, [buffer2, offset2, stride2, …​])
    Rfr: glBindVertexBuffer - glBindVertexBuffers.

  • vertex_attrib_binding(attribindex, bindingindex)
    vertex_attrib_binding(array, attribindex, bindingindex)
    Rfr: glVertexAttribBinding.

  • vertex_attrib_pointer(index, size, type, normalized, stride, pointer)
    vertex_attrib_i_pointer(index, size, type, stride, pointer)
    size: 1, 2, 3, 4, or 0 for GL_BGRA.
    type: 'byte', 'ubyte', 'short', 'ushort', 'int', 'uint', 'float', 'double', 'half float', 'fixed', 'int 2 10 10 10 rev', 'uint 2 10 10 10 rev', 'uint 10f 11f 11f rev'.
    Rfr: glVertexAttribPointer.
    See example.


Vertex Attribute Divisors


Primitive Restart:


Drawing Commands:

  • draw_arrays(mode, first, count, [instancecount], [baseinstance])
    draw_arrays_indirect(mode, indirect)
    multi_draw_arrays(mode, first1, count1, [first2, count2 …​])
    multi_draw_arrays_indirect(mode, indirect, drawcount, stride)
    multi_draw_arrays_indirect_count(mode, indirect, drawcount, maxdrawcount, stride)
    draw_elements(mode, count, type, indices, [instancecount], [baseinstance])
    draw_elements_indirect(mode, type, indirect)
    draw_elements_base_vertex(mode, count, type, indices, basevertex , [instancecount], [baseinstance])
    multi_draw_elements(mode, type, count1, indices1, [count2, indices2, …​])
    multi_draw_elements_indirect(mode, type, indirect, drawcount, stride)
    multi_draw_elements_indirect_count(mode, type, indirect, drawcount, maxdrawcount, stride)
    multi_draw_elements_base_vertex(mode, type, count1, indices1, basevertex1, [count2, indices2, basevertex2, …​])
    draw_range_elements(mode, start, end, count, type, indices)
    draw_range_elements_base_vertex(mode, start, end, count, type, indices, basevertex)
    mode: 'points', 'patches', 'line strip', 'line loop', 'triangle strip', 'triangle fan', 'lines', 'lines adjacency', 'triangles', 'triangles adjacency', 'line strip adjacency', 'triangle strip adjacency'.
    type: 'ubyte', 'ushort', 'uint'.
    Rfr: glDrawArrays - glDrawElements.


Vertex Array Queries:

  • value = get_vertex_array(array, pname, [index])
    pname: 'size' for GL_VERTEX_ATTRIB_ARRAY_SIZE, etc (and 'binding offset' for GL_VERTEX_BINDING_OFFSET, 'element array buffer binding' for GL_ELEMENT_ARRAY_BUFFER_BINDING, 'current attrib' for GL_CURRENT_VERTEX_ATTRIB).
    Rfr: glGetVertexArrayiv, glGetVertexArrayIndexed.

  • value, …​ = get_vertex_attrib(index, pname)
    va1, val2, val3, val4 = get_current_vertex_attrib(index, type)
    pname: see get_vertex_array.
    type: 'byte', ubyte', 'short', 'ushort', 'int', 'uint', 'float', 'double'.
    Rfr: glGetVertexAttrib.


Conditional Rendering:

  • begin_conditional_render(id, mode )
    end_conditional_render( )
    mode: 'query wait' for GL_QUERY_WAIT, 'query no wait' for GL_QUERY_NO_WAIT, etc.
    Rfr: glBeginConditionalRender.

Vertex Attributes

Attribute Location:


Transform Feedback Variables:

  • transform_feedback_varyings(program, mode, varying1, [varying2, …​ ])
    mode: 'interleaved attribs', 'separate attribs'.
    Rfr: glTransformFeedbackVaryings.


Shader Execution:

Vertex Post-Processing

Transform Feedback:

  • xfb= new_transform_feedback(target ) NONGL
    xfb1, xfb2, …​ = gen_transform_feedbacks([n = 1])
    xfb1, xfb2, …​ = create_transform_feedbacks([n = 1])
    bind_transform_feedback(target, [xfb])
    unbind_transform_feedback(target) NONGL
    delete_transform_feedbacks(xfb1, [xfb2, …​])
    target: 'transform feedback'.
    Rfr: glGenTransformFeedbacks - glBindTransformFeedback - glDeleteTransformFeedbacks.

  • transform_feedback_buffer_range(xfb, index, buffer, offset, size)
    transform_feedback_buffer_base(xfb, index, buffer)

  • draw_transform_feedback(mode, xfb, [instancecount])
    draw_transform_feedback_stream(mode, xfb, stream, [instancecount])
    mode: 'points', 'patches', 'line strip', 'line loop', 'triangle strip', 'triangle fan', 'lines', 'lines adjacency', 'triangles', 'triangles adjacency', 'line strip adjacency', 'triangle strip adjacency'.
    Rfr: glDrawTransformFeedback - glDrawTransformFeedbackStream.


Flatshading:

  • provoking_vertex(provokemode)
    provokemode: 'first vertex convention', 'last vertex convention'.
    Rfr: glProvokingVertex.


Primitive Clipping:

  • clip_control(origin, depth)
    origin: 'lower left', 'upper left'.
    depth: 'negative one to one', 'zero to one'.
    Rfr: glClipControl.


Controlling Viewport:

Rasterization


Multisampling:

  • value, …​ = get_multisample(pname)
    pname: 'sample position'.
    Rfr: glGetMultisample.


Points:

  • point_parameter(pname, value)
    pname: 'fade threshold size', 'point sprite coord origin'.
    Rfr: glPointParameter.

  • get


Line Segments:


Polygons:

  • cull_face(mode)
    mode: 'front', 'back', 'front and back'.
    Rfr: glCullFace.


Polygon Rast. & Depth Offset:

  • polygon_mode(face, mode)
    face: 'front and back'.
    mode: 'point', 'line', 'fill'.
    Rfr: glPolygonMode.

  • polygon_offset(factor, units)
    polygon_offset_clamp(factor, units, clamp)
    Rfr: glPolygonOffset.

Fragment Shaders

Compute Shaders

Per-Fragment Operations

Scissor Test:

  • scissor_array(first, x1, y1, w1, h1, [x2, y2, w2, h2, …​])
    scissor(left, bottom, width, height, [index])
    Rfr: glScissor - glScissorArray.


Multisample Fragment Ops.:


Stencil Test:

  • stencil_func(func, ref, mask, [face])
    func: 'never' for GL_NEVER, 'always' for GL_ALWAYS, etc.
    face: 'front', 'back', 'front and back'.
    Rfr: glStencilFunc - glStencilFuncSeparate.

  • stencil_op(sfail, dpfail, dppass, [face])
    sfail, dpfail, dppass: 'keep' for GL_KEEP, 'incr wrap' for GL_INCR_WRAP, etc.
    face: 'front', 'back', 'front and back'.
    Rfr: glStencilOp - glStencilOpSeparate.


Depth Buffer Test:

  • depth_func(func)
    func: 'never' for GL_NEVER, 'always' for GL_ALWAYS, etc.
    Rfr: glDepthFunc.


Occlusion Queries:


Blending:

  • blend_equation(mode)
    blend_equation(buf, mode)
    blend_equation(rgb, alpha)
    blend_equation(buf, rgb, alpha)
    mode, rgb, aplha: 'min', 'max', 'add', 'subtract', 'reverse subtract'.
    Rfr: glBlendEquation.

  • blend_func(src, dst)
    blend_func(buf, src, dst)
    blend_func(srcrgb, dstrgb, srcalpha, dstalpha)
    blend_func(buf, srcrgb, dstrgb, srcalpha, dstalpha)
    src, dst: 'zero', 'one', 'src color', 'one minus src color', etc.
    Rfr: glBlendFunc.


Dithering:


Logical Operations:

  • logic_op(op, green, blue, alpha)
    op: 'clear', 'and', 'and reverse', etc.
    Rfr: glLogicOp.

Hints

  • hint(target, hint)
    target: 'line smooth', 'polygon smooth', 'texture compression', 'fragment shader derivative'.
    hint: 'fastest', 'nicest', 'don’t care'.
    Rfr: glHint.

Whole Framebuffer

Selecting Buffers for Writing:

  • draw_buffer(buf)
    draw_buffer(framebuffer, buf)
    draw_buffers(buf1, [buf2, …​])
    draw_buffers({buf1, [buf2, …​]})
    draw_buffers(framebuffer, buf1, [buf2, …​])
    draw_buffers(framebuffer, {buf1, [buf2, …​]})
    bufk: attachment.
    Rfr: glDrawBuffer, glDrawBuffers.


Fine Control of Buffer Updates:

  • color_mask(r, g, b, a)
    color_mask(drawbuffer, r, g, b, a)
    r, g, b, a: booleans.
    Rfr: glColorMask.

  • stencil_mask(mask, [face])
    face: 'front', 'back', 'front and back'.
    Rfr: glStencilMask.


Clearing the Buffers:

  • clear([buffer, …​ ])
    buffer: 'color', 'depth', 'stencil'.
    Rfr: glClear. See example.

  • clear_buffer('color', drawbuffer, r, g, b, a)
    clear_buffer('color', drawbuffer, color)
    clear_buffer('depth', value)
    clear_buffer('stencil', value)
    clear_buffer(framebuffer, 'color', drawbuffer, r, g, b, a)
    clear_buffer(framebuffer, 'color', drawbuffer, color)
    clear_buffer(framebuffer, 'depth', value)
    clear_buffer(framebuffer, 'stencil', value)
    Rfr: glClearBuffer.

  • clear_bufferfi(depth, stencil)
    clear_bufferfi(framebuffer, depth, stencil)
    Rfr: glClearBufferfi.


Invalidating Framebuffers:

Reading and Copying Pixels

Reading Pixels:

  • data = read_pixels(x, y, width, height, format, type)
    format: 'stencil index' for GL_STENCIL_INDEX, 'red' for GL_RED, etc.
    type: 'half float' for GL_HALF_FLOAT, 'float' for GL_FLOAT, etc.
    Returns data as a binary string.
    Rfr: glReadPixels.


Final Conversion:

  • clamp_color(target, clamp)
    target: 'clamp read color'.
    clamp: 'true', 'false', 'fixed only' (Lua booleans true and false are accepted as well).
    Rfr: glClampColor.

  • blit_framebuffer(srcx0, srcy0, srcx1, srcy1, dstx0, dsty0, dstx1, dsty1, filter, [maskbit1, …​])
    blit_framebuffer(readframebuffer, drawframebuffer, ..ditto..)
    filter: 'linear', 'nearest'.
    maskbit(s): 'color', 'depth', 'stencil'.
    Rfr: glBlitFramebuffer.


Copying Pixels:

  • copy_image_sub_data(srcname, srctarget, srclevel, srcx, srcy, srcz, dstname, dsttarget, dstlevel, dstx, dsty, dstz, width, height, depth)
    Rfr: glCopyImageSubData.

Debug Output


Debug Message Callbacks:

  • debug_message_callback(func)
    The func callback is executed as func(source, type, id, severity, message).
    source: 'api' for GL_DEBUG_SOURCE_API, 'shader compiler' for GL_DEBUG_SOURCE_SHADER_COMPILER, etc.
    type: 'error' for GL_DEBUG_TYPE_ERROR, 'deprecated behavior' for GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, etc.
    severity: 'high', 'medium', 'low', 'notification'.
    Rfr: glDebugMessageCallback.


Controlling Debug Messages:


Externally Generated Messages:


Debug Groups:


Debug Labels:

  • object_label(identifier, name, label)
    identifier: 'buffer' for GL_BUFFER, 'vertex array' for GL_VERTEX_ARRAY, etc.
    Rfr: glObjectLabel.


Synchronous Debug Output:


DebugOutput Queries:

State and State Requests

Simple Queries:

  • value, …​ = get(pname, [index])
    pname: 'context flags' for GL_CONTEXT_FLAGS, 'major version' for GL_MAJOR_VERSION, etc.
    The index argument may be mandatory or optional, depending on pname.
    Rfr: glGet.

Note
An 'invalid enumerant' error raised by a get( ) call means that the pname is not supported by the OpenGL version being used (a mis-spelled pname causes a 'bad argument …​' error).

String Queries:

  • value, …​ = get_string(pname, [index])
    pname: 'renderer', 'vendor', 'version', 'extensions', 'shading language version'.
    The index argument may be mandatory or optional, depending on pname.
    Rfr: glGetString.

  • {extension} = get_extensions([byname]) NONGL
    {spir_v_extension} = get_spir_v_extensions([byname]) NONGL
    If byname is false (default), returns an array with the names (strings) of all the supported extensions.
    If byname is true, returns a table of true values indexed with the names of the supported extensions.
    Rfr: glGetString.


Internal Format Queries:


Transform Feedback Queries:

  • value = get_transform_feedback(xfb, pname)
    pname: 'paused', 'active', 'buffer binding', 'buffer start', 'buffer size'.
    Rfr: glGetTransformFeedback.

Data handling utilities

The functions described in this section are MoonGL-specific utilities (they have no equivalent in OpenGL) that can be used to encode data from Lua variables to binary strings, and to decode data the other way round. They are useful to deal with the binary string format expected by GL functions like, for example, buffer_data( ) and buffer_sub_data( ).

  • val1, …​, valN = flatten(table) NONGL
    Flattens out the given table and returns the terminal elements in the order they are found. Similar to Lua’s table.unpack( ), it also unpacks any nested table. Only the array part of the table(s) is considered.

  • {val1, …​, valN} = flatten_table(table) NONGL
    Same as flatten( ), but returns the values in a flat table. Unlike flatten( ), this function can be used also with very large tables.

  • size = sizeof(type) NONGL
    Returns the size, in bytes, of the GL type.

  • data = pack(type, val1, …​, valN) NONGL
    data = pack(type, table) NONGL
    Packs the numbers val1, …​, valN in a binary string, encoding them according to type. The values may be passed also in a (possibly nested) table t.

  • {val1, …​, valN} = unpack(type, data) NONGL
    Unpacks the binary string data, interpreting it as a sequence of values enncoded according to type, and returns the extracted values in a flat table. The length of the binary string must be a multiple of gl.sizeof(type).

Common data types

color: {float}[4] (normalized rgba components).

data: binary string.

dataptr: {ptr, size}, where ptr is a lightuserdata containing a raw pointer to size bytes of memory.

Enumerations

attachment: 'none', 'front left', 'front right', 'back left', 'back right', 'front', 'back', 'left', 'right', 'front and back', 'color attachment 0', 'color attachment 1', …​, 'color attachment 15', 'color', 'depth', 'stencil', 'depth attachment', 'stencil attachment', 'depth stencil attachment'.

buffer target: 'array', 'uniform', 'atomic counter', 'query', 'copy read', 'copy write', 'dispatch indirect', 'draw indirect', 'element array', 'texture', 'pixel pack', 'pixel unpack', 'shader storage', 'transform feedback'.

buffer usage: 'static draw', 'static read', 'static copy', 'dynamic draw', 'dynamic read', 'dynamic copy', 'stream draw', 'stream read', 'stream copy'.

capability: 'blend', 'clip distance 0' .. 'clip distance 7', 'color logic op', 'cull face', 'debug output', 'debug output synchronous', 'depth clamp', 'depth test', 'dither', 'framebuffer srgb', 'line smooth', 'multisample', 'polygon offset fill', 'polygon offset line', 'polygon offset point', 'polygon smooth', 'primitive restart', 'primitive restart fixed index', 'rasterizer discard', 'sample alpha to coverage', 'sample alpha to one', 'sample coverage', 'sample shading', 'sample mask', 'scissor test', 'stencil test', 'texture cube map seamless', 'program point size'.

format: 'rgb' for GL_RGB, 'depth component' for GL_DEPTH_COMPONENT, etc.

framebuffer target: 'draw', 'read', or 'draw read' (for GL_FRAMEBUFFER).

glsltype: 'float', 'vec2', 'vec3', 'vec4', 'double', 'dvec2', 'dvec3', 'dvec4', 'int', 'ivec2', 'ivec3', 'ivec4', 'uint', 'uvec2', 'uvec3', 'uvec4', 'bool', 'bvec2', 'bvec3', 'bvec4', 'mat2', 'mat3', 'mat4', 'mat2x3', 'mat2x4', 'mat3x2', 'mat3x4', 'mat4x2', 'mat4x3', 'dmat2', 'dmat3', 'dmat4', 'dmat2x3', 'dmat2x4', 'dmat3x2', 'dmat3x4', 'dmat4x2', 'dmat4x3', 'sampler1D', 'sampler2D', 'sampler3D', 'samplerCube', 'sampler1DShadow', 'sampler2DShadow', 'sampler1DArray', 'sampler2DArray', 'sampler1DArrayShadow', 'sampler2DArrayShadow', 'sampler2DMS', 'sampler2DMSArray', 'samplerCubeShadow', 'samplerBuffer', 'sampler2DRect', 'sampler2DRectShadow', 'isampler1D', 'isampler2D', 'isampler3D', 'isamplerCube', 'isampler1DArray', 'isampler2DArray', 'isampler2DMS', 'isampler2DMSArray', 'isamplerBuffer', 'isampler2DRect', 'usampler1D', 'usampler2D', 'usampler3D', 'usamplerCube', 'usampler2DArray', 'usampler2DArray', 'usampler2DMS', 'usampler2DMSArray', 'usamplerBuffer', 'usampler2DRect', 'image1D', 'image2D', 'image3D', 'image2DRect', 'imageCube', 'imageBuffer', 'image1DArray', 'image2DArray', 'image2DMS', 'image2DMSArray', 'iimage1D', 'iimage2D', 'iimage3D', 'iimage2DRect', 'iimageCube', 'iimageBuffer', 'iimage1DArray', 'iimage2DArray', 'iimage2DMS', 'iimage2DMSArray', 'uimage1D', 'uimage2D', 'uimage3D', 'uimage2DRect', 'uimageCube', 'uimageBuffer', 'uimage1DArray', 'uimage2DArray', 'uimage2DMS', 'uimage2DMSArray', 'atomic_uint'.

intformat: 'rgb' for GL_RGB, 'stencil index' for GL_STENCIL_INDEX, 'r8 snorm' for GL_R8_SNORM, etc.
Values: 'none', 'stencil index', 'depth component', 'depth stencil', 'red', 'rg', 'rgb', 'rgba', 'r8', 'r8 snorm', 'r16', 'r16 snorm', 'rg8', 'rg8 snorm', 'rg16', 'rg16 snorm', 'r3 g3 b2', 'rgb4', 'rgb5', 'rgb8', 'rgb8 snorm', 'rgb10', 'rgb12', 'rgb16 snorm', 'rgba2', 'rgba4', 'rgb5 a1', 'rgba8', 'rgba8 snorm', 'rgb10 a2', 'rgb10 a2ui', 'rgba12', 'rgba16', 'srgb8', 'srgb8 alpha8', 'srgb', 'srgb alpha', 'r16f', 'rg16f', 'rgb16f', 'rgba16f', 'r32f', 'rg32f', 'rgb32f', 'rgba32f', 'r11f g11f b10f', 'rgb9 e5', 'r8i', 'r8ui', 'r16i', 'r16ui', 'r32i', 'r32ui', 'rg8i', 'rg8ui', 'rg16i', 'rg16ui', 'rg32i', 'rg32ui', 'rgb8i', 'rgb8ui', 'rgb16i', 'rgb16ui', 'rgb32i', 'rgb32ui', 'rgba8i', 'rgba8ui', 'rgba16i', 'rgba16ui', 'rgba32i', 'rgba32ui', 'depth component16', 'depth component24', 'depth component32', 'depth component32f', 'depth24 stencil8', 'depth32f stencil8', 'stencil index8', 'compressed red', 'compressed rg', 'compressed rgb', 'compressed rgba', 'compressed srgb', 'compressed srgb alpha', 'compressed red rgtc1', 'compressed signed red rgtc1', 'compressed rg rgtc2', 'compressed signed rg rgtc2', 'compressed rgba bptc unorm', 'compressed srgb alpha bptc unorm', 'compressed rgb bptc signed float', 'compressed rgb bptc unsigned float', 'compressed rgb s3tc dxt1 ext', 'compressed srgb s3tc dxt1 ext', 'compressed rgba s3tc dxt1 ext', 'compressed srgb alpha s3tc dxt1 ext', 'compressed rgba s3tc dxt3 ext', 'compressed srgb alpha s3tc dxt3 ext', 'compressed rgba s3tc dxt5 ext', 'compressed srgb alpha s3tc dxt5 ext'.

query target: 'timestamp', 'any samples passed', 'any samples passed conservative', 'primitives generated', 'samples passed', 'time elapsed', 'transform feedback primitives written', 'vertices submitted', 'primitives submitted', 'vertex shader invocations', 'tess control shader patches', 'tess evaluation shader invocations', 'geometry shader primitives emitted', 'fragment shader invocations', 'compute shader invocations', 'geometry shader invocations', 'clipping input primitives', 'clipping output primitives', 'transform feedback overflow', 'transform feedback stream overflow'.

renderbuffer target: 'renderbuffer'.

shaderbinaryformat: 'spir v'.

shadertype: 'vertex', 'fragment', 'geometry', 'tess evaluation', 'tess control', 'compute'.

texture target: '1d', '2d', '3d', '1d array', '2d array', 'rectangle', 'cube map', 'cube map array', '2d multisample', '2d multisample array', 'cube map positive x', 'cube map positive y', 'cube map positive z', 'cube map negative x', 'cube map negative y', 'cube map negative z', 'proxy 1d', 'proxy 2d', 'proxy 3d', 'proxy 1d array', 'proxy 2d array', 'proxy rectangle', 'proxy cube map', 'proxy cube map array', 'proxy 2d multisample', 'proxy 2d multisample array', 'buffer', 'renderbuffer'.

type: 'none', 'ubyte', 'byte', 'ushort', 'short', 'uint', 'int', 'fixed', 'half float', 'float', 'double', 'ubyte 3 3 2', 'ubyte 2 3 3 rev', 'ushort 5 6 5', 'ushort 5 6 5 rev', 'ushort 4 4 4 4', 'ushort 4 4 4 4 rev', 'ushort 5 5 5 1', 'ushort 1 5 5 5 rev', 'uint 8 8 8 8', 'uint 8 8 8 8 rev', 'uint 10 10 10 2', 'uint 2 10 10 10 rev', 'uint 24 8', 'uint 10f 11f 11f rev', 'uint 5 9 9 9 rev', 'float 32 uint 24 8 rev', 'int 2 10 10 10 rev'.

Code Snippets

This section contains code snippets (i.e. incomplete examples) that show the usage of MoonGL functionalities in practice.

OpenGL initialization with MoonGLFW.
gl = require("moongl")
glfw = require("moonglfw")

-- Create a window and make its GL context current:
window = glfw.create_window(600, 400, "Hello, MoonGL!")
glfw.make_context_current(window)

-- This is actually glewInit():
gl.init()

-- ... now it is safe to call MoonGL functions ...
Usage of is_supported( ).
if not gl.is_supported("GL_VERSION_4_5") then
  error("Sorry, OpenGL 4.5 is not supported by your system")
end
Clearing the framebuffer.
-- specify the clear value for the color buffer:
gl.clear_color(1.0, 0.0, 0.0, 1.0)

-- specify the clear value for the depth buffer:
gl.clear_depth(0.6)

-- clear the color buffer and the depth buffer:
gl.clear('color', 'depth')
Defining a rectangle.
vertices = {
-- position:        color:          texture coords:    0 ____ 1
  -0.5,  0.5, 0.0,  1.0, 0.0, 0.0,  0.0, 1.0, -- 0      |   /|
   0.5,  0.5, 0.0,  0.0, 1.0, 0.0,  1.0, 1.0, -- 1      | /  |
   0.5, -0.5, 0.0,  0.0, 0.0, 1.0,  1.0, 0.0, -- 2      |/___|
  -0.5, -0.5, 0.0,  1.0, 1.0, 1.0,  0.0, 0.0, -- 3     3      2
}

indices = {
    0, 1, 3, -- first triangle
    1, 2, 3, -- second triangle
}

floatsz = gl.sizeof('float')

vao = gl.new_vertex_array()  -- vertex array object
vbo = gl.new_buffer('array') -- vertex buffer object
gl.buffer_data('array', gl.pack('float', vertices), 'static draw')
-- position attribute
gl.vertex_attrib_pointer(0, 3, 'float', false, 8*floatsz, 0)
gl.enable_vertex_attrib_array(0)
-- color attribute
gl.vertex_attrib_pointer(1, 3, 'float', false, 8*floatsz, 3*floatsz)
gl.enable_vertex_attrib_array(1)
-- texture coords attribute
gl.vertex_attrib_pointer(2, 2, 'float', false, 8*floatsz, 6*floatsz)
gl.enable_vertex_attrib_array(2)

ebo = gl.new_buffer('element array') -- element buffer object
gl.buffer_data('element array', gl.pack('uint', indices), 'static draw')

gl.unbind_vertex_array()
Assigning values to uniform variables.
gl.uniform(0, 'uint', 123)
gl.uniform(1, 'float', 1.234)
gl.uniform(2, 'bool', true)

gl.uniform(3, 'int', 1, 2) -- 2D vector

v = { 1.0, 2.0, 3.0 }
gl.uniform(4, 'float', gl.flatten(v)) -- table.unpack(v) would do also
Assigning values to uniform matrices.
M = { 1.0, 2.0, 3.0  -- row-major order
      4.0, 5.0, 6.0
      7.0, 8.0, 9.0 }

gl.uniform_matrix(0, 'float', '3x3', true, gl.flatten(M))
Creating and using a texture (loaded with MoonImage).
-- 1) Creating the texture:
tex_id = gl.new_texture('2d')
-- configure it:
gl.texture_parameter('2d', 'wrap s', 'repeat')
gl.texture_parameter('2d', 'wrap t', 'repeat')
gl.texture_parameter('2d', 'min filter', 'linear')
gl.texture_parameter('2d', 'mag filter', 'linear')
-- load the texture image using MoonImage:
image, w, h = mi.load('myimage.png', 'rgb')
gl.texture_image('2d', 0, 'rgb', 'rgb', 'ubyte', image, w, h)
image, w, h = nil, nil, nil -- let the GC collect them
-- generate the mipmap:
gl.generate_mipmap('2d')
gl.unbind_texture('2d')

-- ...

-- 2) Using the texture in the game loop:
gl.use_program(prog_id)
gl.active_texture(0) -- activate texture unit 0
gl.bind_texture('2d', tex_id)
-- Assuming our program has a sampler2D uniform named mytexture:
gl.uniform(gl.uniform_location(prog_id, 'mytexture'), 'int', 0)
-- ... bind geometry and draw ...

1. This manual is written in AsciiDoc, rendered with AsciiDoctor and a CSS from the AsciiDoctor Stylesheet Factory. The PDF version is produced with AsciiDoctor-Pdf.