HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
ShaderGenerator.h
Go to the documentation of this file.
1 //
2 // Copyright Contributors to the MaterialX Project
3 // SPDX-License-Identifier: Apache-2.0
4 //
5 
6 #ifndef MATERIALX_SHADERGENERATOR_H
7 #define MATERIALX_SHADERGENERATOR_H
8 
9 /// @file
10 /// Base shader generator class
11 
13 
20 
21 #include <MaterialXFormat/File.h>
22 
23 
25 
26 /// @class ShaderGenerator
27 /// Base class for shader generators
28 /// All third-party shader generators should derive from this class.
29 /// Derived classes should use DECLARE_SHADER_GENERATOR / DEFINE_SHADER_GENERATOR
30 /// in their declaration / definition, and register with the Registry class.
32 {
33  public:
34  /// Destructor
35  virtual ~ShaderGenerator() { }
36 
37  /// Return the name of the target this generator is for.
38  virtual const string& getTarget() const
39  {
40  return EMPTY_STRING;
41  }
42 
43  /// Generate a shader starting from the given element, translating
44  /// the element and all dependencies upstream into shader code.
45  virtual ShaderPtr generate(const string&, ElementPtr, GenContext&) const
46  {
47  return nullptr;
48  }
49 
50  /// Start a new scope using the given bracket type.
51  virtual void emitScopeBegin(ShaderStage& stage, Syntax::Punctuation punc = Syntax::CURLY_BRACKETS) const;
52 
53  /// End the current scope.
54  virtual void emitScopeEnd(ShaderStage& stage, bool semicolon = false, bool newline = true) const;
55 
56  /// Start a new line.
57  virtual void emitLineBegin(ShaderStage& stage) const;
58 
59  /// End the current line.
60  virtual void emitLineEnd(ShaderStage& stage, bool semicolon = true) const;
61 
62  /// Add a line break.
63  virtual void emitLineBreak(ShaderStage& stage) const;
64 
65  /// Add a string.
66  virtual void emitString(const string& str, ShaderStage& stage) const;
67 
68  /// Add a single line of code, optionally appending a semicolon.
69  virtual void emitLine(const string& str, ShaderStage& stage, bool semicolon = true) const;
70 
71  /// Add a single line code comment.
72  virtual void emitComment(const string& str, ShaderStage& stage) const;
73 
74  /// Add a block of code.
75  virtual void emitBlock(const string& str, const FilePath& sourceFilename, GenContext& context, ShaderStage& stage) const;
76 
77  /// Add the contents of a standard library include file if not already present.
78  /// The library file prefix of the given context, if any, will be prepended
79  /// to the given filename.
80  virtual void emitLibraryInclude(const FilePath& filename, GenContext& context, ShaderStage& stage) const;
81 
82  /// Add a value.
83  template <typename T>
84  void emitValue(const T& value, ShaderStage& stage) const
85  {
86  stage.addValue<T>(value);
87  }
88 
89  /// Add the function definition for a single node.
90  virtual void emitFunctionDefinition(const ShaderNode& node, GenContext& context, ShaderStage& stage) const;
91 
92  // Emit the connected variable name for an input and output in a function definition (Used by CompoundNode)
93  virtual void emitFunctionDefinitionParameter(const ShaderPort* shaderPort, bool isOutput, GenContext& context, ShaderStage& stage) const;
94 
95  /// Add all function definitions for a graph.
96  virtual void emitFunctionDefinitions(const ShaderGraph& graph, GenContext& context, ShaderStage& stage) const;
97 
98  /// Add the function call for a single node.
99  virtual void emitFunctionCall(const ShaderNode& node, GenContext& context, ShaderStage& stage) const;
100  [[deprecated]] virtual void emitFunctionCall(const ShaderNode& node, GenContext& context, ShaderStage& stage, bool checkScope) const;
101 
102  /// Add all function calls for a graph. If a classification mask is given only functions for
103  /// nodes matching this classification will be emitted.
104  virtual void emitFunctionCalls(const ShaderGraph& graph, GenContext& context, ShaderStage& stage, uint32_t classification = 0u) const;
105 
106  /// Add function calls for nodes connected directly upstream from the given node.
107  /// If a classification mask is given only functions for nodes matching this classification
108  /// will be emitted.
109  virtual void emitDependentFunctionCalls(const ShaderNode& node, GenContext& context, ShaderStage& stage, uint32_t classification = 0u) const;
110 
111  /// Emit code for starting a new function body.
112  virtual void emitFunctionBodyBegin(const ShaderNode& node, GenContext& context, ShaderStage& stage, Syntax::Punctuation punc = Syntax::CURLY_BRACKETS) const;
113 
114  /// Emit code for ending a function body.
115  virtual void emitFunctionBodyEnd(const ShaderNode& node, GenContext& context, ShaderStage& stage) const;
116 
117  /// Emit type definitions for all data types that needs it.
118  virtual void emitTypeDefinitions(GenContext& context, ShaderStage& stage) const;
119 
120  /// Emit the connected variable name for an input,
121  /// or constant value if the port is not connected
122  virtual void emitInput(const ShaderInput* input, GenContext& context, ShaderStage& stage) const;
123 
124  /// Emit the output variable name for an output, optionally including it's type
125  /// and default value assignment.
126  virtual void emitOutput(const ShaderOutput* output, bool includeType, bool assignValue, GenContext& context, ShaderStage& stage) const;
127 
128  /// Emit definitions for all shader variables in a block.
129  /// @param block Block to emit.
130  /// @param qualifier Optional qualifier to add before the variable declaration.
131  /// @param separator Separator to use between the declarations.
132  /// @param context Context for generation.
133  /// @param stage The stage to emit code into.
134  /// @param assignValue If true the variables are initialized with their value.
135  virtual void emitVariableDeclarations(const VariableBlock& block, const string& qualifier, const string& separator, GenContext& context, ShaderStage& stage,
136  bool assignValue = true) const;
137 
138  /// Emit definition of a single shader variable.
139  /// @param variable Shader port representing the variable.
140  /// @param qualifier Optional qualifier to add before the variable declaration.
141  /// @param context Context for generation.
142  /// @param stage The stage to emit code into.
143  /// @param assignValue If true the variable is initialized with its value.
144  virtual void emitVariableDeclaration(const ShaderPort* variable, const string& qualifier, GenContext& context, ShaderStage& stage,
145  bool assignValue = true) const;
146 
147  /// Return true if the node needs the additional ClosureData added
148  virtual bool nodeNeedsClosureData(const ShaderNode& /*node*/) const { return false; }
149 
150  /// Emit the closure data argument if required
151  /// Note this is an affordance for HwShaderGenerator
152  virtual void emitClosureDataArg(const ShaderNode& /*node*/, GenContext& /*context*/, ShaderStage& /*stage*/) const {}
153 
154  /// Emit the closure data parameter if required.
155  /// Note this is an affordance for HwShaderGenerator
156  virtual void emitClosureDataParameter(const ShaderNode& /*node*/, GenContext& /*context*/, ShaderStage& /*stage*/) const {}
157 
158  /// Return the result of an upstream connection or value for an input.
159  virtual string getUpstreamResult(const ShaderInput* input, GenContext& context) const;
160 
161  /// Return the syntax object for the language used by the code generator
162  const Syntax& getSyntax() const { return *_syntax; }
163 
164  /// Register a shader node implementation for a given implementation element name
165  void registerImplementation(const string& name, CreatorFunction<ShaderNodeImpl> creator);
166 
167  /// Register a shader node implementation for a given set of implementation element names
168  void registerImplementation(const StringVec& nameVec, CreatorFunction<ShaderNodeImpl> creator);
169 
170  /// Determine if a shader node implementation has been registered for a given implementation element name
171  bool implementationRegistered(const string& name) const;
172 
173  /// Create the shader node implementation for a NodeGraph implementation.
174  virtual ShaderNodeImplPtr createShaderNodeImplForNodeGraph(const NodeGraph& nodegraph) const;
175 
176  /// Create the shader node implementation for an Implementation implementation.
177  virtual ShaderNodeImplPtr createShaderNodeImplForImplementation(const Implementation& implementation) const;
178 
179  /// Return a registered shader node implementation for the given nodedef.
180  virtual ShaderNodeImplPtr getImplementation(const NodeDef& nodedef, GenContext& context) const;
181 
182  /// Sets the color management system
184  {
185  _colorManagementSystem = colorManagementSystem;
186  }
187 
188  /// Returns the color management system
190  {
191  return _colorManagementSystem;
192  }
193 
194  /// Sets the unit system
195  void setUnitSystem(UnitSystemPtr unitSystem)
196  {
197  _unitSystem = unitSystem;
198  }
199 
200  /// Returns the unit system
202  {
203  return _unitSystem;
204  }
205 
206  /// Returns the type system
208  {
209  return _typeSystem;
210  }
211 
212  /// Return the map of token substitutions used by the generator.
214  {
215  return _tokenSubstitutions;
216  }
217 
218  /// Register a shader graph refactoring pass.
220  {
221  _refactors.push_back(refactor);
222  }
223 
224  /// Return the registered graph refactoring passes.
225  const vector<ShaderGraphRefactorPtr>& getRefactors() const
226  {
227  return _refactors;
228  }
229 
230  /// Apply the default GenOptions for this generator's target.
231  virtual void applyDefaultOptions(GenOptions& options) const;
232 
233  /// Register type definitions from the document.
234  virtual void registerTypeDefs(const DocumentPtr& doc);
235 
236  /// Register metadata that should be exported to the generated shaders.
237  /// Supported metadata includes standard UI attributes like "uiname", "uifolder",
238  /// "uimin", "uimax", etc.
239  /// But it is also extendable by defining custom attributes using AttributeDefs.
240  /// Any AttributeDef in the given document with exportable="true" will be
241  /// exported as shader metadata when found on nodes during shader generation.
242  /// Derived shader generators may override this method to change the registration.
243  /// Applications must explicitly call this method before shader generation to enable
244  /// export of metadata.
245  virtual void registerShaderMetadata(const DocumentPtr& doc, GenContext& context) const;
246 
247  // Retrieve the string used for the LightData.type member variable
248  virtual const string& getLightDataTypevarString() const { return LIGHTDATA_TYPEVAR_STRING; }
249 
250  protected:
251  /// Protected constructor
252  ShaderGenerator(TypeSystemPtr typeSystem, SyntaxPtr syntax);
253 
254  /// Create a new stage in a shader.
255  virtual ShaderStagePtr createStage(const string& name, Shader& shader) const;
256 
257  /// Set function name for a stage.
258  void setFunctionName(const string& functionName, ShaderStage& stage) const
259  {
260  stage.setFunctionName(functionName);
261  }
262 
263  /// Replace tokens with identifiers according to the given substitutions map.
264  void replaceTokens(const StringMap& substitutions, ShaderStage& stage) const;
265 
266  /// Create shader variables (e.g. uniforms, inputs and outputs) for
267  /// nodes that require input data from the application.
268  void createVariables(ShaderGraphPtr graph, GenContext& context, Shader& shader) const;
269 
270  protected:
271  static const string T_FILE_TRANSFORM_UV;
272  static const string LIGHTDATA_TYPEVAR_STRING;
273 
280  vector<ShaderGraphRefactorPtr> _refactors;
281 
282  friend ShaderGraph;
283 };
284 
286 
287 #endif // MATERIALX_SHADERGENERATOR_H
GT_API const UT_StringHolder filename
virtual const string & getLightDataTypevarString() const
ColorManagementSystemPtr _colorManagementSystem
shared_ptr< ShaderNodeImpl > ShaderNodeImplPtr
Shared pointer to a ShaderNodeImpl.
Definition: Library.h:39
Definition: File.h:26
void setFunctionName(const string &functionName, ShaderStage &stage) const
Set function name for a stage.
Factory< ShaderNodeImpl > _implFactory
void addValue(const T &value)
Add a value.
Definition: ShaderStage.h:273
virtual bool nodeNeedsClosureData(const ShaderNode &) const
Return true if the node needs the additional ClosureData added.
void setColorManagementSystem(ColorManagementSystemPtr colorManagementSystem)
Sets the color management system.
shared_ptr< class ShaderGraphRefactor > ShaderGraphRefactorPtr
A shared pointer to a shader graph refactor.
static const string T_FILE_TRANSFORM_UV
#define MATERIALX_NAMESPACE_BEGIN
Definition: Generated.h:25
vector< string > StringVec
A vector of strings.
Definition: Library.h:61
GLsizei const GLfloat * value
Definition: glcorearb.h:824
const Syntax & getSyntax() const
Return the syntax object for the language used by the code generator.
shared_ptr< class UnitSystem > UnitSystemPtr
A shared pointer to a UnitSystem.
Definition: UnitSystem.h:26
vector< ShaderGraphRefactorPtr > _refactors
MATERIALX_NAMESPACE_BEGIN MX_CORE_API const string EMPTY_STRING
shared_ptr< Syntax > SyntaxPtr
Shared pointer to a Syntax.
Definition: Syntax.h:28
void registerRefactor(ShaderGraphRefactorPtr refactor)
Register a shader graph refactoring pass.
#define MX_GENSHADER_API
Definition: Export.h:18
shared_ptr< class TypeSystem > TypeSystemPtr
Definition: TypeDesc.h:219
void setUnitSystem(UnitSystemPtr unitSystem)
Sets the unit system.
const StringMap & getTokenSubstitutions() const
Return the map of token substitutions used by the generator.
TypeSystemPtr _typeSystem
shared_ptr< class ColorManagementSystem > ColorManagementSystemPtr
A shared pointer to a ColorManagementSystem.
void emitValue(const T &value, ShaderStage &stage) const
Add a value.
const vector< ShaderGraphRefactorPtr > & getRefactors() const
Return the registered graph refactoring passes.
UnitSystemPtr _unitSystem
shared_ptr< Document > DocumentPtr
A shared pointer to a Document.
Definition: Document.h:22
virtual void emitClosureDataArg(const ShaderNode &, GenContext &, ShaderStage &) const
GLuint const GLchar * name
Definition: glcorearb.h:786
shared_ptr< class ShaderGraph > ShaderGraphPtr
A shared pointer to a shader graph.
Definition: ShaderGraph.h:40
void setFunctionName(const string &functionName)
Set stage function name.
Definition: ShaderStage.h:293
ColorManagementSystemPtr getColorManagementSystem() const
Returns the color management system.
virtual const string & getTarget() const
Return the name of the target this generator is for.
TypeSystemPtr getTypeSystem() const
Returns the type system.
virtual void emitClosureDataParameter(const ShaderNode &, GenContext &, ShaderStage &) const
GLuint shader
Definition: glcorearb.h:785
Definition: Shader.h:32
shared_ptr< ShaderStage > ShaderStagePtr
Shared pointer to a ShaderStage.
Definition: Library.h:35
Punctuation
Punctuation types.
Definition: Syntax.h:47
UnitSystemPtr getUnitSystem() const
Returns the unit system.
std::unordered_map< string, string > StringMap
An unordered map with strings as both keys and values.
Definition: Library.h:63
shared_ptr< Shader > ShaderPtr
Shared pointer to a Shader.
Definition: Library.h:33
shared_ptr< Element > ElementPtr
A shared pointer to an Element.
Definition: Element.h:31
#define MATERIALX_NAMESPACE_END
Definition: Generated.h:26
static const string LIGHTDATA_TYPEVAR_STRING
virtual ~ShaderGenerator()
Destructor.
Definition: Syntax.h:43
virtual ShaderPtr generate(const string &, ElementPtr, GenContext &) const
StringMap _tokenSubstitutions