Support Forum       Library Source       SourceForge Page       G3D Web Page     
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
Classes | Public Types | Public Member Functions | Static Public Member Functions | Static Public Attributes | Protected Member Functions | Static Protected Member Functions | Protected Attributes | Static Protected Attributes | Friends | List of all members
G3D::Shader Class Reference

Abstraction of the programmable hardware pipeline. More...

Inherits G3D::ReferenceCountedObject.

Classes

class  PreprocessedShaderSource
 A structure containing the individual parts of the code of a load-time preprocessed (by g3d, not the driver) shader. More...
 
class  ShaderProgram
 A wrapper around an actual openGL shader program object. More...
 
class  Source
 Stores either a filename or a shader source string (that has not gone through the g3d preprocessor) for a single shader stage. More...
 
class  Specification
 Consists of up to one Shader::Source per shader stage. More...
 

Public Types

enum  FailureBehavior {
  EXCEPTION,
  PROMPT,
  SILENT
}
 Determines the behavior upon a load-time or compile-time error for all shaders. More...
 
enum  RecoverableErrorType {
  LOAD_ERROR,
  COMPILATION_ERROR
}
 
typedef shared_ptr< ShaderRef
 
enum  ShaderStage {
  VERTEX,
  TESSELLATION_CONTROL,
  TESSELLATION_EVAL,
  GEOMETRY,
  PIXEL,
  STAGE_COUNT
}
 
enum  SourceType {
  FILE,
  STRING
}
 

Public Member Functions

void bindStreamArg (const std::string &name, const AttributeArray &vertexRange, const ShaderProgram::AttributeDeclaration &decl)
 Bind a single vertex attribute.
 
void bindStreamArgs (const ShaderProgram::Ref &program, const Args &args, RenderDevice *rd)
 Iterate over all formal parameters and bind all vertex attributes appropriately.
 
void bindUniformArg (const Args::Arg &arg, const ShaderProgram::UniformDeclaration &decl)
 Bind a single uniform variable.
 
void bindUniformArgs (const ShaderProgram::Ref &program, const Args &args, bool g3dPass)
 Iterate over all formal parameters and bind all non-dummy variables appropriately.
 
shared_ptr< ShaderProgramcompileAndBind (const Args &args, RenderDevice *rd)
 Compile the shader and bind the arguments as necessary.
 
bool g3dLoadTimePreprocessor (const std::string &dir, PreprocessedShaderSource &source, std::string &messages)
 Execute all steps of our load-time preprocessor engine.
 
void load ()
 Load the shaders from files on disk, and run the preprocessor.
 
bool processIncludes (const std::string &dir, std::string &code, std::string &messages)
 Replaces all #includes in code with the contents of the appropriate files.
 
void reload ()
 Reload this shader from the files on disk, if it was loaded from disk.
 
ShaderProgram::Ref retry (const Args &args)
 Reload from files on disk (if it was loaded from disk), run all steps of the g3d preprocessor and recompile.
 
void setG3DArgs (const shared_ptr< ShaderProgram > &p, Args &args, RenderDevice *renderDevice, const Args &sourceArgs)
 Sets the g3d uniform variables such as g3d_objectToWorldMatrix (using values from.
 

Static Public Member Functions

static GLenum canonicalType (GLenum e)
 Converts texture types to their canonical value (anything that can be a sampler2D becomes GL_TEXTURE_2D, etc) all others are unmodified.
 
static Ref create (const Specification &s)
 Creates a shader from the given specification, loads it from disk, and applies the g3d preprocessor.
 
static Ref fromFiles (const std::string &f0, const std::string &f1="", const std::string &f2="", const std::string &f3="", const std::string &f4="")
 
 
static bool isSamplerType (GLenum type)
 True if.
 
static bool processVersion (std::string &code, std::string &versionLine)
 Reads the code looking for a #version line (spaces allowed after "#").
 
static void reloadAll ()
 Reloads all shaders throughout G3D.
 
static void setFailureBehavior (FailureBehavior f)
 Set the global failure behavior.
 

Static Public Attributes

static FailureBehavior s_failureBehavior
 

Protected Member Functions

 Shader (const Specification &s)
 No compilation, or even loading from files is performed at construction.
 
std::string getLinePragma (int lineNumber, const std::string &filename)
 Returns a line directive in the format "#line X Y\n", where X is the lineNumber, and Y is an integer that maps to filename.
 
void handleRecoverableError (RecoverableErrorType eType, const Args &args, const std::string &message, ShaderProgram::Ref &program)
 Handle a compilation or loading error as specified by s_failureBehavior.
 
Shader::ShaderProgram::Ref shaderProgram (const Args &args, std::string &messages)
 Finds a shader program in the cache that matches the supplied args, recompiling if necessary.
 

Static Protected Member Functions

static int countNewlines (const std::string &s)
 Number of new lines in the given string.
 
static size_t findLastPragmaWithSpaces (const std::string &macro, const std::string &code, size_t offset=std::string::npos)
 Returns the position of the last pragma of the form "#macro" (with any number of spaces between the # and macro) in code, starting from the.
 
static GLenum toGLType (const std::string &s)
 Converts a type name to a GL enum.
 

Protected Attributes

Table< std::string,
ShaderProgram::Ref
m_compilationCache
 Maps preamble + macro definitions to compiled shaders.
 
Table< std::string, intm_fileNameToIndexTable
 Maps filenames to indices, so that we can correctly print #line directives.
 
Args m_g3dUniformArgs
 A set of args solely for g3d uniforms.
 
Table< int, std::stringm_indexToFilenameTable
 Maps indices to filenames, so that we can correctly output filenames when we get file indices back from the shader on error messages.
 
int m_nextUnusedFileIndex
 The next index to be used by a previously unprocessed file when #including, so that we can produce proper #line directives.
 
Array< PreprocessedShaderSourcem_preprocessedSource
 The source code for a shader from the STAGE_COUNT stages.
 
Specification m_specification
 Contains the filenames or hardcoded source strings this shader was constructed from.
 

Static Protected Attributes

static Array< weak_ptr< Shader > > s_allShaders
 Array of all shaders ever created.
 

Friends

class RenderDevice
 

Detailed Description

Abstraction of the programmable hardware pipeline.

Commonly initialized with the idiom:

m_toonShader = Shader::fromFiles("toon.vrt", "toon.pix");

or

Shader::Specification toonShaderSpec;
toonShaderSpec[Shader::VERTEX] = STR(
void main() {
gl_Position = ...
});
m_toonShader = Shader::create(toonShaderSpec);

Note that G3D introduces two preprocessor pragmas to GLSL: #include and #for, evaluated at load-time and compile-time respectively.

G3D has two distinct preprocessing steps for shaders: load-time and compile-time.

The load-time preprocessor is documented in Shader::g3dLoadTimePreprocessor().

The compile-time preprocessor currently only prepends Args::preambleAndMacroString() and evaluates the #for pragma ( Shader::expandLoopPragmas() )

Member Typedef Documentation

typedef shared_ptr<Shader> G3D::Shader::Ref

Member Enumeration Documentation

Determines the behavior upon a load-time or compile-time error for all shaders.

Enumerator:
EXCEPTION 

Throw an exception on load or compilation failure.

PROMPT 

Prompt the user to throw an exception, abort the program, or retry loading on load or compilation failure.

(default)

SILENT 

ok() will be false if an error occurs

Enumerator:
LOAD_ERROR 
COMPILATION_ERROR 
Enumerator:
VERTEX 
TESSELLATION_CONTROL 

In DirectX, this is called the Hull Shader.

TESSELLATION_EVAL 

In DirectX, this is called the Domain Shader.

GEOMETRY 
PIXEL 

Sometimes referred to as the Fragment Shader.

STAGE_COUNT 
Enumerator:
FILE 
STRING 

Constructor & Destructor Documentation

G3D::Shader::Shader ( const Specification s)
protected

No compilation, or even loading from files is performed at construction.

Member Function Documentation

void G3D::Shader::bindStreamArg ( const std::string name,
const AttributeArray vertexRange,
const ShaderProgram::AttributeDeclaration decl 
)

Bind a single vertex attribute.

void G3D::Shader::bindStreamArgs ( const ShaderProgram::Ref program,
const Args args,
RenderDevice rd 
)

Iterate over all formal parameters and bind all vertex attributes appropriately.

Also sets the glPatchParameter if the primitive type is patch.

void G3D::Shader::bindUniformArg ( const Args::Arg arg,
const ShaderProgram::UniformDeclaration decl 
)

Bind a single uniform variable.

void G3D::Shader::bindUniformArgs ( const ShaderProgram::Ref program,
const Args args,
bool  g3dPass 
)

Iterate over all formal parameters and bind all non-dummy variables appropriately.

If

Parameters
g3dPassis true, ignore all variables not starting with "g3d_", if it is false, ignore all variables that do start with "g3d_"
static GLenum G3D::Shader::canonicalType ( GLenum  e)
static

Converts texture types to their canonical value (anything that can be a sampler2D becomes GL_TEXTURE_2D, etc) all others are unmodified.

shared_ptr<ShaderProgram> G3D::Shader::compileAndBind ( const Args args,
RenderDevice rd 
)

Compile the shader and bind the arguments as necessary.

Adds the necessary g3d uniforms to args

static int G3D::Shader::countNewlines ( const std::string s)
staticprotected

Number of new lines in the given string.

static Ref G3D::Shader::create ( const Specification s)
static

Creates a shader from the given specification, loads it from disk, and applies the g3d preprocessor.

static size_t G3D::Shader::findLastPragmaWithSpaces ( const std::string macro,
const std::string code,
size_t  offset = std::string::npos 
)
staticprotected

Returns the position of the last pragma of the form "#macro" (with any number of spaces between the # and macro) in code, starting from the.

Parameters
offset
static Ref G3D::Shader::fromFiles ( const std::string f0,
const std::string f1 = "",
const std::string f2 = "",
const std::string f3 = "",
const std::string f4 = "" 
)
static

bool G3D::Shader::g3dLoadTimePreprocessor ( const std::string dir,
PreprocessedShaderSource source,
std::string messages 
)

Execute all steps of our load-time preprocessor engine.

Process Includes (adding #line directives where neccessary) Process Version Line Add G3D #defines Add G3D uniform declarations

The G3D uniforms are as follows:

uniform mat4x3 g3d_WorldToObjectMatrix; uniform mat4x3 g3d_ObjectToWorldMatrix; uniform mat4 g3d_ProjectionMatrix; uniform mat3 g3d_WorldToObjectNormalMatrix; uniform mat3 g3d_ObjectToWorldNormalMatrix; uniform mat3 g3d_ObjectToCameraNormalMatrix; uniform mat3 g3d_CameraToObjectNormalMatrix; uniform mat4x3 g3d_WorldToCameraMatrix; uniform mat4x3 g3d_CameraToWorldMatrix; uniform bool g3d_InvertY; uniform mat4 g3d_ModelViewProjectionMatrix; uniform mat3 g3d_WorldToCameraNormalMatrix;

Parameters
messagesAny errors regarding inclusion of files are written here
Returns
True if no error occured during inclusion of other files
std::string G3D::Shader::getLinePragma ( int  lineNumber,
const std::string filename 
)
protected

Returns a line directive in the format "#line X Y\n", where X is the lineNumber, and Y is an integer that maps to filename.

void G3D::Shader::handleRecoverableError ( RecoverableErrorType  eType,
const Args args,
const std::string message,
ShaderProgram::Ref program 
)
protected

Handle a compilation or loading error as specified by s_failureBehavior.

If this handles a compilation error, program can be overwritten with a correctly compiled shader (if s_failureBehaviord is PROMPT and the user reloads).

static bool G3D::Shader::isSamplerType ( GLenum  type)
static

True if.

Parameters
typecorresponding to an OpenGL sampler type.
void G3D::Shader::load ( )

Load the shaders from files on disk, and run the preprocessor.

bool G3D::Shader::processIncludes ( const std::string dir,
std::string code,
std::string messages 
)

Replaces all #includes in code with the contents of the appropriate files.

It is called recursively, so included files may have includes themselves. This is called automatically by the preprocessor, but is public so as to be accessible to code that directly manipulates source strings.

Parameters
dirThe directory from which the parent was loaded.
messagesAny errors regarding inclusion of files are written here
Returns
True if no error occured during inclusion of other files
static bool G3D::Shader::processVersion ( std::string code,
std::string versionLine 
)
static

Reads the code looking for a #version line (spaces allowed after "#").

If one is found, remove it from

Parameters
codeand put it in
versionLine,otherwiseset versionLine to "#version 120\n".
Returns
True if we found and removed a version line from the code.
void G3D::Shader::reload ( )

Reload this shader from the files on disk, if it was loaded from disk.

static void G3D::Shader::reloadAll ( )
static

Reloads all shaders throughout G3D.

ShaderProgram::Ref G3D::Shader::retry ( const Args args)

Reload from files on disk (if it was loaded from disk), run all steps of the g3d preprocessor and recompile.

static void G3D::Shader::setFailureBehavior ( FailureBehavior  f)
static

Set the global failure behavior.

See Shader::FailureBehavior

void G3D::Shader::setG3DArgs ( const shared_ptr< ShaderProgram > &  p,
Args args,
RenderDevice renderDevice,
const Args sourceArgs 
)

Sets the g3d uniform variables such as g3d_objectToWorldMatrix (using values from.

Parameters
renderDevice)
args.See Shader::g3dLoadTimePreprocessor for the declarations of all of the variables of this form that can be set by this function.

Also sets all uniforms of the form g3d_sz2D_textureName, where textureName is the name of any sampler type bound in sourceArgs. g3d_sz2D_textureName is a vec4 of the form (w, h, 1.0/w, 1.0/h), where w and h are the width and height of the texture named textureName.

Shader::ShaderProgram::Ref G3D::Shader::shaderProgram ( const Args args,
std::string messages 
)
protected

Finds a shader program in the cache that matches the supplied args, recompiling if necessary.

if compilation fails, returns NULL and fills in messages with a report of what went wrong. Primarily intended for internal use by Shader; called from compileAndBind() and its variants.

static GLenum G3D::Shader::toGLType ( const std::string s)
staticprotected

Converts a type name to a GL enum.

Friends And Related Function Documentation

friend class RenderDevice
friend

Member Data Documentation

Table<std::string, ShaderProgram::Ref > G3D::Shader::m_compilationCache
protected

Maps preamble + macro definitions to compiled shaders.

Table<std::string, int> G3D::Shader::m_fileNameToIndexTable
protected

Maps filenames to indices, so that we can correctly print #line directives.

Args G3D::Shader::m_g3dUniformArgs
protected

A set of args solely for g3d uniforms.

We use this instead of modifying the args passed into compileAndBind(). This needs to be cleared every time we reload, or we will accidentally bind variables that don't exist in the compiled shader

Table<int, std::string> G3D::Shader::m_indexToFilenameTable
protected

Maps indices to filenames, so that we can correctly output filenames when we get file indices back from the shader on error messages.

int G3D::Shader::m_nextUnusedFileIndex
protected

The next index to be used by a previously unprocessed file when #including, so that we can produce proper #line directives.

Array<PreprocessedShaderSource> G3D::Shader::m_preprocessedSource
protected

The source code for a shader from the STAGE_COUNT stages.

Specification G3D::Shader::m_specification
protected

Contains the filenames or hardcoded source strings this shader was constructed from.

Array< weak_ptr<Shader> > G3D::Shader::s_allShaders
staticprotected

Array of all shaders ever created.

NULL elements are flushed during reloadAll()

FailureBehavior G3D::Shader::s_failureBehavior
static

documentation generated on Sat Jan 12 2013 22:49:57 using doxygen 1.8.2