easy-gl › Shader

Shader

Represents a single compiled shader stage. You typically create shaders, compile them, attach them to a Program, link it, then either keep them or let attach_owned transfer ownership to the Program.

For the common two-stage case, use Program(vertSrc, fragSrc) which compiles and links in one step without constructing Shader objects manually.

ShaderType values

ValueStage
ShaderType::VertexVertex shader
ShaderType::FragmentFragment shader
ShaderType::GeometryGeometry shader (GL 3.2+)
ShaderType::TessControlTessellation control (GL 4.0+)
ShaderType::TessEvaluationTessellation evaluation (GL 4.0+)
ShaderType::ComputeCompute shader (GL 4.3+)

Compiling a shader

const char* vertSrc = R"(#version 330 core
layout (location = 0) in vec3 aPos;
void main() {
    gl_Position = vec4(aPos, 1.0);
})";

easygl::Shader vert(easygl::ShaderType::Vertex);
vert.create();

try {
    vert.compile_from_source(vertSrc);
} catch (const easygl::Exception& e) {
    std::cerr << "Vertex shader error:\n" << e.what() << '\n';
}

// Check status without exception:
if (!vert.is_compiled()) {
    std::cerr << vert.info_log() << '\n';
}

Attaching to a program — take 1: shared ownership

If you keep the Shader alive and want to reuse it across multiple programs:

easygl::Program prog;
prog.create();
prog.attach(vert);   // const ref — vert is not consumed
prog.attach(frag);
prog.link();
prog.detach(vert);  // good practice: detach after linking
prog.detach(frag);

Attaching to a program — take 2: ownership transfer

Transfer the shader into the program; it will be deleted when the program is destroyed:

prog.attach_owned(vert); // vert is now empty — program owns the GL handle
prog.attach_owned(frag);
prog.link();
// No need to detach — Program deletes owned shaders after link

Compute shader

const char* compSrc = R"(#version 430 core
layout (local_size_x = 8, local_size_y = 8) in;
layout (rgba8, binding = 0) uniform image2D uOutput;

void main() {
    ivec2 coord = ivec2(gl_GlobalInvocationID.xy);
    imageStore(uOutput, coord, vec4(1.0));
})";

easygl::Shader comp(easygl::ShaderType::Compute);
comp.create();
comp.compile_from_source(compSrc);

easygl::Program compProg;
compProg.create();
compProg.attach_owned(comp);
compProg.link();

Method reference

MethodDescription
Shader(ShaderType)Construct with a specific shader stage type.
create()Allocate GL shader handle.
destroy()Free handle. Noexcept.
compile_from_source(src)Set source and compile. Throws on failure.
release_native_handle()Return and clear the handle (used by Program internally).
info_log()Compiler error/warning log string.
shader_type()Returns the ShaderType passed at construction.
is_compiled()True after successful compile_from_source().
is_created()True if GL handle is allocated.
native_handle()Raw GL handle.
is_valid_for_current_generation()False after context loss.
creation_generation()Generation counter at creation time.