PShader
Data / CompositeDescription
Datatype for GLSL shaders. Load with loadShader() and apply with shader().
Syntax
PShader* s = loadShader("frag.glsl")
Parameters
None
Returns
PShaderMethods
| set(std::string name, float v) | Set a uniform float |
| set(std::string name, int v) | Set a uniform int |
| set(std::string name, float x, float y) | Set a uniform vec2 |
| set(std::string name, float x, float y, float z) | Set a uniform vec3 |
| bind() | Activate the shader |
| unbind() | Deactivate the shader |
Related
Under the Hood
From Processing.h:
class PShader {
public:
GLuint program = 0, vert = 0, frag = 0;
std::string vertSrc, fragSrc;
bool linked = false;
PShader() = default;
PShader(const std::string& v, const std::string& f) : vertSrc(v), fragSrc(f) {}
static GLuint compileShader(GLenum type, const std::string& src) {
GLuint s = glCreateShader(type);
const char* c = src.c_str();
glShaderSource(s, 1, &c, nullptr);
glCompileShader(s);
GLint ok; glGetShaderiv(s, GL_COMPILE_STATUS, &ok);
if (!ok) { char log[512]; glGetShaderInfoLog(s,512,nullptr,log); std::cerr<<"Shader error: "<<log<<"\n"; }
return s;
}
void compile() {
vert = compileShader(GL_VERTEX_SHADER, vertSrc);
frag = compileShader(GL_FRAGMENT_SHADER, fragSrc);
program = glCreateProgram();
glAttachShader(program,vert); glAttachShader(program,frag);
glLinkProgram(program);
GLint ok; glGetProgramiv(program,GL_LINK_STATUS,&ok);
if (!ok) { char log[512]; glGetProgramInfoLog(program,512,nullptr,log); std::cerr<<"Link error: "<<log<<"\n"; }
linked = ok;
}
void bind() { if (linked) glUseProgram(program); }
void unbind() { glUseProgram(0); }
void set(const std::string& n, float v) { glUniform1f(glGetUniformLocation(program,n.c_str()),v); }
void set(const std::string& n, int v) { glUniform1i(glGetUniformLocation(program,n.c_str()),v); }
void set(const std::string& n, float x, float y) { glUniform2f(glGetUniformLocation(program,n.c_str()),x,y); }
void set(const std::string& n, float x, float y, float z) { glUniform3f(glGetUniformLocation(program,n.c_str()),x,y,z); }
void set(const std::string& n, float x, float y, float z, float w){ glUniform4f(glGetUniformLocation(program,n.c_str()),x,y,z,w); }
~PShader() { if(program)glDeleteProgram(program); if(vert)glDeleteShader(vert); if(frag)glDeleteShader(frag); }
PShader(const PShader&) __attribute__((error(
"E0003: PShader value-style copying is not supported. "
"Declare PShader* instead of PShader. "
"See https://processing-cpp.github.io/error/E0003.html"
)));
PShader& operator=(const PShader&) __attribute__((error(
"E0003: PShader value-style assignment is not supported. "
"Declare PShader* instead of PShader. "
"See https://processing-cpp.github.io/error/E0003.html"
)));
PShader(PShader&& o) noexcept
: program(o.program),vert(o.vert),frag(o.frag),
vertSrc(o.vertSrc),fragSrc(o.fragSrc),linked(o.linked)
{ o.program=o.vert=o.frag=0; }
};