Home > Articles

Shader Fundamentals

This chapter is from the book

Interface Blocks

Shader variables shared with the application or between stages can be, and sometimes must be, organized into blocks of variables. Uniform variables can be organized into uniform blocks, input and output variables into in and out blocks, and shader storage buffers into buffer blocks.

These all have a similar form. First, we use uniform to demonstrate, showing first an anonymous form and second a named form:

uniform b {         // 'uniform' or 'in' or 'out' or 'buffer'
    vec4 v1;        // list of variables
    bool v2;        // ...
};                  // no name; access members as 'v1' and 'v2'

Or:

uniform b {         // 'uniform' or 'in' or 'out' or 'buffer'
    vec4 v1;        // list of variables
    bool v2;        // ...
} name;             // named; access members as 'name.v1' and 'name.v2'

Specific interface block details are provided in the following sections. Generally, the block name at the beginning (b above) is used for interface matching or external identification, while the name at the end (name above) is used in the rest of the shader for accessing the members.

Uniform Blocks

As your shader programs become more complex, it’s likely that the number of uniform variables they use will increase. Often, the same uniform value is used within several shader programs. As uniform locations are generated when a shader is linked (i.e., when glLinkProgram() is called), the indices may change, even though (to you) the values of the uniform variables are identical. Uniform buffer objects provide a method to optimize both accessing uniform variables and enabling sharing of uniform values across shader programs.

As you might imagine, given that uniform variables can exist both in your application and in a shader, you’ll need to both modify your shaders and use OpenGL routines to set up uniform buffer objects.

Specifying Uniform Blocks in Shaders

To access a collection of uniform variables using routines such as glMapBuffer() (see Chapter 3, “Drawing with OpenGL” for more details), you need to slightly modify their declaration in your shader. Instead of declaring each uniform variable individually, you group them, just as you would do in a structure, in a uniform block. A uniform block is specified using the uniform keyword. You then enclose all the variables you want in that block within a pair of braces, as demonstrated in Example 2.3.

Example 2.3 Declaring a Uniform Block

uniform Matrices {
    mat4 ModelView;
    mat4 Projection;
    mat4 Color;
};

Recall types are divided into two categories: opaque and transparent. The opaque types include samplers, images, and atomic counters. Only the transparent types are permitted to be within a uniform block. Additionally, uniform blocks must be declared at global scope.

Uniform Block Layout Control

A variety of qualifiers are available to specify how to lay out the variables within a uniform block. These qualifiers can be used for each individual uniform block or to specify how all subsequent uniform blocks are arranged (after specifying a layout declaration). The possible qualifiers are detailed in Table 2.12.

Table 2.12 Layout Qualifiers for Uniform

Layout Qualifier

Description

binding = N

Specify the buffer′s binding point, used by the OpenGL API.

shared

Specify that the uniform block is shared among multiple programs. (This is the default layout and is not to be confused with the shared storage qualifier.)

packed

Lay out the uniform block to minimize its memory use; however, this prevents sharing across programs.

std140

Use a standard layout for uniform blocks or shader storage buffer blocks, described in Appendix H, “Buffer Object Layouts.”

std430

Use a standard layout for buffer blocks, described in Appendix H, “Buffer Object Layouts.„

offset = N

Explicitly force a member to be located at byte offset N in the buffer.

align = N

Explicitly force a member offset to round up to a multiple of N.

row_major

Cause matrices in the uniform block to be stored in a row-major element ordering.

column_major

Specify matrices should be stored in a column-major element ordering. (This is the default ordering.)

For example, to specify that a single uniform block is shared and has row-major matrix storage, declare it in the following manner:

layout (shared, row_major) uniform { ... };

Multiple qualifying options must be separated by commas within the parentheses. To affect the layout of all subsequent uniform blocks, use the following construct:

layout (packed, column_major) uniform;

With this specification, all uniform blocks declared after that line will use that layout until the global layout is changed or unless they include a layout override specific to their declaration.

When you share a buffer between shaders and the application, both need to agree on what memory offsets are holding the members. Thus, an explicit layout is needed, and this is what std140 and std430 provide.

While std140 and std430 give a well-defined explicit layout of a buffer, you might want finer control over how the buffer is laid out. You can control exact locations of members using offset or align members at a coarser level using align. You only need to use these on some members, to keep layout in sync between the application and shader.

Subsequently unqualified members are automatically assigned offsets, as is standard for std140 or std430.

#version 440
layout (std140) uniform b {
    float size;                    // starts at byte 0, by default
    layout(offset=32) vec4 color;  // starts at byte 32
    layout(align=1024) vec4 a[12]; // starts at the next multiple
                                   // of 1024
    vec4 b[12];                    // assigned next offset after a[12]
} buf;

In your application, set up the buffer’s structure to match, using language tools decorating a C/C++ struct or just directly writing to the buffer at the right offsets. The only catch is the offsets and alignments all have to be sensible. The members still go in order of increasing offsets and still must be aligned as required by the std140 and std430 rules. Generally, this is natural alignment of floats and doubles, for anything containing them, with std140 having the extra constraint of needing 16-byte alignment for things smaller than a vec4.

Note on N: Any time a GLSL layout qualifier has the form layout (ID = N), the value N must be a non-negative integer. Under #version is 430 or earlier, it must be a literal integer. However, starting with #version 440, N can be a constant integer expression.

Accessing Uniform Variables Declared in a Uniform Block

While uniform blocks are named, the uniform variables declared within them are not qualified by that name. That is, a uniform block doesn’t scope a uniform variable’s name, so declaring two variables of the same name within two uniform blocks of different names will cause an error. Using the block name is not necessary when accessing a uniform variable, however.

Accessing Uniform Blocks from Your Application

Because uniform variables form a bridge to share data between shaders and your application, you need to find the offsets of the various uniform variables inside the named uniform blocks in your shaders. Once you know the location of those variables, you can initialize them with data, just as you would any type of buffer object (using calls such as glNamedBufferSubData(), for example).

To start, let’s assume that you already know the names of the uniform blocks used inside the shaders in your application. The first step in initializing the uniform variables in your uniform block is to obtain the index of the block for a given program. Calling

glGetUniformBlockIndex() returns an essential piece of information required to complete the mapping of uniform variables into your application’s address space.

To initialize a buffer object to be associated with your uniform block, you’ll need to bind a buffer object to a GL_UNIFORM_BUFFER target using the glBindBuffer() routine. (Chapter 3, “Drawing with OpenGL,” will add more details.)

Once we have a buffer object initialized, we need to determine how large to make it to accommodate the variables in the named uniform block from our shader. To do so, we use the routine glGetActiveUniformBlockiv(), requesting the GL_UNIFORM_BLOCK_DATA_SIZE, which returns the size of the block as generated by the compiler. (The compiler may decide to eliminate uniform variables that aren’t used in the shader, depending on which uniform block layout you’ve selected.) glGetActiveUniformBlockiv() can be used to obtain other parameters associated with a named uniform block.

After obtaining the index of the uniform block, we need to associate a buffer object with that block. The most common method for doing so is to call either glBindBufferRange() or, if all the buffer storage is used for the uniform block, glBindBufferBase().

Once the association between a named uniform block and a buffer object is made, you can initialize or change values in that block by using any of the commands that affect a buffer’s values.

You may also want to specify the binding for a particular named uniform block to a buffer object, as compared to the process of allowing the linker to assign a block binding and then querying the value of that assignment after the fact. You might follow this approach if you have numerous shader programs that will share a uniform block. It avoids having the block be assigned a different index for each program. To explicitly control a uniform block’s binding, call glUniformBlockBinding() before calling glLinkProgram().

The layout of uniform variables in a named uniform block is controlled by the layout qualifier specified when the block was compiled and linked. If you used the default layout specification, you will need to determine the offset and date-store size of each variable in the uniform block. To do so, you will use a pair of calls: glGetUniformIndices(), to retrieve the index of a particular named uniform variable, and glGetActiveUniformsiv(), to get the offset and size for that particular index, as demonstrated in Example 2.4.

Example 2.4 Initializing Uniform Variables in a Named Uniform Block

// Vertex and fragment shaders that share a block of uniforms
// named "Uniforms"
const char* vShader = {
    "#version 330 core\n"
    "uniform Uniforms {"
    "    vec3  translation;"
    "    float scale;"
    "    vec4  rotation;"
    "    bool  enabled;"
    "};"
    "in vec2  vPos;"
    "in vec3  vColor;"
    "out vec4  fColor;"
    "void main()"
    "{"
    "    vec3   pos = vec3(vPos, 0.0);"
    "    float  angle = radians(rotation[0]);"
    "    vec3   axis = normalize(rotation.yzw);"
    "    mat3   I = mat3(1.0);"
    "    mat3   S = mat3(     0, -axis.z, axis.y, "
    "                     axis.z,      0, -axis.x, "
    "                    -axis.y, axis.x,       0);"
    "    mat3   uuT = outerProduct(axis, axis);"
    "    mat3   rot = uuT + cos(angle)*(I - uuT) + sin(angle)*S;"
    "    pos *= scale;"
    "    pos *= rot;"
    "    pos += translation;"
    "    fColor = vec4(scale, scale, scale, 1);"
    "    gl_Position = vec4(pos, 1);"
    "}"
};

const char* fShader = {
    "#version 330 core\n"
    "uniform Uniforms {"
    "    vec3  translation;"
    "    float scale;"
    "    vec4  rotation;"
    "    bool  enabled;"
    "};"
    "in vec4  fColor;"
    "out vec4 color;"
    "void main()"
    "{"
    "    color = fColor;"
    "}"
};

// Helper function to convert GLSL types to storage sizes
size_t
TypeSize(GLenum type)
{
    size_t  size;

    #define CASE(Enum, Count, Type)     case Enum: size = Count * sizeof(Type); break

    switch (type) {
      CASE(GL_FLOAT,             1, GLfloat);
      CASE(GL_FLOAT_VEC2,        2, GLfloat);
      CASE(GL_FLOAT_VEC3,        3, GLfloat);
      CASE(GL_FLOAT_VEC4,        4, GLfloat);
      CASE(GL_INT,               1, GLint);
      CASE(GL_INT_VEC2,          2, GLint);
      CASE(GL_INT_VEC3,          3, GLint);
      CASE(GL_INT_VEC4,          4, GLint);
      CASE(GL_UNSIGNED_INT,      1, GLuint);
      CASE(GL_UNSIGNED_INT_VEC2, 2, GLuint);
      CASE(GL_UNSIGNED_INT_VEC3, 3, GLuint);
      CASE(GL_UNSIGNED_INT_VEC4, 4, GLuint);
      CASE(GL_BOOL,              1, GLboolean);
      CASE(GL_BOOL_VEC2,         2, GLboolean);
      CASE(GL_BOOL_VEC3,         3, GLboolean);
      CASE(GL_BOOL_VEC4,         4, GLboolean);
      CASE(GL_FLOAT_MAT2,        4, GLfloat);
      CASE(GL_FLOAT_MAT2x3,      6, GLfloat);
      CASE(GL_FLOAT_MAT2x4,      8, GLfloat);
      CASE(GL_FLOAT_MAT3,        9, GLfloat);
      CASE(GL_FLOAT_MAT3x2,      6, GLfloat);
      CASE(GL_FLOAT_MAT3x4,      12, GLfloat);
      CASE(GL_FLOAT_MAT4,        16, GLfloat);
      CASE(GL_FLOAT_MAT4x2,      8, GLfloat);
      CASE(GL_FLOAT_MAT4x3,      12, GLfloat);
      #undef CASE

      default:
      fprintf(stderr, "Unknown type: 0x%x\n", type);
      exit(EXIT_FAILURE);
      break;
    }

    return size;
}


void
init()
{
    GLuint program;

    glClearColor(1, 0, 0, 1);

    ShaderInfo shaders[] = {
        { GL_VERTEX_SHADER, vShader },
        { GL_FRAGMENT_SHADER, fShader },
        { GL_NONE, NULL }
    };

    program = LoadShaders(shaders);
    glUseProgram(program);

    /* Initialize uniform values in uniform block "Uniforms" */
    GLuint   uboIndex;
    GLint    uboSize;
    GLuint   ubo;
    GLvoid  *buffer;

    // Find the uniform buffer index for "Uniforms", and
    // determine the block's sizes
    uboIndex = glGetUniformBlockIndex(program, "Uniforms");

    glGetActiveUniformBlockiv(program, uboIndex,
    GL_UNIFORM_BLOCK_DATA_SIZE, &uboSize);

    buffer = malloc(uboSize);

    if (buffer == NULL) {
        fprintf(stderr, "Unable to allocate buffer\n");
        exit(EXIT_FAILURE);
    }
    else {
        enum { Translation, Scale, Rotation, Enabled, NumUniforms };

      /* Values to be stored in the buffer object */
      GLfloat    scale = 0.5;
      GLfloat    translation[] = { 0.1, 0.1, 0.0 };
      GLfloat    rotation[] = { 90, 0.0, 0.0, 1.0 };
      GLboolean  enabled = GL_TRUE;

      /* Since we know the names of the uniforms
      ** in our block, make an array of those values */
      const char* names[NumUniforms] = {
        "translation",
        "scale",
        "rotation",
        "enabled"
      };

      /* Query the necessary attributes to determine
      ** where in the buffer we should write
      ** the values */
      GLuint    indices[NumUniforms];
      GLint     size[NumUniforms];
      GLint     offset[NumUniforms];
      GLint     type[NumUniforms];

      glGetUniformIndices(program, NumUniforms, names, indices);
      glGetActiveUniformsiv(program, NumUniforms, indices,
                            GL_UNIFORM_OFFSET, offset);
      glGetActiveUniformsiv(program, NumUniforms, indices,
                            GL_UNIFORM_SIZE, size);
      glGetActiveUniformsiv(program, NumUniforms, indices,
                            GL_UNIFORM_TYPE, type);

      /* Copy the uniform values into the buffer */
      memcpy(buffer + offset[Scale], &scale,
             size[Scale] * TypeSize(type[Scale]));
      memcpy(buffer + offset[Translation], &translation,
             size[Translation] * TypeSize(type[Translation]));
      memcpy(buffer + offset[Rotation], &rotation,
             size[Rotation] * TypeSize(type[Rotation]));
      memcpy(buffer + offset[Enabled], &enabled,
             size[Enabled] * TypeSize(type[Enabled]));

      /* Create the uniform buffer object, initialize
      ** its storage, and associated it with the shader
      ** program */
      glGenBuffers(1, &ubo);
      glBindBuffer(GL_UNIFORM_BUFFER, ubo);
      glBufferData(GL_UNIFORM_BUFFER, uboSize,
                   buffer, GL_STATIC_RAW);

      glBindBufferBase(GL_UNIFORM_BUFFER, uboIndex, ubo);
    }
    ...
}

Buffer Blocks

GLSL buffer blocks or, from the application’s perspective, shader storage buffer objects, operate quite similarly to uniform blocks. Two critical differences give these blocks great power, however. First, the shader can write to them, modifying their content as seen from other shader invocations or the application. Second, their size can be established just before rendering rather than at compile or link time. For example:

buffer BufferObject { // create a read-writable buffer
    int mode;         // preamble members
    vec4 points[];    // last member can be unsized array
};

If this array is not provided a size in the shader, its size can be established by the application before rendering, after compiling and linking. The shader can use the length() method to find the render-time size.

The shader may now both read and write the members of the buffer block. Writes modifying the shader storage buffer object will be visible to other shader invocations. This can be particularly valuable in a compute shader, especially when manipulating nongraphical memory rather than an image.

Memory qualifiers (e.g., coherent) and atomic operations apply to buffer blocks and are discussed in depth in Chapter 11, “Memory.”

You set up a shader storage buffer object similarly to how a uniform buffer was set up, except that glBindBuffer(), glBindBufferRange() and glBindBufferBase() take the target GL_SHADER_STORAGE_BUFFER. A more complete example is given in Chapter 11, “Memory,” in “Shader Storage Buffer Objects” on page 589.

If you don’t need to write to a buffer, use a uniform block, as your device might not have as many resources available for buffer blocks as it does for uniform blocks. Also, keep in mind that only buffer blocks can use the std430 layout, while uniform blocks can use either std140 or std430.

In/Out Blocks, Locations, and Components

Shader variables output from one stage and input into the next stage can also be organized into interface blocks. These logical groupings can make it easier to visually verify interface matches between stages, as well as to make linking separate programs together easier.

For example, a vertex shader might output

out Lighting {
    vec3 normal;
    vec2 bumpCoord;
};

This would match a fragment shader input:

in Lighting {
    vec3 normal;
    vec2 bumpCoord;
};

A vertex shader might output material and lighting information, each grouped into its own block.

Throughout this book, layout (location=N) is used on individual input or output variables. As of OpenGL Version 4.4, this can also be applied to members of input and output blocks, to explicitly assign a location:

#version 440
in Lighting {
    layout(location=1) vec3 normal;
    layout(location=2) vec2 bumpCoord;
};

Whether in a block or not, each such location can hold the equivalent of a vec4. If you want to put multiple smaller objects into the same location, that can be done by further specifying a component:

#version 440
in Lighting {
    layout(location=1, component=0) vec2 offset;
    layout(location=1, component=2) vec2 bumpCoord;
};

This is much better than trying to declare a vec4 combined and using combined.xy and combined.zw to simulate offset and bumpCoord. It can also be done outside of blocks.

The interfaces built into the OpenGL Shading Language are also organized into blocks, like gl_PerVertex, which contains the built-in variable gl_Position, among others. A complete list of these is available in Appendix C, “Built-in GLSL Variables and Functions.”

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020