diff --git a/documents/Specification/MaterialX.v1.37.PBRSpec.pdf b/documents/Specification/MaterialX.v1.37.PBRSpec.pdf new file mode 100644 index 0000000000..95c90b4ea5 Binary files /dev/null and b/documents/Specification/MaterialX.v1.37.PBRSpec.pdf differ diff --git a/documents/Specification/MaterialX.v1.37.Spec.pdf b/documents/Specification/MaterialX.v1.37.Spec.pdf new file mode 100644 index 0000000000..f005550ddb Binary files /dev/null and b/documents/Specification/MaterialX.v1.37.Spec.pdf differ diff --git a/documents/Specification/MaterialX.v1.37.Supplement.pdf b/documents/Specification/MaterialX.v1.37.Supplement.pdf new file mode 100644 index 0000000000..4c3305f540 Binary files /dev/null and b/documents/Specification/MaterialX.v1.37.Supplement.pdf differ diff --git a/documents/Specification/ShaderX.Draft.pdf b/documents/Specification/ShaderX.Draft.pdf deleted file mode 100644 index 244787b34f..0000000000 Binary files a/documents/Specification/ShaderX.Draft.pdf and /dev/null differ diff --git a/source/MaterialXContrib/MaterialXMaya/ShadingNodeOverrides.cpp b/source/MaterialXContrib/MaterialXMaya/ShadingNodeOverrides.cpp index c08a9accdb..2ab1fe3f0d 100644 --- a/source/MaterialXContrib/MaterialXMaya/ShadingNodeOverrides.cpp +++ b/source/MaterialXContrib/MaterialXMaya/ShadingNodeOverrides.cpp @@ -76,12 +76,25 @@ MStatus bindFileTexture(MHWRender::MShaderInstance& shader, mTilePositions.append(udimCoordinates[i][0]); mTilePositions.append(udimCoordinates[i][1]); } - const unsigned int UDIM_BAKE_WIDTH = 4096; - const unsigned int UDIM_BAKE_HEIGHT = 4096; + mx::Vector2 scaleUV; + mx::Vector2 offsetUV; + mx::getUdimScaleAndOffset(udimCoordinates, scaleUV, offsetUV); + + unsigned int udimBakeWidth = 4096; + unsigned int udimBakeHeight = 4096; + float ratio = scaleUV[1] / scaleUV[0]; + if (ratio > 1.0) + { + udimBakeHeight = static_cast(std::truncf(static_cast(udimBakeHeight) * ratio)); + } + else + { + udimBakeWidth = static_cast(std::truncf(static_cast(udimBakeWidth) * ratio)); + } // Note: we do not use the uv scale and offset. Ideally this should be used for the texture lookup code // but at this point the shader code has already been generated. texturePtr.reset(textureManager->acquireTiledTexture(fileName.c_str(), mTilePaths, mTilePositions, - undefinedColor, UDIM_BAKE_WIDTH, UDIM_BAKE_HEIGHT, + undefinedColor, udimBakeWidth, udimBakeHeight, failedTilePaths, uvScaleOffset)); } else @@ -246,7 +259,7 @@ void ShadingNodeOverride::updateShader(MHWRender::MShaderInstance& shader, // Set up image file name search path. mx::FilePath documentPath(node->getDocumentFilePath().asChar()); - documentPath.pop(); + documentPath = documentPath.getParentPath(); mx::FileSearchPath imageSearchPath = Plugin::instance().getResourceSearchPath(); imageSearchPath.prepend(documentPath); diff --git a/source/MaterialXCore/Document.cpp b/source/MaterialXCore/Document.cpp index e6a49f22ad..6ae2ee45d0 100644 --- a/source/MaterialXCore/Document.cpp +++ b/source/MaterialXCore/Document.cpp @@ -190,6 +190,19 @@ void Document::importLibrary(const ConstDocumentPtr& library, const CopyOptions* } } +StringSet Document::getReferencedSourceUris() const +{ + StringSet sourceUris; + for (ElementPtr elem : traverseTree()) + { + if (elem->hasSourceUri()) + { + sourceUris.insert(elem->getSourceUri()); + } + } + return sourceUris; +} + std::pair Document::getVersionIntegers() const { if (!hasVersionString()) diff --git a/source/MaterialXCore/Document.h b/source/MaterialXCore/Document.h index 26a0475d41..289ea2ef18 100644 --- a/source/MaterialXCore/Document.h +++ b/source/MaterialXCore/Document.h @@ -65,6 +65,9 @@ class Document : public GraphElement /// import function. Defaults to a null pointer. void importLibrary(const ConstDocumentPtr& library, const CopyOptions* copyOptions = nullptr); + /// Get a list of source URI's referenced by the document + StringSet getReferencedSourceUris() const; + /// @} /// @name NodeGraph Elements /// @{ diff --git a/source/MaterialXCore/Element.h b/source/MaterialXCore/Element.h index 2b32b1cedd..47b32928eb 100644 --- a/source/MaterialXCore/Element.h +++ b/source/MaterialXCore/Element.h @@ -73,6 +73,8 @@ class Element : public std::enable_shared_from_this } public: virtual ~Element() { } + Element(const Element&) = delete; + Element& operator=(const Element&) = delete; protected: using DocumentPtr = shared_ptr; @@ -447,10 +449,7 @@ class Element : public std::enable_shared_from_this ElementPtr getChild(const string& name) const { ElementMap::const_iterator it = _childMap.find(name); - if (it == _childMap.end()) - return ElementPtr(); - else - return it->second; + return (it != _childMap.end()) ? it->second : ElementPtr(); } /// Return the child element, if any, with the given name and subclass. @@ -525,10 +524,7 @@ class Element : public std::enable_shared_from_this const string& getAttribute(const string& attrib) const { StringMap::const_iterator it = _attributeMap.find(attrib); - if (it == _attributeMap.end()) - return EMPTY_STRING; - else - return it->second; + return (it != _attributeMap.end()) ? it->second : EMPTY_STRING; } /// Return a vector of stored attribute names, in the order they were set. @@ -548,7 +544,7 @@ class Element : public std::enable_shared_from_this /// Return the the value of an implicitly typed attribute. If the given /// attribute is not present, or cannot be converted to the given data /// type, then the zero value for the data type is returned. - template const T getTypedAttribute(const string& attrib) const + template T getTypedAttribute(const string& attrib) const { try { @@ -870,9 +866,6 @@ class Element : public std::enable_shared_from_this weak_ptr _root; private: - Element(const Element&) = delete; - Element& operator=(const Element&) = delete; - template static ElementPtr createElement(ElementPtr parent, const string& name) { return std::make_shared(parent, name); @@ -1037,6 +1030,12 @@ class ValueElement : public TypedElement setValueString(toValueString(value)); } + /// Set the typed value of an element from a C-style string. + void setValue(const char* value, const string& type = EMPTY_STRING) + { + setValue(value ? string(value) : EMPTY_STRING, type); + } + /// Return true if the element possesses a typed value. bool hasValue() const { diff --git a/source/MaterialXCore/Library.h b/source/MaterialXCore/Library.h index cee417b3db..c0be61afbb 100644 --- a/source/MaterialXCore/Library.h +++ b/source/MaterialXCore/Library.h @@ -42,13 +42,11 @@ class Exception : public std::exception { public: explicit Exception(const string& msg) : - std::exception(), _msg(msg) { } Exception(const Exception& e) : - std::exception(), _msg(e._msg) { } diff --git a/source/MaterialXCore/Value.cpp b/source/MaterialXCore/Value.cpp index c8429229ea..2da8f0e4d3 100644 --- a/source/MaterialXCore/Value.cpp +++ b/source/MaterialXCore/Value.cpp @@ -30,12 +30,12 @@ template class is_std_vector< vector > : public std::true_type { }; template using enable_if_std_vector_t = typename std::enable_if::value, T>::type; -template void stringToData(const string& value, T& data) +template void stringToData(const string& str, T& data) { - std::stringstream ss(value); + std::stringstream ss(str); if (!(ss >> data)) { - throw ExceptionTypeError("Type mismatch in generic stringToData: " + value); + throw ExceptionTypeError("Type mismatch in generic stringToData: " + str); } } diff --git a/source/MaterialXCore/Value.h b/source/MaterialXCore/Value.h index 51a938334b..17e5ea043e 100644 --- a/source/MaterialXCore/Value.h +++ b/source/MaterialXCore/Value.h @@ -12,6 +12,7 @@ #include #include +#include namespace MaterialX { @@ -49,6 +50,12 @@ class Value return std::make_shared< TypedValue >(data); } + // Create a new value from a C-style string. + static ValuePtr createValue(const char* data) + { + return createValue(data ? string(data) : EMPTY_STRING); + } + /// Create a new value instance from value and type strings. /// @return A shared pointer to a typed value, or an empty shared pointer /// if the conversion to the given data type cannot be performed. diff --git a/source/MaterialXFormat/File.cpp b/source/MaterialXFormat/File.cpp index 2a9e3f6c91..612b29d021 100644 --- a/source/MaterialXFormat/File.cpp +++ b/source/MaterialXFormat/File.cpp @@ -25,8 +25,7 @@ namespace MaterialX { -const string VALID_SEPARATORS_WINDOWS = "/\\"; -const string VALID_SEPARATORS_POSIX = "/"; +const string VALID_SEPARATORS = "/\\"; const char PREFERRED_SEPARATOR_WINDOWS = '\\'; const char PREFERRED_SEPARATOR_POSIX = '/'; @@ -42,13 +41,17 @@ const string MATERIALX_SEARCH_PATH_ENV_VAR = "MATERIALX_SEARCH_PATH"; // FilePath methods // -void FilePath::assign(const string& str, Format format) +void FilePath::assign(const string& str) { _type = TypeRelative; - if (format == FormatWindows) + _vec = splitString(str, VALID_SEPARATORS); + if (!str.empty()) { - _vec = splitString(str, VALID_SEPARATORS_WINDOWS); - if (str.size() >= 2) + if (str[0] == PREFERRED_SEPARATOR_POSIX) + { + _type = TypeAbsolute; + } + else if (str.size() >= 2) { if (std::isalpha(str[0]) && str[1] == ':') { @@ -60,15 +63,6 @@ void FilePath::assign(const string& str, Format format) } } } - else - { - _vec = splitString(str, VALID_SEPARATORS_POSIX); - if (!str.empty() && str[0] == PREFERRED_SEPARATOR_POSIX) - { - _type = TypeAbsolute; - } - } - _format = format; } string FilePath::asString(Format format) const @@ -109,10 +103,6 @@ FilePath FilePath::operator/(const FilePath& rhs) const { throw Exception("Appended path must be relative."); } - if (_format != rhs._format) - { - throw Exception("Appended path must have the same format."); - } FilePath combined(*this); for (const string& str : rhs._vec) @@ -122,14 +112,6 @@ FilePath FilePath::operator/(const FilePath& rhs) const return combined; } -void FilePath::pop() -{ - if (!isEmpty()) - { - _vec.pop_back(); - } -} - bool FilePath::exists() const { #if defined(_WIN32) diff --git a/source/MaterialXFormat/File.h b/source/MaterialXFormat/File.h index 53c801f0f1..8f50fa06be 100644 --- a/source/MaterialXFormat/File.h +++ b/source/MaterialXFormat/File.h @@ -45,8 +45,7 @@ class FilePath public: FilePath() : - _type(TypeRelative), - _format(FormatNative) + _type(TypeRelative) { } ~FilePath() { } @@ -54,8 +53,7 @@ class FilePath bool operator==(const FilePath& rhs) const { return _vec == rhs._vec && - _type == rhs._type && - _format == rhs._format; + _type == rhs._type; } bool operator!=(const FilePath& rhs) const { @@ -71,14 +69,20 @@ class FilePath assign(str); } + /// Construct a path from a C-style string. + FilePath(const char* str) + { + assign(string(str)); + } + /// Convert a path to a standard string. operator string() const { return asString(); } - /// Assign a path from a standard string with the given format. - void assign(const string& str, Format format = FormatNative); + /// Assign a path from a standard string. + void assign(const string& str); /// Return this path as a standard string with the given format. string asString(Format format = FormatNative) const; @@ -106,6 +110,18 @@ class FilePath return _vec[_vec.size() - 1]; } + /// Return the parent directory of the given path, if any. If no + /// parent directory is present, then the empty path is returned. + FilePath getParentPath() const + { + FilePath parent(*this); + if (!parent.isEmpty()) + { + parent._vec.pop_back(); + } + return parent; + } + /// Return the file extension of the given path. string getExtension() const { @@ -118,9 +134,6 @@ class FilePath /// combined path. FilePath operator/(const FilePath& rhs) const; - /// Set the path to the parent directory if one exists. - void pop(); - /// @} /// @name File System Operations /// @{ @@ -148,7 +161,6 @@ class FilePath private: StringVec _vec; Type _type; - Format _format; }; /// @class FileSearchPath @@ -156,6 +168,10 @@ class FilePath /// of a given filename on the file system. class FileSearchPath { + public: + using Iterator = FilePathVec::iterator; + using ConstIterator = FilePathVec::const_iterator; + public: FileSearchPath() { @@ -166,21 +182,9 @@ class FileSearchPath /// @param searchPath A string containing a sequence of file paths joined /// by separator characters. /// @param sep The set of separator characters used in the search path. - /// Defaults to the semicolon character. - FileSearchPath(const string& searchPath, const string& sep = PATH_LIST_SEPARATOR) : - FileSearchPath() + /// Defaults to the PATH_LIST_SEPARATOR character. + FileSearchPath(const string& searchPath, const string& sep = PATH_LIST_SEPARATOR) { - parse(searchPath, sep); - } - - /// Parse a given path and append to the sequence - void parse(const string& searchPath, const string& sep = PATH_LIST_SEPARATOR) - { - if (searchPath.empty()) - { - return; - } - for (const string& path : splitString(searchPath, sep)) { if (!path.empty()) @@ -214,18 +218,12 @@ class FileSearchPath /// Append the given search path to the sequence. void append(const FileSearchPath& searchPath) { - for (const FilePath& path : searchPath.paths()) + for (const FilePath& path : searchPath) { _paths.push_back(path); } } - /// Get list of paths in the search path. - const FilePathVec& paths() const - { - return _paths; - } - /// Prepend the given path to the sequence. void prepend(const FilePath& path) { @@ -238,6 +236,12 @@ class FileSearchPath return _paths.size(); } + /// Return true if the search path is empty. + bool isEmpty() const + { + return _paths.empty(); + } + /// Return the path at the given index. FilePath& operator[](size_t index) { @@ -274,6 +278,17 @@ class FileSearchPath return filename; } + /// @name Iterators + /// @{ + + Iterator begin() { return _paths.begin(); } + ConstIterator begin() const { return _paths.begin(); } + + Iterator end() { return _paths.end(); } + ConstIterator end() const { return _paths.end(); } + + /// @} + private: FilePathVec _paths; }; diff --git a/source/MaterialXFormat/XmlIo.cpp b/source/MaterialXFormat/XmlIo.cpp index f55c2cfc15..0c033f815b 100644 --- a/source/MaterialXFormat/XmlIo.cpp +++ b/source/MaterialXFormat/XmlIo.cpp @@ -5,16 +5,13 @@ #include -#include - #include #include -#include +#include #include #include -#include using namespace pugi; @@ -120,36 +117,35 @@ void elementToXml(ConstElementPtr elem, xml_node& xmlNode, const XmlWriteOptions } } -void xmlDocumentFromFile(xml_document& xmlDoc, string filename, const string& searchPath) +void xmlDocumentFromFile(xml_document& xmlDoc, FilePath filename, FileSearchPath searchPath) { - FileSearchPath fileSearchPath = FileSearchPath(searchPath); - fileSearchPath.append(getEnvironmentPath()); + searchPath.append(getEnvironmentPath()); - filename = fileSearchPath.find(filename); + filename = searchPath.find(filename); - xml_parse_result result = xmlDoc.load_file(filename.c_str()); + xml_parse_result result = xmlDoc.load_file(filename.asString().c_str()); if (!result) { if (result.status == xml_parse_status::status_file_not_found || result.status == xml_parse_status::status_io_error || result.status == xml_parse_status::status_out_of_memory) { - throw ExceptionFileMissing("Failed to open file for reading: " + filename); + throw ExceptionFileMissing("Failed to open file for reading: " + filename.asString()); } else { string desc = result.description(); string offset = std::to_string(result.offset); - throw ExceptionParseError("XML parse error in file: " + filename + + throw ExceptionParseError("XML parse error in file: " + filename.asString() + " (" + desc + " at character " + offset + ")"); } } } -void processXIncludes(DocumentPtr doc, xml_node& xmlNode, const string& searchPath, const XmlReadOptions* readOptions) +void processXIncludes(DocumentPtr doc, xml_node& xmlNode, const FileSearchPath& searchPath, const XmlReadOptions* readOptions) { // Search path for includes. Set empty and then evaluated once in the iteration through xml includes. - string includeSearchPath; + FileSearchPath includeSearchPath; XmlReadFunction readXIncludeFunction = readOptions ? readOptions->readXIncludeFunction : readFromXmlFile; xml_node xmlChild = xmlNode.first_child(); @@ -179,22 +175,21 @@ void processXIncludes(DocumentPtr doc, xml_node& xmlNode, const string& searchPa // Prepend the directory of the parent to accomodate // includes relative the the parent file location. - if (includeSearchPath.empty()) + if (includeSearchPath.isEmpty()) { string parentUri = doc->getSourceUri(); if (!parentUri.empty()) { - FileSearchPath fileSearchPath(searchPath); - FilePath filePath = fileSearchPath.find(parentUri); + FilePath filePath = searchPath.find(parentUri); if (!filePath.isEmpty()) { // Remove the file name from the path as we want the path to the containing folder. - filePath.pop(); - includeSearchPath = filePath.asString() + PATH_LIST_SEPARATOR + searchPath; + includeSearchPath = searchPath; + includeSearchPath.prepend(filePath.getParentPath()); } } // Set default search path if no parent path found - if (includeSearchPath.empty()) + if (includeSearchPath.isEmpty()) { includeSearchPath = searchPath; } @@ -219,7 +214,7 @@ void processXIncludes(DocumentPtr doc, xml_node& xmlNode, const string& searchPa void documentFromXml(DocumentPtr doc, const xml_document& xmlDoc, - const string& searchPath = EMPTY_STRING, + const FileSearchPath& searchPath = FileSearchPath(), const XmlReadOptions* readOptions = nullptr) { ScopedUpdate update(doc); @@ -283,7 +278,7 @@ void readFromXmlStream(DocumentPtr doc, std::istream& stream, const XmlReadOptio documentFromXml(doc, xmlDoc, EMPTY_STRING, readOptions); } -void readFromXmlFile(DocumentPtr doc, const string& filename, const string& searchPath, const XmlReadOptions* readOptions) +void readFromXmlFile(DocumentPtr doc, const FilePath& filename, const FileSearchPath& searchPath, const XmlReadOptions* readOptions) { xml_document xmlDoc; xmlDocumentFromFile(xmlDoc, filename, searchPath); @@ -322,9 +317,9 @@ void writeToXmlStream(DocumentPtr doc, std::ostream& stream, const XmlWriteOptio xmlDoc.save(stream, " "); } -void writeToXmlFile(DocumentPtr doc, const string& filename, const XmlWriteOptions* writeOptions) +void writeToXmlFile(DocumentPtr doc, const FilePath& filename, const XmlWriteOptions* writeOptions) { - std::ofstream ofs(filename); + std::ofstream ofs(filename.asString()); writeToXmlStream(doc, ofs, writeOptions); } @@ -335,10 +330,10 @@ string writeToXmlString(DocumentPtr doc, const XmlWriteOptions* writeOptions) return stream.str(); } -void prependXInclude(DocumentPtr doc, const string& filename) +void prependXInclude(DocumentPtr doc, const FilePath& filename) { ElementPtr elem = doc->addChildOfCategory("xinclude"); - elem->setSourceUri(filename); + elem->setSourceUri(filename.asString()); doc->setChildIndex(elem->getName(), 0); } diff --git a/source/MaterialXFormat/XmlIo.h b/source/MaterialXFormat/XmlIo.h index 39d4c540fa..39c2b8e260 100644 --- a/source/MaterialXFormat/XmlIo.h +++ b/source/MaterialXFormat/XmlIo.h @@ -13,6 +13,8 @@ #include +#include + namespace MaterialX { @@ -22,7 +24,7 @@ extern const string MTLX_EXTENSION; /// A standard function that reads from an XML file into a Document, with /// optional search path and read options. -using XmlReadFunction = std::function; +using XmlReadFunction = std::function; /// @class XmlReadOptions /// A set of options for controlling the behavior of XML read functions. @@ -52,7 +54,7 @@ class XmlWriteOptions /// If true, elements with source file markings will be written as /// XIncludes rather than explicit data. Defaults to true. bool writeXIncludeEnable; - + /// If provided, this function will be used to exclude specific elements /// (those returning false) from the write operation. Defaults to nullptr. ElementPredicate elementPredicate; @@ -97,18 +99,20 @@ void readFromXmlStream(DocumentPtr doc, std::istream& stream, const XmlReadOptio /// Read a Document as XML from the given filename. /// @param doc The Document into which data is read. -/// @param filename The filename from which data is read. -/// @param searchPath A semicolon-separated sequence of file paths, which will -/// be applied in order when searching for the given file and its includes. -/// Defaults to the empty string. +/// @param filename The filename from which data is read. This argument can +/// be supplied either as a FilePath or a standard string. +/// @param searchPath An optional sequence of file paths that will be applied +/// in order when searching for the given file and its includes. This +/// argument can be supplied either as a FileSearchPath, or as a standard +/// string with paths separated by the PATH_SEPARATOR character. /// @param readOptions An optional pointer to an XmlReadOptions object. -/// If provided, then the given options will affect the behavior of the -/// read function. Defaults to a null pointer. +/// If provided, then the given options will affect the behavior of the read +/// function. Defaults to a null pointer. /// @throws ExceptionParseError if the document cannot be parsed. /// @throws ExceptionFileMissing if the file cannot be opened. void readFromXmlFile(DocumentPtr doc, - const string& filename, - const string& searchPath = EMPTY_STRING, + const FilePath& filename, + const FileSearchPath& searchPath = FileSearchPath(), const XmlReadOptions* readOptions = nullptr); /// Read a Document as XML from the given string. @@ -134,11 +138,12 @@ void writeToXmlStream(DocumentPtr doc, std::ostream& stream, const XmlWriteOptio /// Write a Document as XML to the given filename. /// @param doc The Document to be written. -/// @param filename The filename to which data is written +/// @param filename The filename to which data is written. This argument can +/// be supplied either as a FilePath or a standard string. /// @param writeOptions An optional pointer to an XmlWriteOptions object. /// If provided, then the given options will affect the behavior of the /// write function. Defaults to a null pointer. -void writeToXmlFile(DocumentPtr doc, const string& filename, const XmlWriteOptions* writeOptions = nullptr); +void writeToXmlFile(DocumentPtr doc, const FilePath& filename, const XmlWriteOptions* writeOptions = nullptr); /// Write a Document as XML to a new string, returned by value. /// @param doc The Document to be written. @@ -156,7 +161,7 @@ string writeToXmlString(DocumentPtr doc, const XmlWriteOptions* writeOptions = n /// element to hold the reference filename. /// @param doc The Document to be modified. /// @param filename The filename of the XInclude reference to be added. -void prependXInclude(DocumentPtr doc, const string& filename); +void prependXInclude(DocumentPtr doc, const FilePath& filename); /// @} diff --git a/source/MaterialXGenGlsl/GlslShaderGenerator.cpp b/source/MaterialXGenGlsl/GlslShaderGenerator.cpp index aa9b40b12d..6f6002a298 100644 --- a/source/MaterialXGenGlsl/GlslShaderGenerator.cpp +++ b/source/MaterialXGenGlsl/GlslShaderGenerator.cpp @@ -709,7 +709,7 @@ bool GlslShaderGenerator::remapEnumeration(const ValueElement& input, const stri result.second = nullptr; // Try remapping to an enum value. - if (value.size()) + if (!value.empty()) { StringVec valueElemEnumsVec = splitString(enumNames, ","); auto pos = std::find(valueElemEnumsVec.begin(), valueElemEnumsVec.end(), value); diff --git a/source/MaterialXGenGlsl/Nodes/HeightToNormalNodeGlsl.cpp b/source/MaterialXGenGlsl/Nodes/HeightToNormalNodeGlsl.cpp index f209d3ccb1..1d92eb4d52 100644 --- a/source/MaterialXGenGlsl/Nodes/HeightToNormalNodeGlsl.cpp +++ b/source/MaterialXGenGlsl/Nodes/HeightToNormalNodeGlsl.cpp @@ -27,8 +27,7 @@ namespace const float filterOffset = 0.0; } -HeightToNormalNodeGlsl::HeightToNormalNodeGlsl() : - ConvolutionNode() +HeightToNormalNodeGlsl::HeightToNormalNodeGlsl() { } diff --git a/source/MaterialXGenGlsl/Nodes/LightNodeGlsl.cpp b/source/MaterialXGenGlsl/Nodes/LightNodeGlsl.cpp index 5af13007b5..365ed38b4b 100644 --- a/source/MaterialXGenGlsl/Nodes/LightNodeGlsl.cpp +++ b/source/MaterialXGenGlsl/Nodes/LightNodeGlsl.cpp @@ -12,7 +12,7 @@ namespace MaterialX namespace { - static const string LIGHT_DIRECTION_CALCULATION = + const string LIGHT_DIRECTION_CALCULATION = "vec3 L = light.position - position;\n" "float distance = length(L);\n" "L /= distance;\n" diff --git a/source/MaterialXGenShader/DefaultColorManagementSystem.cpp b/source/MaterialXGenShader/DefaultColorManagementSystem.cpp index 5f57080439..f13d65c110 100644 --- a/source/MaterialXGenShader/DefaultColorManagementSystem.cpp +++ b/source/MaterialXGenShader/DefaultColorManagementSystem.cpp @@ -28,7 +28,6 @@ DefaultColorManagementSystemPtr DefaultColorManagementSystem::create(const strin } DefaultColorManagementSystem::DefaultColorManagementSystem(const string& language) - : ColorManagementSystem() { _language = createValidName(language); } diff --git a/source/MaterialXGenShader/Nodes/SourceCodeNode.h b/source/MaterialXGenShader/Nodes/SourceCodeNode.h index e12638f926..a33be37f36 100644 --- a/source/MaterialXGenShader/Nodes/SourceCodeNode.h +++ b/source/MaterialXGenShader/Nodes/SourceCodeNode.h @@ -19,10 +19,8 @@ class SourceCodeNode : public ShaderNodeImpl public: static ShaderNodeImplPtr create(); - void initialize(const InterfaceElement& implementation, GenContext& context) override; - + void initialize(const InterfaceElement& element, GenContext& context) override; void emitFunctionDefinition(const ShaderNode& node, GenContext& context, ShaderStage& stage) const override; - void emitFunctionCall(const ShaderNode& node, GenContext& context, ShaderStage& stage) const override; protected: diff --git a/source/MaterialXGenShader/Shader.h b/source/MaterialXGenShader/Shader.h index d65727f1a1..586e391402 100644 --- a/source/MaterialXGenShader/Shader.h +++ b/source/MaterialXGenShader/Shader.h @@ -20,8 +20,6 @@ namespace MaterialX class ShaderGenerator; class Shader; -// Shared pointer to a Shader -using ShaderPtr = shared_ptr; /// @class Shader /// Class containing all data needed during shader generation. diff --git a/source/MaterialXGenShader/ShaderNode.cpp b/source/MaterialXGenShader/ShaderNode.cpp index e767c8b1fe..522e4cd094 100644 --- a/source/MaterialXGenShader/ShaderNode.cpp +++ b/source/MaterialXGenShader/ShaderNode.cpp @@ -146,7 +146,7 @@ bool ShaderNode::referencedConditionally() const return false; } -void ShaderNode::ScopeInfo::adjustAtConditionalInput(ShaderNode* condNode, int branch, const uint32_t fullMask) +void ShaderNode::ScopeInfo::adjustAtConditionalInput(ShaderNode* condNode, int branch, uint32_t fullMask) { if (type == ScopeInfo::GLOBAL || (type == ScopeInfo::SINGLE && conditionBitmask == fullConditionMask)) { diff --git a/source/MaterialXGenShader/ShaderNode.h b/source/MaterialXGenShader/ShaderNode.h index 735cbe79b5..a4a41d14e6 100644 --- a/source/MaterialXGenShader/ShaderNode.h +++ b/source/MaterialXGenShader/ShaderNode.h @@ -242,7 +242,7 @@ class ShaderNode ScopeInfo() : type(UNKNOWN), conditionalNode(nullptr), conditionBitmask(0), fullConditionMask(0) {} void merge(const ScopeInfo& fromScope); - void adjustAtConditionalInput(ShaderNode* condNode, int branch, const uint32_t condMask); + void adjustAtConditionalInput(ShaderNode* condNode, int branch, uint32_t fullMask); bool usedByBranch(int branchIndex) const { return (conditionBitmask & (1 << branchIndex)) != 0; } Type type; diff --git a/source/MaterialXGenShader/TypeDesc.cpp b/source/MaterialXGenShader/TypeDesc.cpp index 22d8ac8c34..b97f8127a6 100644 --- a/source/MaterialXGenShader/TypeDesc.cpp +++ b/source/MaterialXGenShader/TypeDesc.cpp @@ -11,7 +11,7 @@ namespace MaterialX namespace { - using TypeDescPtr = std::shared_ptr; + using TypeDescPtr = std::unique_ptr; using TypeDescMap = std::unordered_map; // Internal storage of the type descriptor pointers @@ -47,10 +47,11 @@ const TypeDesc* TypeDesc::registerType(const string& name, unsigned char basetyp throw ExceptionShaderGenError("A type with name '" + name + "' is already registered"); } - TypeDescPtr ptr = TypeDescPtr(new TypeDesc(name, basetype, semantic, size, editable, channelMapping)); - map[name] = ptr; + std::unique_ptr uniquePtr(new TypeDesc(name, basetype, semantic, size, editable, channelMapping)); + TypeDesc* rawPtr = uniquePtr.get(); + map[name] = std::move(uniquePtr); - return ptr.get(); + return rawPtr; } int TypeDesc::getChannelIndex(char channel) const diff --git a/source/MaterialXGenShader/Util.cpp b/source/MaterialXGenShader/Util.cpp index 28eeb1e4bb..975ac8b9be 100644 --- a/source/MaterialXGenShader/Util.cpp +++ b/source/MaterialXGenShader/Util.cpp @@ -45,8 +45,9 @@ bool readFile(const string& filename, string& contents) return false; } -void loadDocuments(const FilePath& rootPath, const FileSearchPath& searchPath, const StringSet& skipFiles, const StringSet& includeFiles, - vector& documents, StringVec& documentsPaths, StringVec& errors) +void loadDocuments(const FilePath& rootPath, const FileSearchPath& searchPath, const StringSet& skipFiles, + const StringSet& includeFiles, vector& documents, StringVec& documentsPaths, + StringVec& errors) { for (const FilePath& dir : rootPath.getSubDirectories()) { @@ -59,9 +60,9 @@ void loadDocuments(const FilePath& rootPath, const FileSearchPath& searchPath, c const FilePath filePath = dir / file; try { - FileSearchPath readSearchPath(searchPath.asString()); + FileSearchPath readSearchPath(searchPath); readSearchPath.append(dir); - readFromXmlFile(doc, filePath, readSearchPath.asString()); + readFromXmlFile(doc, filePath, readSearchPath); documents.push_back(doc); documentsPaths.push_back(filePath.asString()); } @@ -79,7 +80,7 @@ void loadLibrary(const FilePath& file, DocumentPtr doc) DocumentPtr libDoc = createDocument(); XmlReadOptions readOptions; readOptions.skipConflictingElements = true; - readFromXmlFile(libDoc, file, EMPTY_STRING, &readOptions); + readFromXmlFile(libDoc, file, FileSearchPath(), &readOptions); CopyOptions copyOptions; copyOptions.skipConflictingElements = true; doc->importLibrary(libDoc, ©Options); @@ -188,7 +189,7 @@ namespace { opaque = true; } - else if (opacity->getNodeName() == EMPTY_STRING && opacity->getInterfaceName() == EMPTY_STRING) + else if (opacity->getNodeName().empty() && opacity->getInterfaceName().empty()) { ValuePtr value = opacity->getValue(); if (!value || (value->isA() && isOne(value->asA()))) @@ -261,7 +262,7 @@ namespace { transmissionInterfaceNames.insert(tranmsInterfaceName); } - if (transmission->getNodeName() == EMPTY_STRING) + if (transmission->getNodeName().empty()) { // Unconnected, check the value ValuePtr value = transmission->getValue(); @@ -289,7 +290,7 @@ namespace { opacityInterfaceNames.insert(opacityInterfaceName); } - if (opacity->getNodeName() == EMPTY_STRING) + if (opacity->getNodeName().empty()) { // Unconnected, check the value ValuePtr value = opacity->getValue(); @@ -427,7 +428,7 @@ bool isTransparentSurface(ElementPtr element, const ShaderGenerator& shadergen) NodeGraphPtr graph = impl->asA(); vector outputs = graph->getActiveOutputs(); - if (outputs.size() > 0) + if (!outputs.empty()) { const OutputPtr& output = outputs[0]; if (TypeDesc::get(output->getType()) == Type::SURFACESHADER) diff --git a/source/MaterialXGenShader/Util.h b/source/MaterialXGenShader/Util.h index 35eee639b6..0529144ce2 100644 --- a/source/MaterialXGenShader/Util.h +++ b/source/MaterialXGenShader/Util.h @@ -29,11 +29,9 @@ string removeExtension(const string& filename); bool readFile(const string& filename, string& content); /// Scans for all documents under a root path and returns documents which can be loaded -void loadDocuments(const FilePath& rootPath, - const FileSearchPath& searchPath, - const StringSet& skipFiles, const StringSet& includeFiles, - vector& documents, StringVec& documentsPaths, - StringVec& errorLog); +void loadDocuments(const FilePath& rootPath, const FileSearchPath& searchPath, const StringSet& skipFiles, + const StringSet& includeFiles, vector& documents, StringVec& documentsPaths, + StringVec& errors); /// Load a given MaterialX library into a document void loadLibrary(const FilePath& file, DocumentPtr doc); diff --git a/source/MaterialXRender/ExceptionShaderValidationError.h b/source/MaterialXRender/ExceptionShaderValidationError.h deleted file mode 100644 index 4c23986c29..0000000000 --- a/source/MaterialXRender/ExceptionShaderValidationError.h +++ /dev/null @@ -1,58 +0,0 @@ -// -// TM & (c) 2017 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd. -// All rights reserved. See LICENSE.txt for license. -// - -#ifndef MATERIALX__EXCEPTIONSHADERVALIDATIONERROR_H -#define MATERIALX__EXCEPTIONSHADERVALIDATIONERROR_H - -#include - -namespace MaterialX -{ - -/// Error string list type -using ShaderValidationErrorList = StringVec; - -/// @class @ExceptionShaderValidationError -/// An exception that is thrown when shader validation fails. -/// An error log of shader errors is cached as part of the exception. -/// For example, if shader compilation fails, then a list of compilation errors is cached. -class ExceptionShaderValidationError : public Exception -{ - public: - ExceptionShaderValidationError(const string& msg, const ShaderValidationErrorList& errorList) : - Exception(msg), - _errorLog(errorList) - { - } - - ExceptionShaderValidationError(const ExceptionShaderValidationError& e) : - Exception(e) - { - _errorLog = e._errorLog; - } - - ExceptionShaderValidationError& operator=(const ExceptionShaderValidationError& e) - { - Exception::operator=(e); - _errorLog = e._errorLog; - return *this; - } - - virtual ~ExceptionShaderValidationError() noexcept - { - } - - const ShaderValidationErrorList& errorLog() const - { - return _errorLog; - } - - private: - ShaderValidationErrorList _errorLog; -}; - -} // namespace MaterialX - -#endif diff --git a/source/MaterialXRender/GeometryHandler.cpp b/source/MaterialXRender/GeometryHandler.cpp index ec90b08bbe..575d537ee1 100644 --- a/source/MaterialXRender/GeometryHandler.cpp +++ b/source/MaterialXRender/GeometryHandler.cpp @@ -3,9 +3,10 @@ // All rights reserved. See LICENSE.txt for license. // -#include #include +#include + namespace MaterialX { void GeometryHandler::addLoader(GeometryLoaderPtr loader) @@ -13,7 +14,7 @@ void GeometryHandler::addLoader(GeometryLoaderPtr loader) const StringSet& extensions = loader->supportedExtensions(); for (const auto& extension : extensions) { - _geometryLoaders.insert(std::pair(extension, loader)); + _geometryLoaders.insert(std::pair(extension, loader)); } } diff --git a/source/MaterialXRender/GeometryHandler.h b/source/MaterialXRender/GeometryHandler.h index 8387103528..d9791c3cb0 100644 --- a/source/MaterialXRender/GeometryHandler.h +++ b/source/MaterialXRender/GeometryHandler.h @@ -9,9 +9,10 @@ /// @file /// Geometry loader interfaces -#include #include -#include + +#include + #include namespace MaterialX @@ -26,11 +27,10 @@ using GeometryLoaderPtr = std::shared_ptr; class GeometryLoader { public: - /// Default constructor - GeometryLoader() {} - - /// Default destructor - virtual ~GeometryLoader() {} + GeometryLoader() + { + } + virtual ~GeometryLoader() { } /// Returns a list of supported extensions /// @return List of support extensions @@ -46,7 +46,7 @@ class GeometryLoader virtual bool load(const FilePath& filePath, MeshList& meshList) = 0; protected: - /// List of supported string extensions + // List of supported string extensions StringSet _extensions; }; @@ -62,13 +62,12 @@ using GeometryLoaderMap = std::multimap; class GeometryHandler { public: - /// Default constructor - GeometryHandler() {}; - - /// Default destructor - virtual ~GeometryHandler() {}; + GeometryHandler() + { + } + virtual ~GeometryHandler() { } - /// Static instance create function + /// Create a new geometry handler static GeometryHandlerPtr create() { return std::make_shared(); @@ -112,9 +111,10 @@ class GeometryHandler } protected: - /// Recompute bounds for all stored geometry + // Recompute bounds for all stored geometry void computeBounds(); + protected: GeometryLoaderMap _geometryLoaders; MeshList _meshes; Vector3 _minimumBounds; @@ -122,4 +122,5 @@ class GeometryHandler }; } // namespace MaterialX + #endif diff --git a/source/MaterialXRender/ImageHandler.cpp b/source/MaterialXRender/ImageHandler.cpp index 44f599e34c..3a3a1b4ac2 100644 --- a/source/MaterialXRender/ImageHandler.cpp +++ b/source/MaterialXRender/ImageHandler.cpp @@ -3,14 +3,16 @@ // All rights reserved. See LICENSE.txt for license. // -#include -#include -#include #include + +#include +#include + #include namespace MaterialX { + string ImageDesc::BASETYPE_UINT8 = "UINT8"; string ImageDesc::BASETYPE_HALF = "HALF"; string ImageDesc::BASETYPE_FLOAT = "FLOAT"; @@ -212,38 +214,38 @@ void ImageHandler::clearImageCache() void ImageSamplingProperties::setProperties(const string& fileNameUniform, const VariableBlock& uniformBlock) { - const std::string IMAGE_SEPARATOR("_"); - const std::string UADDRESS_MODE_POST_FIX("_uaddressmode"); - const std::string VADDRESS_MODE_POST_FIX("_vaddressmode"); - const std::string FILTER_TYPE_POST_FIX("_filtertype"); - const std::string DEFAULT_COLOR_POST_FIX("_default"); + const string IMAGE_SEPARATOR("_"); + const string UADDRESS_MODE_POST_FIX("_uaddressmode"); + const string VADDRESS_MODE_POST_FIX("_vaddressmode"); + const string FILTER_TYPE_POST_FIX("_filtertype"); + const string DEFAULT_COLOR_POST_FIX("_default"); const int INVALID_MAPPED_INT_VALUE = -1; // Any value < 0 is not considered to be invalid // Get the additional texture parameters based on image uniform name // excluding the trailing "_file" postfix string - std::string root = fileNameUniform; + string root = fileNameUniform; size_t pos = root.find_last_of(IMAGE_SEPARATOR); - if (pos != std::string::npos) + if (pos != string::npos) { root = root.substr(0, pos); } - const std::string uaddressmodeStr = root + UADDRESS_MODE_POST_FIX; + const string uaddressmodeStr = root + UADDRESS_MODE_POST_FIX; const ShaderPort* port = uniformBlock.find(uaddressmodeStr); ValuePtr intValue = port ? port->getValue() : nullptr; uaddressMode = ImageSamplingProperties::AddressMode(intValue && intValue->isA() ? intValue->asA() : INVALID_MAPPED_INT_VALUE); - const std::string vaddressmodeStr = root + VADDRESS_MODE_POST_FIX; + const string vaddressmodeStr = root + VADDRESS_MODE_POST_FIX; port = uniformBlock.find(vaddressmodeStr); intValue = port ? port->getValue() : nullptr; vaddressMode = ImageSamplingProperties::AddressMode(intValue && intValue->isA() ? intValue->asA() : INVALID_MAPPED_INT_VALUE); - const std::string filtertypeStr = root + FILTER_TYPE_POST_FIX; + const string filtertypeStr = root + FILTER_TYPE_POST_FIX; port = uniformBlock.find(filtertypeStr); intValue = port ? port->getValue() : nullptr; filterType = ImageSamplingProperties::FilterType(intValue && intValue->isA() ? intValue->asA() : INVALID_MAPPED_INT_VALUE); - const std::string defaultColorStr = root + DEFAULT_COLOR_POST_FIX; + const string defaultColorStr = root + DEFAULT_COLOR_POST_FIX; port = uniformBlock.find(defaultColorStr); ValuePtr colorValue = port ? port->getValue() : nullptr; if (colorValue) diff --git a/source/MaterialXRender/ImageHandler.h b/source/MaterialXRender/ImageHandler.h index 3210515918..16888699f2 100644 --- a/source/MaterialXRender/ImageHandler.h +++ b/source/MaterialXRender/ImageHandler.h @@ -9,16 +9,16 @@ /// @file /// Image handler interfaces +#include + #include #include #include -#include - -#include namespace MaterialX { + class VariableBlock; /// A function to perform image buffer deallocation @@ -50,22 +50,6 @@ class ImageDesc /// Preset image type identifiers static ImageType IMAGETYPE_2D; - /// Image width - unsigned int width = 0; - /// Image height - unsigned int height = 0; - /// Number of channels - unsigned int channelCount = 0; - /// Number of mip map levels - unsigned int mipCount = 0; - /// CPU buffer. May be empty - void* resourceBuffer = nullptr; - /// Base type - BaseType baseType = BASETYPE_UINT8; - /// Image Type - ImageType imageType = IMAGETYPE_2D; - /// Hardware target dependent resource identifier. May be undefined. - unsigned int resourceId = 0; /// Deallocator to free resource buffer memory. If not defined then malloc() is /// assumed to have been used to allocate the buffer and corresponding free() is /// used to deallocate. @@ -77,11 +61,26 @@ class ImageDesc /// Compute the number of mip map levels based on size of the image void computeMipCount() { - mipCount = (unsigned int)std::log2(std::max(width, height)) + 1; + mipCount = (unsigned int) std::log2(std::max(width, height)) + 1; } /// Free any resource buffer memory void freeResourceBuffer(); + + public: + unsigned int width = 0; + unsigned int height = 0; + unsigned int channelCount = 0; + unsigned int mipCount = 0; + + BaseType baseType = BASETYPE_UINT8; + ImageType imageType = IMAGETYPE_2D; + + // CPU buffer. May be empty. + void* resourceBuffer = nullptr; + + // Hardware target dependent resource identifier. May be undefined. + unsigned int resourceId = 0; }; /// Structure containing harware image description restrictions @@ -104,10 +103,8 @@ class ImageSamplingProperties void setProperties(const string& fileNameUniform, const VariableBlock& uniformBlock); - /// Address mode options. Matches enumerations - /// allowed for address modes, except - /// UNSPECIFIED which indicates no explicit mode was - /// defined. + /// Address mode options. Matches enumerations allowed for image address + /// modes, except UNSPECIFIED which indicates no explicit mode was defined. enum class AddressMode : int { UNSPECIFIED = -1, @@ -122,10 +119,8 @@ class ImageSamplingProperties /// Address mode in V AddressMode vaddressMode = AddressMode::UNSPECIFIED; - /// Filter type options. Matches enumerations - /// allowed for filter types, except - /// UNSPECIFIED which indicates no explicit type was - /// defined. + /// Filter type options. Matches enumerations allowed for image filter + /// types, except UNSPECIFIED which indicates no explicit type was defined. enum class FilterType : int { UNSPECIFIED = -1, @@ -137,8 +132,8 @@ class ImageSamplingProperties /// Filter type FilterType filterType = FilterType::UNSPECIFIED; - /// Default color. Corresponds to the "default" - /// value on the node definition. + /// Default color. Corresponds to the "default" value on the image + /// node definition. Color4 defaultColor = { 0.0f, 0.0f, 0.0f, 1.0f }; }; @@ -154,11 +149,10 @@ using ImageLoaderPtr = std::shared_ptr; class ImageLoader { public: - /// Default constructor - ImageLoader() {} - - /// Default destructor - virtual ~ImageLoader() {} + ImageLoader() + { + } + virtual ~ImageLoader() { } /// Stock extension names static string BMP_EXTENSION; @@ -212,7 +206,7 @@ using ImageHandlerPtr = std::shared_ptr; /// Map of extensions to image loaders using ImageLoaderMap = std::multimap; -/// @class @ImageHandler +/// @class ImageHandler /// A image handler class. Keeps track of images which are loaded /// from disk via supplied ImageLoader. Derive classes are responsible /// for determinine how to perform the logic for "binding" of these resources @@ -222,7 +216,7 @@ class ImageHandler { public: /// Constructor. Assume at least one loader must be supplied. - ImageHandler(ImageLoaderPtr imageLoader); + explicit ImageHandler(ImageLoaderPtr imageLoader); /// Static instance create function static ImageHandlerPtr create(ImageLoaderPtr imageLoader) @@ -347,14 +341,12 @@ class ImageHandler /// this to add restrictions specific to that handler. virtual const ImageDescRestrictions* getRestrictions() const { return nullptr; } - /// Image loader utilities + protected: ImageLoaderMap _imageLoaders; - /// Image description cache ImageDescCache _imageCache; - - /// Filename search path FileSearchPath _searchPath; }; } // namespace MaterialX + #endif diff --git a/source/MaterialXRender/LightHandler.cpp b/source/MaterialXRender/LightHandler.cpp index 83a0b3069d..be55bde98a 100644 --- a/source/MaterialXRender/LightHandler.cpp +++ b/source/MaterialXRender/LightHandler.cpp @@ -23,8 +23,8 @@ void LightHandler::addLightSource(NodePtr node) _lightSources.push_back(node); } -void LightHandler::mapNodeDefToIdentiers(const std::vector& nodes, - std::unordered_map& ids) +void LightHandler::mapNodeDefToIdentiers(const vector& nodes, + std::unordered_map& ids) { unsigned int id = 1; for (const auto& node : nodes) @@ -41,7 +41,7 @@ void LightHandler::mapNodeDefToIdentiers(const std::vector& nodes, } } -void LightHandler::findLights(DocumentPtr doc, std::vector& lights) +void LightHandler::findLights(DocumentPtr doc, vector& lights) { lights.clear(); for (NodePtr node : doc->getNodes()) @@ -54,7 +54,7 @@ void LightHandler::findLights(DocumentPtr doc, std::vector& lights) } } -void LightHandler::registerLights(DocumentPtr doc, const std::vector& lights, GenContext& context) +void LightHandler::registerLights(DocumentPtr doc, const vector& lights, GenContext& context) { // Clear context light user data which is set when bindLightShader() // is called. This is necessary in case the light types have already been diff --git a/source/MaterialXRender/LightHandler.h b/source/MaterialXRender/LightHandler.h index a51e37c56f..34901fc208 100644 --- a/source/MaterialXRender/LightHandler.h +++ b/source/MaterialXRender/LightHandler.h @@ -9,11 +9,7 @@ /// @file /// Handler for hardware lights -#include -#include - -#include -#include +#include namespace MaterialX { @@ -29,15 +25,12 @@ using LightHandlerPtr = std::shared_ptr; class LightHandler { public: - /// Static instance create function - static LightHandlerPtr create() { return std::make_shared(); } - - /// Default constructor LightHandler(); - - /// Default destructor virtual ~LightHandler(); + /// Create a new light handler + static LightHandlerPtr create() { return std::make_shared(); } + /// Adds a light source node void addLightSource(NodePtr node); @@ -85,19 +78,19 @@ class LightHandler /// From a set of nodes, create a mapping of corresponding /// nodedef identifiers to numbers - void mapNodeDefToIdentiers(const std::vector& nodes, + void mapNodeDefToIdentiers(const vector& nodes, std::unordered_map& ids); /// Find lights to use based on an input document /// @param doc Document to scan for lights /// @param lights List of lights found in document - void findLights(DocumentPtr doc, std::vector& lights); + void findLights(DocumentPtr doc, vector& lights); /// Register light node definitions and light count with a given generation context /// @param doc Document containing light nodes and definitions /// @param lights Lights to register /// @param context Context to update - void registerLights(DocumentPtr doc, const std::vector& lights, GenContext& context); + void registerLights(DocumentPtr doc, const vector& lights, GenContext& context); private: vector _lightSources; diff --git a/source/MaterialXRender/Mesh.cpp b/source/MaterialXRender/Mesh.cpp index ce62ef8206..9962f1215f 100644 --- a/source/MaterialXRender/Mesh.cpp +++ b/source/MaterialXRender/Mesh.cpp @@ -9,6 +9,7 @@ namespace MaterialX { + const string MeshStream::POSITION_ATTRIBUTE("position"); const string MeshStream::NORMAL_ATTRIBUTE("normal"); const string MeshStream::TEXCOORD_ATTRIBUTE("texcoord"); @@ -210,37 +211,37 @@ void MeshStream::transform(const Matrix44 &matrix) { unsigned int stride = getStride(); size_t numElements = _data.size() / getStride(); - if(getType() == MeshStream::POSITION_ATTRIBUTE || - getType() == MeshStream::TEXCOORD_ATTRIBUTE || - getType() == MeshStream::GEOMETRY_PROPERTY_ATTRIBUTE) + if (getType() == MeshStream::POSITION_ATTRIBUTE || + getType() == MeshStream::TEXCOORD_ATTRIBUTE || + getType() == MeshStream::GEOMETRY_PROPERTY_ATTRIBUTE) { for (size_t i=0; i; /// Float geometry buffer using MeshFloatBuffer = vector; -/// Shader pointer to a mesh stream +/// Shared pointer to a mesh stream using MeshStreamPtr = shared_ptr; /// List of mesh streams @@ -30,45 +30,38 @@ using MeshStreamList = vector; class MeshStream { public: - /// Position attribute static const string POSITION_ATTRIBUTE; - /// Normal attribute static const string NORMAL_ATTRIBUTE; - /// Texture coordinate attribute static const string TEXCOORD_ATTRIBUTE; - /// Tangent attribute static const string TANGENT_ATTRIBUTE; - /// Bitangent attribute static const string BITANGENT_ATTRIBUTE; - /// Color attribute static const string COLOR_ATTRIBUTE; - /// Generic geometry property attribute static const string GEOMETRY_PROPERTY_ATTRIBUTE; - /// Create instance of a mesh stream - static MeshStreamPtr create(const string& name, const string& type, unsigned int index=0) - { - return std::make_shared(name, type, index); - } - - /// Default element string is 3. static const unsigned int STRIDE_3D = 3; static const unsigned int STRIDE_2D = 2; static const unsigned int DEFAULT_STRIDE = STRIDE_3D; - /// Constructor + public: MeshStream(const string& name, const string& type, unsigned int index) : _name(name), _type(type), _index(index), - _stride(DEFAULT_STRIDE) {} + _stride(DEFAULT_STRIDE) + { + } + ~MeshStream() { } - ~MeshStream() {} + /// Create a new mesh stream + static MeshStreamPtr create(const string& name, const string& type, unsigned int index = 0) + { + return std::make_shared(name, type, index); + } /// Resize data to an given number of elements void resize(unsigned int elementCount) { - _data.resize(elementCount * _stride); + _data.resize((size_t) elementCount * (size_t) _stride); } /// Get stream name @@ -128,7 +121,7 @@ class MeshStream unsigned int _stride; }; -/// Shader pointer to a mesh stream +/// Shared pointer to a mesh partition using MeshPartitionPtr = shared_ptr; /// @class MeshPartition @@ -137,24 +130,22 @@ using MeshPartitionPtr = shared_ptr; class MeshPartition { public: - static MeshPartitionPtr create() - { - return std::make_shared(); - } - - /// Default constructor MeshPartition() : _faceCount(0) { } - - /// Default destructor ~MeshPartition() { } - /// Resize data to an given number of indices - void resize(unsigned int elementCount) + /// Create a new mesh partition + static MeshPartitionPtr create() + { + return std::make_shared(); + } + + /// Resize data to the given number of indices + void resize(unsigned int indexCount) { - _indices.resize(elementCount); + _indices.resize(indexCount); } /// Get geometry identifier @@ -199,37 +190,36 @@ class MeshPartition size_t _faceCount; }; - -/// Shader pointer to a GeometryMesh +/// Shared pointer to a mesh using MeshPtr = shared_ptr; /// List of meshes using MeshList = vector; -/// Map of names to mesh +/// Map from names to meshes using MeshMap = std::unordered_map; /// @class Mesh /// Container for mesh data -/// class Mesh { public: + Mesh(const string& identifier); + ~Mesh() { } + + /// Create a new mesh static MeshPtr create(const string& identifier) { return std::make_shared(identifier); } - Mesh(const string& identifier); - ~Mesh() { } - /// Get mesh identifier const string& getIdentifier() const { return _identifier; } - /// Set the mesh 's source URI. + /// Set the mesh's source URI. void setSourceUri(const string& sourceUri) { _sourceUri = sourceUri; @@ -241,7 +231,7 @@ class Mesh return !_sourceUri.empty(); } - /// Return the mesh 's source URI. + /// Return the mesh's source URI. const string& getSourceUri() const { return _sourceUri; diff --git a/source/MaterialXRender/OiioImageLoader.cpp b/source/MaterialXRender/OiioImageLoader.cpp index b79c383c8e..b0d169e4a8 100644 --- a/source/MaterialXRender/OiioImageLoader.cpp +++ b/source/MaterialXRender/OiioImageLoader.cpp @@ -21,7 +21,6 @@ #include - #if defined(_WIN32) #pragma warning( pop ) #elif defined(__clang__) diff --git a/source/MaterialXRender/OiioImageLoader.h b/source/MaterialXRender/OiioImageLoader.h index 961e1faac6..839db86c72 100644 --- a/source/MaterialXRender/OiioImageLoader.h +++ b/source/MaterialXRender/OiioImageLoader.h @@ -13,21 +13,18 @@ namespace MaterialX { + /// Shared pointer to an OiioImageLoader using OiioImageLoaderPtr = std::shared_ptr; /// @class OiioImageLoader -/// Disk image loader wrapper using OpenImageIO library -/// +/// Image file loader using OpenImageIO library class OiioImageLoader : public ImageLoader { public: - /// Static instance create function - static OiioImageLoaderPtr create() { return std::make_shared(); } - - /// Default constructor. Set all extensions supported by stb OiioImageLoader() { + // Set all extensions supported by OpenImageIO _extensions.insert(BMP_EXTENSION); _extensions.insert(GIF_EXTENSION); _extensions.insert(HDR_EXTENSION); @@ -44,9 +41,10 @@ class OiioImageLoader : public ImageLoader _extensions.insert(TXT_EXTENSION); _extensions.insert(TXR_EXTENSION); } + virtual ~OiioImageLoader() { } - /// Default destructor - virtual ~OiioImageLoader() {} + /// Create a new OpenImageIO image loader + static OiioImageLoaderPtr create() { return std::make_shared(); } /// Save image to disk. This method must be implemented by derived classes. /// @param filePath Path to file to save image to @@ -66,6 +64,6 @@ class OiioImageLoader : public ImageLoader const ImageDescRestrictions* restrictions = nullptr) override; }; -} // namespace MaterialX; +} // namespace MaterialX #endif diff --git a/source/MaterialXRender/ShaderValidator.h b/source/MaterialXRender/ShaderValidator.h index 776ceecb5a..beb40bbd07 100644 --- a/source/MaterialXRender/ShaderValidator.h +++ b/source/MaterialXRender/ShaderValidator.h @@ -9,16 +9,16 @@ /// @file /// Base class for shader validation -#include -#include -#include -#include #include -#include +#include #include +#include + +#include namespace MaterialX { + /// Shared pointer to a shader validator using ShaderValidatorPtr = std::shared_ptr; @@ -32,8 +32,7 @@ class ShaderValidator using StageMap = StringMap; public: - /// Destructor - virtual ~ShaderValidator() {}; + virtual ~ShaderValidator() { } /// @name Setup /// @{ @@ -43,28 +42,28 @@ class ShaderValidator /// Set image handler to use for image load and save /// @param imageHandler Handler used to save image - void setImageHandler(const ImageHandlerPtr imageHandler) + void setImageHandler(ImageHandlerPtr imageHandler) { _imageHandler = imageHandler; } /// Get image handler /// @return Shared pointer to an image handler - const ImageHandlerPtr getImageHandler() const + ImageHandlerPtr getImageHandler() const { return _imageHandler; } /// Set light handler to use for light bindings /// @param lightHandler Handler used for lights - void setLightHandler(const LightHandlerPtr lightHandler) + void setLightHandler(LightHandlerPtr lightHandler) { _lightHandler = lightHandler; } /// Get light handler /// @return Shared pointer to a light handler - const LightHandlerPtr getLightHandler() const + LightHandlerPtr getLightHandler() const { return _lightHandler; } @@ -78,19 +77,18 @@ class ShaderValidator /// Set viewing utilities handler. /// @param viewHandler Handler to use - void setViewHandler(const ViewHandlerPtr viewHandler) + void setViewHandler(ViewHandlerPtr viewHandler) { _viewHandler = viewHandler; } /// Get viewing utilities handler /// @return Shared pointer to a view utilities handler - const ViewHandlerPtr getViewHandler() const + ViewHandlerPtr getViewHandler() const { return _viewHandler; } - /// @} /// @name Validation /// @{ @@ -122,21 +120,54 @@ class ShaderValidator /// @} protected: - /// Constructor - ShaderValidator() {}; + // Protected constructor + ShaderValidator() { } - /// Utility image handler + protected: ImageHandlerPtr _imageHandler; - - /// Utility geometry handler GeometryHandlerPtr _geometryHandler; - - /// Utility light handler LightHandlerPtr _lightHandler; - - /// Viewing utilities handler ViewHandlerPtr _viewHandler; }; +/// Error string list type +using ShaderValidationErrorList = StringVec; + +/// @class ExceptionShaderValidationError +/// An exception that is thrown when shader validation fails. +/// An error log of shader errors is cached as part of the exception. +/// For example, if shader compilation fails, then a list of compilation errors is cached. +class ExceptionShaderValidationError : public Exception +{ + public: + ExceptionShaderValidationError(const string& msg, const ShaderValidationErrorList& errorList) : + Exception(msg), + _errorLog(errorList) + { + } + + ExceptionShaderValidationError(const ExceptionShaderValidationError& e) : + Exception(e), + _errorLog(e._errorLog) + { + } + + ExceptionShaderValidationError& operator=(const ExceptionShaderValidationError& e) + { + Exception::operator=(e); + _errorLog = e._errorLog; + return *this; + } + + const ShaderValidationErrorList& errorLog() const + { + return _errorLog; + } + + private: + ShaderValidationErrorList _errorLog; +}; + } // namespace MaterialX + #endif diff --git a/source/MaterialXRender/StbImageLoader.cpp b/source/MaterialXRender/StbImageLoader.cpp index 2f2ee66ad8..5b15b227b7 100644 --- a/source/MaterialXRender/StbImageLoader.cpp +++ b/source/MaterialXRender/StbImageLoader.cpp @@ -23,11 +23,11 @@ #pragma warning( pop ) #endif - #include namespace MaterialX { + bool StbImageLoader::saveImage(const FilePath& filePath, const ImageDesc& imageDesc, bool verticalFlip) @@ -52,7 +52,7 @@ bool StbImageLoader::saveImage(const FilePath& filePath, const string filePathName = filePath.asString(); - std::string extension = (filePathName.substr(filePathName.find_last_of(".") + 1)); + string extension = (filePathName.substr(filePathName.find_last_of(".") + 1)); if (!isFloat) { if (extension == PNG_EXTENSION) @@ -104,7 +104,7 @@ bool StbImageLoader::loadImage(const FilePath& filePath, ImageDesc &imageDesc, const string fileName = filePath.asString(); // If HDR, switch to float reader - std::string extension = (fileName.substr(fileName.find_last_of(".") + 1)); + string extension = (fileName.substr(fileName.find_last_of(".") + 1)); if (extension == HDR_EXTENSION) { // Early out if base type is unsupported diff --git a/source/MaterialXRender/StbImageLoader.h b/source/MaterialXRender/StbImageLoader.h index 194c2ad605..4069d059ed 100644 --- a/source/MaterialXRender/StbImageLoader.h +++ b/source/MaterialXRender/StbImageLoader.h @@ -13,21 +13,18 @@ namespace MaterialX { -/// Shared pointer to an stbImageLoader + +/// Shared pointer to an StbImageLoader using StbImageLoaderPtr = std::shared_ptr; /// @class StbImageLoader -/// Disk image loader wrapper using stb library -/// +/// Image file loader using stb library class StbImageLoader : public ImageLoader { public: - /// Static instance create function - static StbImageLoaderPtr create() { return std::make_shared(); } - - /// Default constructor. Set all extensions supported by stb - StbImageLoader() + StbImageLoader() { + // Set all extensions supported by stb image _extensions.insert(BMP_EXTENSION); _extensions.insert(GIF_EXTENSION); _extensions.insert(HDR_EXTENSION); @@ -38,9 +35,10 @@ class StbImageLoader : public ImageLoader _extensions.insert(PSD_EXTENSION); _extensions.insert(TGA_EXTENSION); } + virtual ~StbImageLoader() { } - /// Default destructor - virtual ~StbImageLoader() {} + /// Create a new stb image loader + static StbImageLoaderPtr create() { return std::make_shared(); } /// Save image to disk. This method must be implemented by derived classes. /// @param filePath Path to file to save image to diff --git a/source/MaterialXRender/TinyObjLoader.cpp b/source/MaterialXRender/TinyObjLoader.cpp index ed220f1a00..3ba26efe0d 100644 --- a/source/MaterialXRender/TinyObjLoader.cpp +++ b/source/MaterialXRender/TinyObjLoader.cpp @@ -23,9 +23,9 @@ namespace MaterialX bool TinyObjLoader::load(const FilePath& filePath, MeshList& meshList) { tinyobj::attrib_t attrib; - std::vector shapes; - std::vector materials; - std::string err; + vector shapes; + vector materials; + string err; bool load = tinyobj::LoadObj(&attrib, &shapes, &materials, nullptr, &err, filePath.asString().c_str(), nullptr, true, false); if (!load) diff --git a/source/MaterialXRender/TinyObjLoader.h b/source/MaterialXRender/TinyObjLoader.h index d51550fecf..f84e2adb41 100644 --- a/source/MaterialXRender/TinyObjLoader.h +++ b/source/MaterialXRender/TinyObjLoader.h @@ -9,12 +9,12 @@ /// @file /// OBJ geometry format loader using the TinyObj library -#include #include namespace MaterialX { -/// Shared pointer to an TinyObjLoader + +/// Shared pointer to a TinyObjLoader using TinyObjLoaderPtr = std::shared_ptr; /// @class TinyObjLoader @@ -23,21 +23,19 @@ using TinyObjLoaderPtr = std::shared_ptr; class TinyObjLoader : public GeometryLoader { public: - /// Static instance create function - static TinyObjLoaderPtr create() { return std::make_shared(); } - - /// Default constructor TinyObjLoader() { _extensions = { "obj", "OBJ" }; } - - /// Default destructor - virtual ~TinyObjLoader() {} + virtual ~TinyObjLoader() { } + + /// Create a new TinyObjLoader + static TinyObjLoaderPtr create() { return std::make_shared(); } /// Load geometry from disk bool load(const FilePath& filePath, MeshList& meshList) override; }; } // namespace MaterialX + #endif diff --git a/source/MaterialXRender/Util.cpp b/source/MaterialXRender/Util.cpp index 9b5fcce2a7..c6a527aab8 100644 --- a/source/MaterialXRender/Util.cpp +++ b/source/MaterialXRender/Util.cpp @@ -17,9 +17,9 @@ ShaderPtr createShader(const string& shaderName, GenContext& context, ElementPtr } ShaderPtr createConstantShader(GenContext& context, - DocumentPtr stdLib, - const string& shaderName, - const Color3& color) + DocumentPtr stdLib, + const string& shaderName, + const Color3& color) { // Construct the constant color nodegraph DocumentPtr doc = createDocument(); @@ -56,7 +56,7 @@ unsigned int getUIProperties(ConstValueElementPtr nodeDefElement, UIProperties& if (!enumString.empty()) { uiProperties.enumeration = splitString(enumString, ","); - if (uiProperties.enumeration.size()) + if (!uiProperties.enumeration.empty()) propertyCount++; } @@ -93,7 +93,7 @@ unsigned int getUIProperties(ConstValueElementPtr nodeDefElement, UIProperties& { uiProperties.enumerationValues.push_back(Value::createValue(enumerationValues)); } - if(uiProperties.enumeration.size() != uiProperties.enumerationValues.size()) + if (uiProperties.enumeration.size() != uiProperties.enumerationValues.size()) { throw std::runtime_error("Every enum must have a value!"); } @@ -125,7 +125,7 @@ unsigned int getUIProperties(ConstValueElementPtr nodeDefElement, UIProperties& const string& uiAdvancedString = nodeDefElement->getAttribute(ValueElement::UI_ADVANCED_ATTRIBUTE); uiProperties.uiAdvanced = (uiAdvancedString == "true"); - if(!uiAdvancedString.empty()) + if (!uiAdvancedString.empty()) { propertyCount++; } @@ -154,13 +154,13 @@ void createUIPropertyGroups(ElementPtr uniformElement, DocumentPtr contentDocume item.value = uniformElement->asA()->getValue(); getUIProperties(uniformElement->getNamePath(), contentDocument, EMPTY_STRING, item.ui); - std::string parentLabel; + string parentLabel; ElementPtr parent = uniformElement->getParent(); if (parent && parent != contentDocument && parent != materialElement) { parentLabel = parent->getNamePath(); } - if (!materialElement || parentLabel == materialElement->getAttribute(PortElement::NODE_NAME_ATTRIBUTE)) + if (!materialElement || parentLabel == materialElement->getAttribute(PortElement::NODE_NAME_ATTRIBUTE)) { parentLabel.clear(); } @@ -180,19 +180,19 @@ void createUIPropertyGroups(ElementPtr uniformElement, DocumentPtr contentDocume if (!item.ui.uiFolder.empty()) { - groups.insert(std::pair + groups.insert(std::pair (item.ui.uiFolder, item)); } else { - unnamedGroups.insert(std::pair + unnamedGroups.insert(std::pair (EMPTY_STRING, item)); } } } void createUIPropertyGroups(const VariableBlock& block, DocumentPtr contentDocument, TypedElementPtr materialElement, - const string& pathSeparator, UIPropertyGroup& groups, UIPropertyGroup& unnamedGroups) + const string& pathSeparator, UIPropertyGroup& groups, UIPropertyGroup& unnamedGroups) { for (const auto& uniform : block.getVariableOrder()) { diff --git a/source/MaterialXRender/Util.h b/source/MaterialXRender/Util.h index 4b44c36607..26b5a2c805 100644 --- a/source/MaterialXRender/Util.h +++ b/source/MaterialXRender/Util.h @@ -9,11 +9,12 @@ /// @file /// Rendering utility methods -#include -#include #include +#include #include +#include + #include namespace MaterialX diff --git a/source/MaterialXRender/ViewHandler.cpp b/source/MaterialXRender/ViewHandler.cpp index 97a587aef5..e22ed78da6 100644 --- a/source/MaterialXRender/ViewHandler.cpp +++ b/source/MaterialXRender/ViewHandler.cpp @@ -9,11 +9,11 @@ namespace MaterialX { -float ViewHandler::PI_VALUE = 3.14159265358979323846f; +const float PI = std::acos(-1.0f); float ViewHandler::degreesToRadians(float degrees) const { - return (degrees * PI_VALUE / 180.0f); + return (degrees * PI / 180.0f); } Matrix44 ViewHandler::createViewMatrix(const Vector3& eye, diff --git a/source/MaterialXRender/ViewHandler.h b/source/MaterialXRender/ViewHandler.h index 9afcc40340..3e5f4c6be6 100644 --- a/source/MaterialXRender/ViewHandler.h +++ b/source/MaterialXRender/ViewHandler.h @@ -10,7 +10,6 @@ /// Utility for providing view data #include -#include namespace MaterialX { @@ -21,18 +20,16 @@ using ViewHandlerPtr = std::shared_ptr; /// @class ViewHandler /// Utility view handler for creating and providing /// View data for shader binding. -/// class ViewHandler { public: - /// Static instance create function - static ViewHandlerPtr create() { return std::make_shared(); } + ViewHandler() + { + } + virtual ~ViewHandler() { } - /// Default constructor - ViewHandler() {}; - - /// Default destructor - virtual ~ViewHandler() {}; + /// Create a new view handler + static ViewHandlerPtr create() { return std::make_shared(); } /// Create a view matrix given a eye position, a target position and an up vector static Matrix44 createViewMatrix(const Vector3& eye, @@ -89,21 +86,13 @@ class ViewHandler /// @return value converted to radians float degreesToRadians(float degrees) const; - /// PI - static float PI_VALUE; - /// @} protected: - /// World matrix Matrix44 _worldMatrix; - /// View matrix Matrix44 _viewMatrix; - /// View position Vector3 _viewPosition; - /// View direction Vector3 _viewDirection; - /// Projection matrix Matrix44 _projectionMatrix; }; diff --git a/source/MaterialXRenderGlsl/GLTextureHandler.cpp b/source/MaterialXRenderGlsl/GLTextureHandler.cpp index 70c2b2043a..3a90f1a04e 100644 --- a/source/MaterialXRenderGlsl/GLTextureHandler.cpp +++ b/source/MaterialXRenderGlsl/GLTextureHandler.cpp @@ -3,11 +3,13 @@ // All rights reserved. See LICENSE.txt for license. // -#include #include + #include #include +#include + namespace MaterialX { diff --git a/source/MaterialXRenderGlsl/GLTextureHandler.h b/source/MaterialXRenderGlsl/GLTextureHandler.h index 3b02cff6e2..d95a309bc4 100644 --- a/source/MaterialXRenderGlsl/GLTextureHandler.h +++ b/source/MaterialXRenderGlsl/GLTextureHandler.h @@ -54,7 +54,7 @@ class GLTextureHandler : public ImageHandler /// Bind an image. This method will bind the texture to an active texture /// unit as defined by the corresponding image description. The method /// will fail if there are not enough available image units to bind to. - /// @param identifier Identifier for image description to bind. + /// @param filePath File path of image description to bind. /// @param samplingProperties Sampling properties for the image /// @return true if succeded to bind bool bindImage(const FilePath& filePath, const ImageSamplingProperties& samplingProperties) override; diff --git a/source/MaterialXRenderGlsl/GLUtilityContext.cpp b/source/MaterialXRenderGlsl/GLUtilityContext.cpp index 00618bcdd2..966928a0b7 100644 --- a/source/MaterialXRenderGlsl/GLUtilityContext.cpp +++ b/source/MaterialXRenderGlsl/GLUtilityContext.cpp @@ -56,7 +56,7 @@ GLUtilityContext::GLUtilityContext(const WindowWrapper& /*windowWrapper*/, Hardw if (SetPixelFormat(dummyWindowWrapper.internalHandle(), chosenPixelFormat, &pfd)) { _contextHandle = wglCreateContext(dummyWindowWrapper.internalHandle()); - if (_contextHandle != 0) + if (_contextHandle) { if (sharedWithContext) { diff --git a/source/MaterialXRenderGlsl/GlslProgram.cpp b/source/MaterialXRenderGlsl/GlslProgram.cpp index 08b35db28f..074f795744 100644 --- a/source/MaterialXRenderGlsl/GlslProgram.cpp +++ b/source/MaterialXRenderGlsl/GlslProgram.cpp @@ -6,12 +6,11 @@ #include #include +#include + #include #include -#include -#include - namespace MaterialX { @@ -27,8 +26,9 @@ static string FILTER_TYPE_POST_FIX("_filtertype"); static string DEFAULT_COLOR_POST_FIX("_default"); // -// Creator +// GlslProgram methods // + GlslProgramPtr GlslProgram::create() { return std::shared_ptr(new GlslProgram()); @@ -135,7 +135,7 @@ unsigned int GlslProgram::build() // Compile vertex shader const char* vertexChar = vertexShaderSource.c_str(); - glShaderSource(vertexShaderId, 1, &vertexChar, NULL); + glShaderSource(vertexShaderId, 1, &vertexChar, nullptr); glCompileShader(vertexShaderId); // Check Vertex Shader @@ -147,8 +147,7 @@ unsigned int GlslProgram::build() if (GLInfoLogLength > 0) { std::vector vsErrorMessage(GLInfoLogLength + 1); - glGetShaderInfoLog(vertexShaderId, GLInfoLogLength, NULL, - &vsErrorMessage[0]); + glGetShaderInfoLog(vertexShaderId, GLInfoLogLength, nullptr, &vsErrorMessage[0]); errors.push_back(&vsErrorMessage[0]); } } @@ -167,7 +166,7 @@ unsigned int GlslProgram::build() // Compile fragment shader const char *fragmentChar = fragmentShaderSource.c_str(); - glShaderSource(fragmentShaderId, 1, &fragmentChar, NULL); + glShaderSource(fragmentShaderId, 1, &fragmentChar, nullptr); glCompileShader(fragmentShaderId); // Check fragment shader @@ -179,8 +178,7 @@ unsigned int GlslProgram::build() if (GLInfoLogLength > 0) { std::vector fsErrorMessage(GLInfoLogLength + 1); - glGetShaderInfoLog(fragmentShaderId, GLInfoLogLength, NULL, - &fsErrorMessage[0]); + glGetShaderInfoLog(fragmentShaderId, GLInfoLogLength, nullptr, &fsErrorMessage[0]); errors.push_back(&fsErrorMessage[0]); } } @@ -207,8 +205,7 @@ unsigned int GlslProgram::build() if (GLInfoLogLength > 0) { std::vector ProgramErrorMessage(GLInfoLogLength + 1); - glGetProgramInfoLog(_programId, GLInfoLogLength, NULL, - &ProgramErrorMessage[0]); + glGetProgramInfoLog(_programId, GLInfoLogLength, nullptr, &ProgramErrorMessage[0]); errors.push_back(&ProgramErrorMessage[0]); } } @@ -242,7 +239,7 @@ unsigned int GlslProgram::build() // errors during linking and throw one exception for them all so that // if there is a failure a complete set of issues is returned. We do // this after cleanup so keep GL state clean. - if (errors.size()) + if (!errors.empty()) { throw ExceptionShaderValidationError(errorType, errors); } @@ -365,7 +362,7 @@ void GlslProgram::bindAttribute(const GlslProgram::InputMap& inputs, MeshPtr mes glEnableVertexAttribArray(location); _enabledStreamLocations.insert(location); - glVertexAttribPointer(location, stride, GL_FLOAT, GL_FALSE, 0, 0); + glVertexAttribPointer(location, stride, GL_FLOAT, GL_FALSE, 0, nullptr); } } @@ -1519,10 +1516,10 @@ void GlslProgram::checkErrors() { errors.push_back("OpenGL error: " + std::to_string(error)); } - if (errors.size()) + if (!errors.empty()) { throw ExceptionShaderValidationError("OpenGL context error.", errors); } } -} +} // namespace MaterialX diff --git a/source/MaterialXRenderGlsl/GlslProgram.h b/source/MaterialXRenderGlsl/GlslProgram.h index f9d6f1eb03..cf3b980e28 100644 --- a/source/MaterialXRenderGlsl/GlslProgram.h +++ b/source/MaterialXRenderGlsl/GlslProgram.h @@ -9,13 +9,12 @@ /// @file /// GLSL Program interfaces -#include - -#include -#include -#include #include +#include #include +#include + +#include namespace MaterialX { @@ -23,7 +22,7 @@ namespace MaterialX // Shared pointer to a GlslProgram using GlslProgramPtr = std::shared_ptr; -/// @class @GlslProgram +/// @class GlslProgram /// GLSL program helper class to perform validation of GLSL source code. /// /// There are two main interfaces which can be used. One which takes in a HwShader and one which diff --git a/source/MaterialXRenderGlsl/GlslValidator.h b/source/MaterialXRenderGlsl/GlslValidator.h index 6cea709c13..379169e515 100644 --- a/source/MaterialXRenderGlsl/GlslValidator.h +++ b/source/MaterialXRenderGlsl/GlslValidator.h @@ -10,7 +10,6 @@ /// GLSL code validator #include -#include #include #include #include @@ -22,7 +21,7 @@ namespace MaterialX // Shared pointer to a GlslProgram using GlslValidatorPtr = std::shared_ptr; -/// @class @GlslValidator +/// @class GlslValidator /// Helper class to perform validation of GLSL source code generated by the GLSL code generator. /// /// There are two main interfaces which can be used. One which takes in a HwShader and one which diff --git a/source/MaterialXRenderOsl/OslValidator.h b/source/MaterialXRenderOsl/OslValidator.h index 301a86a6a7..d50852a720 100644 --- a/source/MaterialXRenderOsl/OslValidator.h +++ b/source/MaterialXRenderOsl/OslValidator.h @@ -9,7 +9,6 @@ /// @file /// OSL code validator -#include #include #include diff --git a/source/MaterialXTest/File.cpp b/source/MaterialXTest/File.cpp index df735624cf..15a31fce1c 100644 --- a/source/MaterialXTest/File.cpp +++ b/source/MaterialXTest/File.cpp @@ -24,8 +24,7 @@ TEST_CASE("Syntactic operations", "[file]") for (const InputPair& pair : inputPairs) { - mx::FilePath path; - path.assign(pair.first, pair.second); + mx::FilePath path(pair.first); REQUIRE(path.asString(pair.second) == pair.first); } } @@ -49,20 +48,19 @@ TEST_CASE("File system operations", "[file]") TEST_CASE("File search path operations", "[file]") { - std::string searchPath = "libraries/stdlib" + - mx::PATH_LIST_SEPARATOR + - "resources/Materials/Examples/Syntax"; + mx::FileSearchPath searchPath = "libraries/stdlib" + + mx::PATH_LIST_SEPARATOR + + "resources/Materials/Examples/Syntax"; - mx::StringVec filenames = + mx::FilePathVec filenames = { "stdlib_defs.mtlx", "MaterialBasic.mtlx", "PaintMaterials.mtlx", }; - for (const std::string& filename : filenames) + for (const mx::FilePath& filename : filenames) { - mx::FilePath path(filename); - REQUIRE(mx::FileSearchPath(searchPath, mx::PATH_LIST_SEPARATOR).find(path).exists()); + REQUIRE(searchPath.find(filename).exists()); } } diff --git a/source/MaterialXTest/Geom.cpp b/source/MaterialXTest/Geom.cpp index 768f78d43b..c1a202cdb0 100644 --- a/source/MaterialXTest/Geom.cpp +++ b/source/MaterialXTest/Geom.cpp @@ -42,7 +42,7 @@ TEST_CASE("Geom elements", "[geom]") nodeGraph->setFilePrefix("folder/"); REQUIRE_THROWS_AS(doc->addNodeGraph(nodeGraph->getName()), mx::Exception&); mx::NodePtr image = nodeGraph->addNode("image"); - image->setParameterValue("file", std::string("_diffuse_.tif"), mx::FILENAME_TYPE_STRING); + image->setParameterValue("file", "_diffuse_.tif", mx::FILENAME_TYPE_STRING); // Test filename string substitutions. mx::ParameterPtr fileParam = image->getParameter("file"); diff --git a/source/MaterialXTest/Material.cpp b/source/MaterialXTest/Material.cpp index af1cd34d1e..631d5dbf6d 100644 --- a/source/MaterialXTest/Material.cpp +++ b/source/MaterialXTest/Material.cpp @@ -19,7 +19,7 @@ TEST_CASE("Material", "[material]") mx::InputPtr diffColor = simpleSrf->setInputValue("diffColor", mx::Color3(1.0f)); mx::InputPtr specColor = simpleSrf->setInputValue("specColor", mx::Color3(0.0f)); mx::ParameterPtr roughness = simpleSrf->setParameterValue("roughness", 0.25f); - mx::TokenPtr texId = simpleSrf->setTokenValue("texId", std::string("01")); + mx::TokenPtr texId = simpleSrf->setTokenValue("texId", "01"); REQUIRE(simpleSrf->getInputValue("diffColor")->asA() == mx::Color3(1.0f)); REQUIRE(simpleSrf->getInputValue("specColor")->asA() == mx::Color3(0.0f)); REQUIRE(simpleSrf->getParameterValue("roughness")->asA() == 0.25f); @@ -68,7 +68,7 @@ TEST_CASE("Material", "[material]") // Bind a shader token to a value. mx::BindTokenPtr bindToken = refAnisoSrf->addBindToken("texId"); - bindToken->setValue(std::string("02")); + bindToken->setValue("02"); REQUIRE(texId->getBoundValue(material)->asA() == "02"); REQUIRE(texId->getDefaultValue()->asA() == "01"); mx::StringResolverPtr resolver = doc->createStringResolver(mx::UNIVERSAL_GEOM_NAME, material); diff --git a/source/MaterialXTest/Node.cpp b/source/MaterialXTest/Node.cpp index e964de7037..6b1bffc5fc 100644 --- a/source/MaterialXTest/Node.cpp +++ b/source/MaterialXTest/Node.cpp @@ -137,9 +137,9 @@ TEST_CASE("Node", "[node]") TEST_CASE("Flatten", "[nodegraph]") { - std::string searchPath = "resources/Materials/Examples/Syntax" + - mx::PATH_LIST_SEPARATOR + - "libraries/stdlib"; + mx::FileSearchPath searchPath = "resources/Materials/Examples/Syntax" + + mx::PATH_LIST_SEPARATOR + + "libraries/stdlib"; // Read the example file. mx::DocumentPtr doc = mx::createDocument(); diff --git a/source/MaterialXTest/Render.cpp b/source/MaterialXTest/Render.cpp index dceff6dc26..c1a74117d6 100644 --- a/source/MaterialXTest/Render.cpp +++ b/source/MaterialXTest/Render.cpp @@ -14,8 +14,8 @@ #include #include +#include #include -#include #include diff --git a/source/MaterialXTest/RenderOSL.cpp b/source/MaterialXTest/RenderOSL.cpp index a3ae490ddb..208c1cb982 100644 --- a/source/MaterialXTest/RenderOSL.cpp +++ b/source/MaterialXTest/RenderOSL.cpp @@ -73,11 +73,9 @@ void OslShaderRenderTester::createValidator(std::ostream& log) _validator->setOslOutputFilePath(shaderPath); const std::string OSL_EXTENSION("osl"); - mx::FilePathVec files = shaderPath.getFilesInDirectory(OSL_EXTENSION); - for (const auto& file : files) + for (const mx::FilePath& filename : shaderPath.getFilesInDirectory(OSL_EXTENSION)) { - mx::FilePath filePath = shaderPath / file; - _validator->compileOSL(filePath.asString()); + _validator->compileOSL(shaderPath / filename); } // Set the search path for these compiled shaders. diff --git a/source/MaterialXTest/RenderUtil.cpp b/source/MaterialXTest/RenderUtil.cpp index 7645a55d08..d0d63b9774 100644 --- a/source/MaterialXTest/RenderUtil.cpp +++ b/source/MaterialXTest/RenderUtil.cpp @@ -86,12 +86,11 @@ void ShaderRenderTester::loadDependentLibraries(GenShaderUtil::TestSuiteOptions mx::loadLibraries(libraries, searchPath, dependLib, nullptr); for (size_t i = 0; i < options.externalLibraryPaths.size(); i++) { - const mx::FilePath& extraPath = options.externalLibraryPaths[i]; - mx::FilePathVec libraryFiles = extraPath.getFilesInDirectory("mtlx"); - for (size_t l = 0; l < libraryFiles.size(); l++) + const mx::FilePath& libraryPath = options.externalLibraryPaths[i]; + for (const mx::FilePath& libraryFile : libraryPath.getFilesInDirectory("mtlx")) { - std::cout << "Extra library path: " << (extraPath / libraryFiles[l]).asString() << std::endl; - mx::loadLibrary((extraPath / libraryFiles[l]), dependLib); + std::cout << "Extra library path: " << (libraryPath / libraryFile).asString() << std::endl; + mx::loadLibrary((libraryPath / libraryFile), dependLib); } } @@ -235,35 +234,33 @@ bool ShaderRenderTester::validate(const mx::FilePathVec& testRootPaths, const mx continue; } - const mx::FilePath filePath = mx::FilePath(dir) / mx::FilePath(file); - const std::string filename = filePath; - + const mx::FilePath filename = mx::FilePath(dir) / mx::FilePath(file); mx::DocumentPtr doc = mx::createDocument(); try { - mx::FileSearchPath readSearchPath(searchPath.asString()); + mx::FileSearchPath readSearchPath(searchPath); readSearchPath.append(dir); - mx::readFromXmlFile(doc, filename, readSearchPath.asString()); + mx::readFromXmlFile(doc, filename, readSearchPath); } catch (mx::Exception& e) { - docValidLog << "Failed to load in file: " << filename << ". Error: " << e.what() << std::endl; - WARN("Failed to load in file: " + filename + "See: " + docValidLogFilename + " for details."); + docValidLog << "Failed to load in file: " << filename.asString() << ". Error: " << e.what() << std::endl; + WARN("Failed to load in file: " + filename.asString() + "See: " + docValidLogFilename + " for details."); } doc->importLibrary(dependLib, ©Options); ioTimer.endTimer(); validateTimer.startTimer(); - std::cout << "- Validating MTLX file: " << filename << std::endl; - log << "MTLX Filename: " << filename << std::endl; + std::cout << "- Validating MTLX file: " << filename.asString() << std::endl; + log << "MTLX Filename: " << filename.asString() << std::endl; // Validate the test document std::string validationErrors; bool validDoc = doc->validate(&validationErrors); if (!validDoc) { - docValidLog << filename << std::endl; + docValidLog << filename.asString() << std::endl; docValidLog << validationErrors << std::endl; } validateTimer.endTimer(); diff --git a/source/MaterialXTest/Value.cpp b/source/MaterialXTest/Value.cpp index 4007526391..1d291a570d 100644 --- a/source/MaterialXTest/Value.cpp +++ b/source/MaterialXTest/Value.cpp @@ -50,8 +50,7 @@ TEST_CASE("Value strings", "[value]") REQUIRE(mx::toValueString(mx::Color3(1.0f)) == "1, 1, 1"); REQUIRE(mx::toValueString(std::string("text")) == "text"); - // Convert from data values to value strings - // using the various float formattings. + // Convert from floats to value strings with custom formatting. { mx::ScopedFloatFormatting fmt(mx::Value::FloatFormatFixed, 3); REQUIRE(mx::toValueString(0.1234f) == "0.123"); @@ -119,4 +118,9 @@ TEST_CASE("Typed values", "[value]") // Alias types testTypedValue(1l, 2l); testTypedValue(1.0, 2.0); + + // Construct a string value from a string literal + mx::ValuePtr value = mx::Value::createValue("text"); + REQUIRE(value->isA()); + REQUIRE(value->asA() == "text"); } diff --git a/source/MaterialXTest/XmlIo.cpp b/source/MaterialXTest/XmlIo.cpp index 64332055b0..bfc291fb68 100644 --- a/source/MaterialXTest/XmlIo.cpp +++ b/source/MaterialXTest/XmlIo.cpp @@ -15,13 +15,13 @@ TEST_CASE("Load content", "[xmlio]") { mx::FilePath libraryPath("libraries/stdlib"); mx::FilePath examplesPath("resources/Materials/Examples/Syntax"); - std::string searchPath = libraryPath.asString() + - mx::PATH_LIST_SEPARATOR + - examplesPath.asString(); + mx::FileSearchPath searchPath = libraryPath.asString() + + mx::PATH_LIST_SEPARATOR + + examplesPath.asString(); // Read the standard library. std::vector libs; - for (std::string filename : libraryPath.getFilesInDirectory(mx::MTLX_EXTENSION)) + for (const mx::FilePath& filename : libraryPath.getFilesInDirectory(mx::MTLX_EXTENSION)) { mx::DocumentPtr lib = mx::createDocument(); mx::readFromXmlFile(lib, filename, searchPath); @@ -29,7 +29,7 @@ TEST_CASE("Load content", "[xmlio]") } // Read and validate each example document. - for (std::string filename : examplesPath.getFilesInDirectory(mx::MTLX_EXTENSION)) + for (const mx::FilePath& filename : examplesPath.getFilesInDirectory(mx::MTLX_EXTENSION)) { mx::DocumentPtr doc = mx::createDocument(); mx::readFromXmlFile(doc, filename, searchPath); @@ -41,7 +41,7 @@ TEST_CASE("Load content", "[xmlio]") bool docValid = doc->validate(&message); if (!docValid) { - WARN("[" + filename + "] " + message); + WARN("[" + filename.asString() + "] " + message); } REQUIRE(docValid); @@ -174,7 +174,7 @@ TEST_CASE("Load content", "[xmlio]") REQUIRE(*flatDoc != *doc); // Read document using environment search path. - mx::setEnviron(mx::MATERIALX_SEARCH_PATH_ENV_VAR, searchPath); + mx::setEnviron(mx::MATERIALX_SEARCH_PATH_ENV_VAR, searchPath.asString()); mx::DocumentPtr envDoc = mx::createDocument(); mx::readFromXmlFile(envDoc, filename); REQUIRE(*envDoc == *doc); diff --git a/source/MaterialXView/Editor.cpp b/source/MaterialXView/Editor.cpp index 39a8176e12..6da21a8335 100644 --- a/source/MaterialXView/Editor.cpp +++ b/source/MaterialXView/Editor.cpp @@ -3,13 +3,13 @@ #include #include +#include +#include #include #include -#include -#include #include -#include -#include +#include +#include namespace { @@ -24,12 +24,12 @@ class EditorFormHelper : public ng::FormHelper void setVariableSpacing(int val) { mVariableSpacing = val; } }; -// Custom color picker so we can get numeric entry and feedback. +// Custom color picker with numeric entry and feedback. // -class MyColorPicker : public ng::ColorPicker +class EditorColorPicker : public ng::ColorPicker { public: - MyColorPicker(ng::Widget *parent, const ng::Color& color) : + EditorColorPicker(ng::Widget *parent, const ng::Color& color) : ng::ColorPicker(parent, color) { ng::Popup *popup = this->popup(); @@ -218,18 +218,18 @@ void PropertyEditor::addItemToForm(const mx::UIPropertyItem& item, const std::st auto indexInEnumeration = [&value, &enumValues, &enumeration]() { size_t index = 0; - for(auto& enumValue: enumValues) + for (auto& enumValue: enumValues) { - if(value->getValueString() == enumValue->getValueString()) + if (value->getValueString() == enumValue->getValueString()) { return index; } index++; } index = 0; - for(auto& enumName: enumeration) + for (auto& enumName: enumeration) { - if(value->getValueString() == enumName) + if (value->getValueString() == enumName) { return index; } @@ -255,11 +255,11 @@ void PropertyEditor::addItemToForm(const mx::UIPropertyItem& item, const std::st comboBox->setCallback([path, viewer, enumeration, enumValues](int index) { MaterialPtr material = viewer->getSelectedMaterial(); - if(index >= 0 && static_cast(index) < enumValues.size()) + if (index >= 0 && static_cast(index) < enumValues.size()) { material->setUniformInt(path, enumValues[index]->asA()); } - else if(index >= 0 && static_cast(index) < enumeration.size()) + else if (index >= 0 && static_cast(index) < enumeration.size()) { material->setUniformEnum(path, index, enumeration[index]); } @@ -308,7 +308,7 @@ void PropertyEditor::addItemToForm(const mx::UIPropertyItem& item, const std::st boolVar->setCallback([path, viewer](bool v) { MaterialPtr material = viewer->getSelectedMaterial(); - if(material) + if (material) { material->setUniformFloat(path, v); } @@ -328,13 +328,13 @@ void PropertyEditor::addItemToForm(const mx::UIPropertyItem& item, const std::st c.g() = v[1]; c.b() = 0.0f; c.w() = 1.0f; - auto colorVar = new MyColorPicker(twoColumns, c); + auto colorVar = new EditorColorPicker(twoColumns, c); colorVar->setFixedSize({ 100, 20 }); colorVar->setFontSize(15); colorVar->setFinalCallback([path, viewer, colorVar](const ng::Color &c) { MaterialPtr material = viewer->getSelectedMaterial(); - if(material) + if (material) { ng::Vector2f v; v.x() = c.r(); @@ -357,7 +357,7 @@ void PropertyEditor::addItemToForm(const mx::UIPropertyItem& item, const std::st // Determine if there is an enumeration for this mx::Color3 color = value->asA(); int index = -1; - if (enumeration.size() && enumValues.size()) + if (!enumeration.empty() && !enumValues.empty()) { index = 0; for (size_t i = 0; i < enumValues.size(); i++) @@ -405,7 +405,7 @@ void PropertyEditor::addItemToForm(const mx::UIPropertyItem& item, const std::st c.w() = 1.0; new ng::Label(twoColumns, label); - auto colorVar = new MyColorPicker(twoColumns, c); + auto colorVar = new EditorColorPicker(twoColumns, c); colorVar->setFixedSize({ 100, 20 }); colorVar->setFontSize(15); colorVar->setFinalCallback([path, viewer](const ng::Color &c) @@ -433,7 +433,7 @@ void PropertyEditor::addItemToForm(const mx::UIPropertyItem& item, const std::st c.g() = v[1]; c.b() = v[2]; c.w() = v[3]; - auto colorVar = new MyColorPicker(twoColumns, c); + auto colorVar = new EditorColorPicker(twoColumns, c); colorVar->setFixedSize({ 100, 20 }); colorVar->setFontSize(15); colorVar->setFinalCallback([path, viewer](const ng::Color &c) @@ -661,7 +661,7 @@ void PropertyEditor::addItemToForm(const mx::UIPropertyItem& item, const std::st { if (uniform->getType() == mx::Type::FILENAME) { - const mx::GLTextureHandlerPtr handler = viewer->getImageHandler(); + mx::GLTextureHandlerPtr handler = viewer->getImageHandler(); if (handler) { mx::StringSet extensions; @@ -715,6 +715,20 @@ void PropertyEditor::updateContents(Viewer* viewer) return; } + // Shading model display + mx::TypedElementPtr elem = material ? material->getElement() : nullptr; + std::string shaderName = elem ? elem->getAttribute("node") : mx::EMPTY_STRING; + if (!shaderName.empty()) + { + ng::Widget* twoColumns = new ng::Widget(_container); + twoColumns->setLayout(_gridLayout2); + ng::Label* modelLabel = new ng::Label(twoColumns, "Shading Model"); + modelLabel->setFontSize(20); + modelLabel->setFont("sans-bold"); + ng::Label* nameLabel = new ng::Label(twoColumns, shaderName); + nameLabel->setFontSize(20); + } + const bool showAdvancedItems = viewer->showAdvancedProperties(); bool addedItems = false; const mx::VariableBlock* publicUniforms = material->getPublicUniforms(); @@ -734,7 +748,7 @@ void PropertyEditor::updateContents(Viewer* viewer) const std::string& folder = it->first; const mx::UIPropertyItem& item = it->second; - if(item.ui.uiAdvanced && !showAdvancedItems) + if (item.ui.uiAdvanced && !showAdvancedItems) { continue; } diff --git a/source/MaterialXView/Main.cpp b/source/MaterialXView/Main.cpp index fe0ef3c156..c939ea9472 100644 --- a/source/MaterialXView/Main.cpp +++ b/source/MaterialXView/Main.cpp @@ -28,13 +28,13 @@ int main(int argc, char* const argv[]) tokens.push_back(std::string(argv[i])); } - mx::StringVec libraryFolders = { "libraries/stdlib", "libraries/pbrlib", "libraries/stdlib/genglsl", "libraries/pbrlib/genglsl", - "libraries/bxdf", "libraries/lights", "libraries/lights/genglsl" }; + mx::FilePathVec libraryFolders = { "libraries/stdlib", "libraries/pbrlib", "libraries/stdlib/genglsl", "libraries/pbrlib/genglsl", + "libraries/bxdf", "libraries/lights", "libraries/lights/genglsl" }; mx::FileSearchPath searchPath; std::string meshFilename = "resources/Geometry/shaderball.obj"; std::string materialFilename = "resources/Materials/Examples/StandardSurface/standard_surface_default.mtlx"; - std::string envRadiancePath = "resources/Images/goegap_4k_dim.hdr"; - std::string envIrradiancePath = "resources/Images/goegap_4k_dim.convolved.hdr"; + std::string envRadiancePath = "resources/Images/san_giuseppe_bridge.hdr"; + std::string envIrradiancePath = "resources/Images/san_giuseppe_bridge_diffuse.hdr"; DocumentModifiers modifiers; int multiSampleCount = 0; int refresh = 50; @@ -108,8 +108,7 @@ int main(int argc, char* const argv[]) // Search current directory and parent directory if not found. mx::FilePath currentPath(mx::FilePath::getCurrentPath()); - mx::FilePath parentCurrentPath(currentPath); - parentCurrentPath.pop(); + mx::FilePath parentCurrentPath = currentPath.getParentPath(); std::vector libraryPaths = { mx::FilePath("libraries") diff --git a/source/MaterialXView/Material.cpp b/source/MaterialXView/Material.cpp index e5857c90c4..22bff5bb90 100644 --- a/source/MaterialXView/Material.cpp +++ b/source/MaterialXView/Material.cpp @@ -322,7 +322,7 @@ void Material::bindImages(mx::GLTextureHandlerPtr imageHandler, const mx::FileSe mx::Color4 fallbackColor(0, 0, 0, 1); for (const auto& uniform : publicUniforms->getVariableOrder()) { - if (uniform->getType() != MaterialX::Type::FILENAME) + if (uniform->getType() != mx::Type::FILENAME) { continue; } @@ -347,7 +347,8 @@ void Material::bindImages(mx::GLTextureHandlerPtr imageHandler, const mx::FileSe } mx::FilePath Material::bindImage(const mx::FilePath& filePath, const std::string& uniformName, mx::GLTextureHandlerPtr imageHandler, - mx::ImageDesc& desc, const mx::ImageSamplingProperties& samplingProperties, const std::string& udim, mx::Color4* fallbackColor) + mx::ImageDesc& desc, const mx::ImageSamplingProperties& samplingProperties, const std::string& udim, + mx::Color4* fallbackColor) { mx::FilePath returnPath; @@ -612,7 +613,7 @@ mx::ShaderPort* Material::findUniform(const std::string& path) const void Material::changeUniformElement(mx::ShaderPort* uniform, const std::string& value) { - if (nullptr == uniform) + if (!uniform) { throw std::runtime_error("Null ShaderPort"); } @@ -620,7 +621,7 @@ void Material::changeUniformElement(mx::ShaderPort* uniform, const std::string& mx::ElementPtr element = _doc->getDescendant(uniform->getPath()); if (element) { - mx::ValueElementPtr valueElement = element->asA(); + mx::ValueElementPtr valueElement = element->asA(); if (valueElement) { valueElement->setValueString(value); diff --git a/source/MaterialXView/Material.h b/source/MaterialXView/Material.h index 7aa42defe6..5082a6522d 100644 --- a/source/MaterialXView/Material.h +++ b/source/MaterialXView/Material.h @@ -142,8 +142,9 @@ class Material void unbindImages(mx::GLTextureHandlerPtr imageHandler); /// Bind a single image. - mx::FilePath bindImage(const mx::FilePath& filename, const std::string& uniformName, mx::GLTextureHandlerPtr imageHandler, - mx::ImageDesc& desc, const mx::ImageSamplingProperties& samplingProperties, const std::string& udim = mx::EMPTY_STRING, mx::Color4* fallbackColor = nullptr); + mx::FilePath bindImage(const mx::FilePath& filePath, const std::string& uniformName, mx::GLTextureHandlerPtr imageHandler, + mx::ImageDesc& desc, const mx::ImageSamplingProperties& samplingProperties, const std::string& udim = mx::EMPTY_STRING, + mx::Color4* fallbackColor = nullptr); /// Bind lights to shader. void bindLights(mx::LightHandlerPtr lightHandler, mx::GLTextureHandlerPtr imageHandler, const mx::FileSearchPath& imagePath, @@ -167,22 +168,22 @@ class Material /// Change the uniform value inside the shader and the associated element in the MaterialX document. void changeUniformElement(mx::ShaderPort* uniform, const std::string& value); - /// Set the value for an element with a given path. + /// Set the value for an integer element with a given path. void setUniformInt(const std::string& path, int value); - /// Set the value for an element with a given path. + /// Set the value for a float element with a given path. void setUniformFloat(const std::string& path, float value); - /// Set the value for an element with a given path. + /// Set the value for a vector2 element with a given path. void setUniformVec2(const std::string& path, const ng::Vector2f& value); - /// Set the value for an element with a given path. + /// Set the value for a vector3 element with a given path. void setUniformVec3(const std::string& path, const ng::Vector3f& value); - /// Set the value for an element with a given path. + /// Set the value for a vector4 element with a given path. void setUniformVec4(const std::string& path, const ng::Vector4f& value); - /// Set the value for an element with a given path. + /// Set the value for an enumerated element with a given path. void setUniformEnum(const std::string& path, int index, const std::string& value); protected: diff --git a/source/MaterialXView/Viewer.cpp b/source/MaterialXView/Viewer.cpp index afb338f62b..67b04e0c3b 100644 --- a/source/MaterialXView/Viewer.cpp +++ b/source/MaterialXView/Viewer.cpp @@ -56,10 +56,7 @@ bool stringEndsWith(const std::string& str, std::string const& end) { return !str.compare(str.length() - end.length(), end.length(), end); } - else - { - return false; - } + return false; } void writeTextFile(const std::string& text, const std::string& filePath) @@ -70,31 +67,26 @@ void writeTextFile(const std::string& text, const std::string& filePath) file.close(); } -std::pair loadLibraries(const mx::StringVec& libraryFolders, const mx::FileSearchPath& searchPath) +mx::DocumentPtr loadLibraries(const mx::FilePathVec& libraryFolders, const mx::FileSearchPath& searchPath) { mx::DocumentPtr doc = mx::createDocument(); - mx::StringVec xincludeFiles; for (const std::string& libraryFolder : libraryFolders) { - mx::FilePath path = searchPath.find(libraryFolder); - mx::FilePathVec filenames = path.getFilesInDirectory("mtlx"); - mx::CopyOptions copyOptions; copyOptions.skipConflictingElements = true; mx::XmlReadOptions readOptions; readOptions.skipConflictingElements = true; - for (const std::string& filename : filenames) + + mx::FilePath libraryPath = searchPath.find(libraryFolder); + for (const mx::FilePath& filename : libraryPath.getFilesInDirectory("mtlx")) { - mx::FilePath file = path / filename; mx::DocumentPtr libDoc = mx::createDocument(); - mx::readFromXmlFile(libDoc, file, mx::EMPTY_STRING, &readOptions); - libDoc->setSourceUri(file); + mx::readFromXmlFile(libDoc, libraryPath / filename, mx::FileSearchPath(), &readOptions); doc->importLibrary(libDoc, ©Options); - xincludeFiles.push_back(file); } } - return std::make_pair(doc, xincludeFiles); + return doc; } void applyModifiers(mx::DocumentPtr doc, const DocumentModifiers& modifiers) @@ -163,7 +155,7 @@ void applyModifiers(mx::DocumentPtr doc, const DocumentModifiers& modifiers) // Viewer methods // -Viewer::Viewer(const mx::StringVec& libraryFolders, +Viewer::Viewer(const mx::FilePathVec& libraryFolders, const mx::FileSearchPath& searchPath, const std::string& meshFilename, const std::string& materialFilename, @@ -242,7 +234,7 @@ Viewer::Viewer(const mx::StringVec& libraryFolders, { setSelectedMaterial(_materialAssignments[getSelectedGeometry()]); } - updatePropertyEditor(); + updateDisplayedProperties(); updateMaterialSelectionUI(); } }); @@ -272,17 +264,7 @@ Viewer::Viewer(const mx::StringVec& libraryFolders, _lightFileName = "resources/Materials/TestSuite/Utilities/Lights/default_viewer_lights.mtlx"; // Initialize standard library and color management. - const auto stdDocAndXIncludes = loadLibraries(_libraryFolders, _searchPath); - _stdLib = stdDocAndXIncludes.first; - _xincludeFiles = stdDocAndXIncludes.second; - - mx::DefaultColorManagementSystemPtr cms = mx::DefaultColorManagementSystem::create(_genContext.getShaderGenerator().getLanguage()); - cms->loadLibrary(_stdLib); - for (size_t i = 0; i < _searchPath.size(); i++) - { - _genContext.registerSourceCodeSearchPath(_searchPath[i]); - } - _genContext.getShaderGenerator().setColorManagementSystem(cms); + loadStandardLibraries(); // Generate wireframe material. const std::string constantShaderName("__WIRE_SHADER_NAME__"); @@ -363,13 +345,13 @@ void Viewer::setupLights(mx::DocumentPtr doc) { mx::XmlReadOptions readOptions; readOptions.skipConflictingElements = true; - mx::readFromXmlFile(lightDoc, path.asString(), mx::EMPTY_STRING, &readOptions); + mx::readFromXmlFile(lightDoc, path, mx::FileSearchPath(), &readOptions); lightDoc->setSourceUri(path); mx::CopyOptions copyOptions; copyOptions.skipConflictingElements = true; doc->importLibrary(lightDoc, ©Options); - _xincludeFiles.push_back(path); + _xincludeFiles.insert(path); } catch (std::exception& e) { @@ -450,7 +432,7 @@ void Viewer::assignMaterial(mx::MeshPartitionPtr geometry, MaterialPtr material) if (geometry == getSelectedGeometry()) { setSelectedMaterial(material); - updatePropertyEditor(); + updateDisplayedProperties(); } } @@ -537,14 +519,14 @@ void Viewer::createSaveMaterialsInterface(Widget* parent, const std::string& lab { if (elem->hasSourceUri()) { - return (std::find(_xincludeFiles.begin(), _xincludeFiles.end(), elem->getSourceUri()) == _xincludeFiles.end()); + return (_xincludeFiles.count(elem->getSourceUri()) == 0); } return true; }; mx::XmlWriteOptions writeOptions; writeOptions.writeXIncludeEnable = true; writeOptions.elementPredicate = skipXincludes; - MaterialX::writeToXmlFile(doc, filename, &writeOptions); + mx::writeToXmlFile(doc, filename, &writeOptions); } // Update material file name @@ -668,7 +650,7 @@ void Viewer::createAdvancedSettings(Widget* parent) showAdvancedProperties->setCallback([this](bool enable) { _showAdvancedProperties = enable; - updatePropertyEditor(); + updateDisplayedProperties(); }); } @@ -785,17 +767,17 @@ void Viewer::loadDocument(const mx::FilePath& filename, mx::DocumentPtr librarie // Set up read options. mx::XmlReadOptions readOptions; readOptions.skipConflictingElements = true; - readOptions.readXIncludeFunction = [](mx::DocumentPtr doc, const std::string& filename, - const std::string& searchPath, const mx::XmlReadOptions* options) + readOptions.readXIncludeFunction = [](mx::DocumentPtr doc, const mx::FilePath& filename, + const mx::FileSearchPath& searchPath, const mx::XmlReadOptions* options) { - mx::FilePath resolvedFilename = mx::FileSearchPath(searchPath).find(filename); + mx::FilePath resolvedFilename = searchPath.find(filename); if (resolvedFilename.exists()) { readFromXmlFile(doc, resolvedFilename, searchPath, options); } else { - std::cerr << "Include file not found: " << filename << std::endl; + std::cerr << "Include file not found: " << filename.asString() << std::endl; } }; @@ -820,7 +802,7 @@ void Viewer::loadDocument(const mx::FilePath& filename, mx::DocumentPtr librarie { // Load source document. mx::DocumentPtr doc = mx::createDocument(); - mx::readFromXmlFile(doc, filename, _searchPath.asString(), &readOptions); + mx::readFromXmlFile(doc, filename, _searchPath, &readOptions); // Import libraries. mx::CopyOptions copyOptions; @@ -891,8 +873,7 @@ void Viewer::loadDocument(const mx::FilePath& filename, mx::DocumentPtr librarie _materials.insert(_materials.end(), newMaterials.begin(), newMaterials.end()); // Set the default image search path. - mx::FilePath materialFolder = _materialFilename; - materialFolder.pop(); + mx::FilePath materialFolder = _materialFilename.getParentPath(); _imageHandler->setSearchPath(mx::FileSearchPath(materialFolder)); mx::MeshPtr mesh = _geometryHandler->getMeshes()[0]; @@ -933,9 +914,8 @@ void Viewer::loadDocument(const mx::FilePath& filename, mx::DocumentPtr librarie mx::MaterialPtr materialRef = shaderRef ? shaderRef->getParent()->asA() : nullptr; if (materialRef) { - for (size_t partIndex = 0; partIndex < _geometryList.size(); partIndex++) + for (mx::MeshPartitionPtr part : _geometryList) { - mx::MeshPartitionPtr part = _geometryList[partIndex]; std::string partGeomName = part->getIdentifier(); if (!materialRef->getGeometryBindings(partGeomName).empty()) { @@ -1087,6 +1067,19 @@ void Viewer::saveDotFiles() } } +void Viewer::loadStandardLibraries() +{ + // Initialize standard library and color management. + _stdLib = loadLibraries(_libraryFolders, _searchPath); + mx::DefaultColorManagementSystemPtr cms = mx::DefaultColorManagementSystem::create(_genContext.getShaderGenerator().getLanguage()); + cms->loadLibrary(_stdLib); + for (const mx::FilePath& filePath : _searchPath) + { + _genContext.registerSourceCodeSearchPath(filePath); + } + _genContext.getShaderGenerator().setColorManagementSystem(cms); +} + bool Viewer::keyboardEvent(int key, int scancode, int action, int modifiers) { if (Screen::keyboardEvent(key, scancode, action, modifiers)) @@ -1104,6 +1097,17 @@ bool Viewer::keyboardEvent(int key, int scancode, int action, int modifiers) return true; } + // Reload all files from standard library + if (key == GLFW_KEY_R && modifiers == GLFW_MOD_SHIFT && action == GLFW_PRESS) + { + MaterialPtr material = getSelectedMaterial(); + mx::DocumentPtr doc = material ? material->getDocument() : nullptr; + mx::FilePath filename = doc ? mx::FilePath(doc->getSourceUri()) : _materialFilename; + loadStandardLibraries(); + loadDocument(filename, _stdLib); + return true; + } + // Save the current shader source to file. if (key == GLFW_KEY_S && action == GLFW_PRESS) { @@ -1616,7 +1620,7 @@ void Viewer::computeCameraMatrices(mx::Matrix44& world, world *= mx::Matrix44::createTranslation(_modelTranslation).getTranspose(); } -void Viewer::updatePropertyEditor() +void Viewer::updateDisplayedProperties() { _propertyEditor.updateContents(this); } diff --git a/source/MaterialXView/Viewer.h b/source/MaterialXView/Viewer.h index 77872fcb0b..321670a95b 100644 --- a/source/MaterialXView/Viewer.h +++ b/source/MaterialXView/Viewer.h @@ -13,7 +13,7 @@ namespace ng = nanogui; class Viewer : public ng::Screen { public: - Viewer(const mx::StringVec& libraryFolders, + Viewer(const mx::FilePathVec& libraryFolders, const mx::FileSearchPath& searchPath, const std::string& meshFilename, const std::string& materialFilename, @@ -71,7 +71,7 @@ class Viewer : public ng::Screen return _searchPath; } - const mx::GLTextureHandlerPtr getImageHandler() const + mx::GLTextureHandlerPtr getImageHandler() const { return _imageHandler; } @@ -88,6 +88,7 @@ class Viewer : public ng::Screen void setupLights(mx::DocumentPtr doc); void loadDocument(const mx::FilePath& filename, mx::DocumentPtr libraries); void reloadShaders(); + void loadStandardLibraries(); void saveShaderSource(); void loadShaderSource(); void saveDotFiles(); @@ -103,7 +104,7 @@ class Viewer : public ng::Screen void updateGeometrySelections(); void updateMaterialSelections(); void updateMaterialSelectionUI(); - void updatePropertyEditor(); + void updateDisplayedProperties(); void createLoadMeshInterface(Widget* parent, const std::string& label); void createLoadMaterialsInterface(Widget* parent, const std::string& label); @@ -136,12 +137,12 @@ class Viewer : public ng::Screen ng::Vector2i _translationStart; // Document management - mx::StringVec _libraryFolders; + mx::FilePathVec _libraryFolders; mx::FileSearchPath _searchPath; mx::DocumentPtr _stdLib; mx::FilePath _materialFilename; DocumentModifiers _modifiers; - mx::StringVec _xincludeFiles; + mx::StringSet _xincludeFiles; // Lighting information std::string _lightFileName; diff --git a/source/PyMaterialX/PyMaterialXCore/PyDocument.cpp b/source/PyMaterialX/PyMaterialXCore/PyDocument.cpp index 7b7dd11f94..d9e12ea955 100644 --- a/source/PyMaterialX/PyMaterialXCore/PyDocument.cpp +++ b/source/PyMaterialX/PyMaterialXCore/PyDocument.cpp @@ -17,8 +17,9 @@ void bindPyDocument(py::module& mod) py::class_(mod, "Document") .def("initialize", &mx::Document::initialize) .def("copy", &mx::Document::copy) - .def("importLibrary", &mx::Document::importLibrary, + .def("importLibrary", &mx::Document::importLibrary, py::arg("library"), py::arg("copyOptions") = (const mx::CopyOptions*) nullptr) + .def("getReferencedSourceUris", &mx::Document::getReferencedSourceUris) .def("addNodeGraph", &mx::Document::addNodeGraph, py::arg("name") = mx::EMPTY_STRING) .def("getNodeGraph", &mx::Document::getNodeGraph) diff --git a/source/PyMaterialX/PyMaterialXFormat/PyFile.cpp b/source/PyMaterialX/PyMaterialXFormat/PyFile.cpp index 51a1dcea7c..8ab6c6ee77 100644 --- a/source/PyMaterialX/PyMaterialXFormat/PyFile.cpp +++ b/source/PyMaterialX/PyMaterialXFormat/PyFile.cpp @@ -25,18 +25,40 @@ void bindPyFile(py::module& mod) .export_values(); py::class_(mod, "FilePath") - .def_static("getCurrentPath", &mx::FilePath::getCurrentPath) .def(py::init<>()) .def(py::init()) .def(py::self == py::self) .def(py::self != py::self) .def(py::self / py::self) - .def("assign", &mx::FilePath::assign) - .def("asString", &mx::FilePath::asString) + .def("asString", &mx::FilePath::asString, + py::arg("format") = mx::FilePath::Format::FormatNative) .def("isEmpty", &mx::FilePath::isEmpty) .def("isAbsolute", &mx::FilePath::isAbsolute) .def("getBaseName", &mx::FilePath::getBaseName) - .def("exists", &mx::FilePath::exists); + .def("getParentPath", &mx::FilePath::getParentPath) + .def("getExtension", &mx::FilePath::getExtension) + .def("exists", &mx::FilePath::exists) + .def("isDirectory", &mx::FilePath::isDirectory) + .def("getFilesInDirectory", &mx::FilePath::getFilesInDirectory) + .def("getSubDirectories", &mx::FilePath::getSubDirectories) + .def("createDirectory", &mx::FilePath::createDirectory) + .def_static("getCurrentPath", &mx::FilePath::getCurrentPath); + + py::class_(mod, "FileSearchPath") + .def(py::init<>()) + .def(py::init(), + py::arg("searchPath"), py::arg("sep") = mx::PATH_LIST_SEPARATOR) + .def("asString", &mx::FileSearchPath::asString, + py::arg("sep") = mx::PATH_LIST_SEPARATOR) + .def("append", static_cast(&mx::FileSearchPath::append)) + .def("append", static_cast(&mx::FileSearchPath::append)) + .def("prepend", &mx::FileSearchPath::prepend) + .def("size", &mx::FileSearchPath::size) + .def("isEmpty", &mx::FileSearchPath::isEmpty) + .def("find", &mx::FileSearchPath::find); + + py::implicitly_convertible(); + py::implicitly_convertible(); mod.attr("PATH_LIST_SEPARATOR") = mx::PATH_LIST_SEPARATOR; mod.attr("MATERIALX_SEARCH_PATH_ENV_VAR") = mx::MATERIALX_SEARCH_PATH_ENV_VAR; diff --git a/source/PyMaterialX/PyMaterialXFormat/PyModule.cpp b/source/PyMaterialX/PyMaterialXFormat/PyModule.cpp index 7bd407d387..7f24691210 100644 --- a/source/PyMaterialX/PyMaterialXFormat/PyModule.cpp +++ b/source/PyMaterialX/PyMaterialXFormat/PyModule.cpp @@ -7,13 +7,13 @@ namespace py = pybind11; -void bindPyXmlIo(py::module& mod); void bindPyFile(py::module& mod); +void bindPyXmlIo(py::module& mod); PYBIND11_MODULE(PyMaterialXFormat, mod) { mod.doc() = "Module containing Python bindings for the MaterialXFormat library"; - bindPyXmlIo(mod); bindPyFile(mod); + bindPyXmlIo(mod); } diff --git a/source/PyMaterialX/PyMaterialXFormat/PyXmlIo.cpp b/source/PyMaterialX/PyMaterialXFormat/PyXmlIo.cpp index 454bc551d5..343345279b 100644 --- a/source/PyMaterialX/PyMaterialXFormat/PyXmlIo.cpp +++ b/source/PyMaterialX/PyMaterialXFormat/PyXmlIo.cpp @@ -24,7 +24,7 @@ void bindPyXmlIo(py::module& mod) .def_readwrite("elementPredicate", &mx::XmlWriteOptions::elementPredicate); mod.def("readFromXmlFileBase", &mx::readFromXmlFile, - py::arg("doc"), py::arg("filename"), py::arg("searchPath") = mx::EMPTY_STRING, py::arg("readOptions") = (mx::XmlReadOptions*) nullptr); + py::arg("doc"), py::arg("filename"), py::arg("searchPath") = mx::FileSearchPath(), py::arg("readOptions") = (mx::XmlReadOptions*) nullptr); mod.def("readFromXmlString", &mx::readFromXmlString, py::arg("doc"), py::arg("str"), py::arg("readOptions") = (mx::XmlReadOptions*) nullptr); mod.def("writeToXmlFile", mx::writeToXmlFile, diff --git a/source/PyMaterialX/PyMaterialXGenShader/PyColorManagement.cpp b/source/PyMaterialX/PyMaterialXGenShader/PyColorManagement.cpp index 853eacab02..15040df67a 100644 --- a/source/PyMaterialX/PyMaterialXGenShader/PyColorManagement.cpp +++ b/source/PyMaterialX/PyMaterialXGenShader/PyColorManagement.cpp @@ -55,7 +55,7 @@ void bindPyColorManagement(py::module& mod) .def("loadLibrary", &mx::ColorManagementSystem::loadLibrary) .def("supportsTransform", &mx::ColorManagementSystem::supportsTransform); - py::class_(mod, "DefaultColorManagementSystem") + py::class_(mod, "DefaultColorManagementSystem") .def_static("create", &mx::DefaultColorManagementSystem::create) .def("getName", &mx::DefaultColorManagementSystem::getName); } diff --git a/source/PyMaterialX/PyMaterialXGenShader/PyModule.cpp b/source/PyMaterialX/PyMaterialXGenShader/PyModule.cpp index 6ecc909e41..3192d8938b 100644 --- a/source/PyMaterialX/PyMaterialXGenShader/PyModule.cpp +++ b/source/PyMaterialX/PyMaterialXGenShader/PyModule.cpp @@ -16,6 +16,7 @@ void bindPyHwShaderGenerator(py::module& mod); void bindPyGenOptions(py::module& mod); void bindPyShaderStage(py::module& mod); void bindPyUtil(py::module& mod); +void bindPyTypeDesc(py::module& mod); PYBIND11_MODULE(PyMaterialXGenShader, mod) { @@ -30,4 +31,5 @@ PYBIND11_MODULE(PyMaterialXGenShader, mod) bindPyGenOptions(mod); bindPyShaderStage(mod); bindPyUtil(mod); + bindPyTypeDesc(mod); } diff --git a/source/PyMaterialX/PyMaterialXGenShader/PyTypeDesc.cpp b/source/PyMaterialX/PyMaterialXGenShader/PyTypeDesc.cpp new file mode 100644 index 0000000000..b59615bdd6 --- /dev/null +++ b/source/PyMaterialX/PyMaterialXGenShader/PyTypeDesc.cpp @@ -0,0 +1,32 @@ +// +// TM & (c) 2017 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd. +// All rights reserved. See LICENSE.txt for license. +// + +#include + +#include + +namespace py = pybind11; +namespace mx = MaterialX; + +void bindPyTypeDesc(py::module& mod) +{ + // Set nodelete as destructor on returned TypeDescs since they are owned + // by the container they are stored in and should not be destroyed when + // garbage collected by the python interpreter + py::class_>(mod, "TypeDesc") + .def_static("get", &mx::TypeDesc::get) + .def("getName", &mx::TypeDesc::getName) + .def("getBaseType", &mx::TypeDesc::getBaseType) + .def("getChannelIndex", &mx::TypeDesc::getChannelIndex) + .def("getSemantic", &mx::TypeDesc::getSemantic) + .def("getSize", &mx::TypeDesc::getSize) + .def("isEditable", &mx::TypeDesc::isEditable) + .def("isScalar", &mx::TypeDesc::isScalar) + .def("isAggregate", &mx::TypeDesc::isAggregate) + .def("isArray", &mx::TypeDesc::isArray) + .def("isFloat2", &mx::TypeDesc::isFloat2) + .def("isFloat3", &mx::TypeDesc::isFloat3) + .def("isFloat4", &mx::TypeDesc::isFloat4); +} diff --git a/source/PyMaterialX/PyMaterialXRender/PyExceptionShaderValidationError.cpp b/source/PyMaterialX/PyMaterialXRender/PyExceptionShaderValidationError.cpp deleted file mode 100644 index 3a7adc6e7e..0000000000 --- a/source/PyMaterialX/PyMaterialXRender/PyExceptionShaderValidationError.cpp +++ /dev/null @@ -1,36 +0,0 @@ -// -// TM & (c) 2019 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd. -// All rights reserved. See LICENSE.txt for license. -// - -#include - -#include - -namespace py = pybind11; -namespace mx = MaterialX; - -void bindPyExceptionShaderValidationError(py::module& mod) -{ - static py::exception pyExceptionShaderValidationError(mod, "ExceptionShaderValidationError"); - - py::register_exception_translator( - [](std::exception_ptr errPtr) - { - try - { - if (errPtr != NULL) - std::rethrow_exception(errPtr); - } - catch (const mx::ExceptionShaderValidationError& err) - { - std::string errorMsg = err.what(); - for (std::string error : err.errorLog()) - { - errorMsg += "\n" + error; - } - PyErr_SetString(PyExc_LookupError, errorMsg.c_str()); - } - } - ); -} diff --git a/source/PyMaterialX/PyMaterialXRender/PyModule.cpp b/source/PyMaterialX/PyMaterialXRender/PyModule.cpp index a37cddad82..23d24c962b 100644 --- a/source/PyMaterialX/PyMaterialXRender/PyModule.cpp +++ b/source/PyMaterialX/PyMaterialXRender/PyModule.cpp @@ -20,7 +20,6 @@ void bindPySampleObjLoader(py::module& mod); #endif void bindPyTinyObjLoader(py::module& mod); void bindPyViewHandler(py::module& mod); -void bindPyExceptionShaderValidationError(py::module& mod); void bindPyShaderValidator(py::module& mod); PYBIND11_MODULE(PyMaterialXRender, mod) @@ -40,6 +39,5 @@ PYBIND11_MODULE(PyMaterialXRender, mod) #endif bindPyTinyObjLoader(mod); bindPyViewHandler(mod); - bindPyExceptionShaderValidationError(mod); bindPyShaderValidator(mod); } diff --git a/source/PyMaterialX/PyMaterialXRender/PyShaderValidator.cpp b/source/PyMaterialX/PyMaterialXRender/PyShaderValidator.cpp index bb81ce5706..132722d8dc 100644 --- a/source/PyMaterialX/PyMaterialXRender/PyShaderValidator.cpp +++ b/source/PyMaterialX/PyMaterialXRender/PyShaderValidator.cpp @@ -10,7 +10,6 @@ namespace py = pybind11; namespace mx = MaterialX; - class PyShaderValidator : public mx::ShaderValidator { public: @@ -94,4 +93,26 @@ void bindPyShaderValidator(py::module& mod) .def("validateInputs", &mx::ShaderValidator::validateInputs) .def("validateRender", &mx::ShaderValidator::validateRender) .def("save", &mx::ShaderValidator::save); + + static py::exception pyExceptionShaderValidationError(mod, "ExceptionShaderValidationError"); + + py::register_exception_translator( + [](std::exception_ptr errPtr) + { + try + { + if (errPtr != NULL) + std::rethrow_exception(errPtr); + } + catch (const mx::ExceptionShaderValidationError& err) + { + std::string errorMsg = err.what(); + for (std::string error : err.errorLog()) + { + errorMsg += "\n" + error; + } + PyErr_SetString(PyExc_LookupError, errorMsg.c_str()); + } + } + ); } diff --git a/source/PyMaterialX/PyMaterialXRender/PyViewHandler.cpp b/source/PyMaterialX/PyMaterialXRender/PyViewHandler.cpp index 1dd6545e30..d4840f0f85 100644 --- a/source/PyMaterialX/PyMaterialXRender/PyViewHandler.cpp +++ b/source/PyMaterialX/PyMaterialXRender/PyViewHandler.cpp @@ -14,10 +14,9 @@ void bindPyViewHandler(py::module& mod) { py::class_(mod, "ViewHandler") .def_static("create", &mx::ViewHandler::create) - .def_readonly_static("PI_VALUE", &mx::ViewHandler::PI_VALUE) - .def(py::init<>()) .def_static("createViewMatrix", &mx::ViewHandler::createViewMatrix) .def_static("createPerspectiveMatrix", &mx::ViewHandler::createPerspectiveMatrix) + .def(py::init<>()) .def("setWorldMatrix", &mx::ViewHandler::setWorldMatrix) .def("projectionMatrix", &mx::ViewHandler::projectionMatrix, py::return_value_policy::reference) .def("viewMatrix", &mx::ViewHandler::viewMatrix, py::return_value_policy::reference)